Page MenuHomePhorge

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/plugins/calendar/calendar.php b/plugins/calendar/calendar.php
index 83926a18..5d2965ca 100644
--- a/plugins/calendar/calendar.php
+++ b/plugins/calendar/calendar.php
@@ -1,4047 +1,4047 @@
<?php
/**
* Calendar plugin for Roundcube webmail
*
* @author Lazlo Westerhof <hello@lazlo.me>
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2010, Lazlo Westerhof <hello@lazlo.me>
* Copyright (C) 2014-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 calendar extends rcube_plugin
{
const FREEBUSY_UNKNOWN = 0;
const FREEBUSY_FREE = 1;
const FREEBUSY_BUSY = 2;
const FREEBUSY_TENTATIVE = 3;
const FREEBUSY_OOF = 4;
const SESSION_KEY = 'calendar_temp';
public $task = '?(?!logout).*';
public $rc;
public $lib;
public $resources_dir;
public $home; // declare public to be used in other classes
public $urlbase;
public $timezone;
public $timezone_offset;
public $gmt_offset;
public $ui;
public $defaults = [
'calendar_default_view' => "agendaWeek",
'calendar_timeslots' => 2,
'calendar_work_start' => 6,
'calendar_work_end' => 18,
'calendar_agenda_range' => 60,
'calendar_show_weekno' => 0,
'calendar_first_day' => 1,
'calendar_first_hour' => 6,
'calendar_time_format' => null,
'calendar_event_coloring' => 0,
'calendar_time_indicator' => true,
'calendar_allow_invite_shared' => false,
'calendar_itip_send_option' => 3,
'calendar_itip_after_action' => 0,
];
// These are implemented with __get()
// private $ical;
// private $itip;
// private $driver;
/**
* Plugin initialization.
*/
function init()
{
$this->rc = rcube::get_instance();
$this->register_task('calendar', 'calendar');
// load calendar configuration
$this->load_config();
// catch iTIP confirmation requests that don're require a valid session
if ($this->rc->action == 'attend' && !empty($_REQUEST['_t'])) {
$this->add_hook('startup', [$this, 'itip_attend_response']);
}
else if ($this->rc->action == 'feed' && !empty($_REQUEST['_cal'])) {
$this->add_hook('startup', [$this, 'ical_feed_export']);
}
else if ($this->rc->task != 'login') {
// default startup routine
$this->add_hook('startup', [$this, 'startup']);
}
$this->add_hook('user_delete', [$this, 'user_delete']);
}
/**
* Setup basic plugin environment and UI
*/
protected function setup()
{
$this->require_plugin('libcalendaring');
$this->require_plugin('libkolab');
$this->lib = libcalendaring::get_instance();
$this->timezone = $this->lib->timezone;
$this->gmt_offset = $this->lib->gmt_offset;
$this->dst_active = $this->lib->dst_active;
$this->timezone_offset = $this->gmt_offset / 3600 - $this->dst_active;
// load localizations
$this->add_texts('localization/', $this->rc->task == 'calendar' && (!$this->rc->action || $this->rc->action == 'print'));
require($this->home . '/lib/calendar_ui.php');
$this->ui = new calendar_ui($this);
}
/**
* Startup hook
*/
public function startup($args)
{
// the calendar module can be enabled/disabled by the kolab_auth plugin
if ($this->rc->config->get('calendar_disabled', false)
|| !$this->rc->config->get('calendar_enabled', true)
) {
return;
}
$this->setup();
// load Calendar user interface
if (!$this->rc->output->ajax_call
&& (empty($this->rc->output->env['framed']) || $args['action'] == 'preview')
) {
$this->ui->init();
// settings are required in (almost) every GUI step
if ($args['action'] != 'attend') {
$this->rc->output->set_env('calendar_settings', $this->load_settings());
}
}
if ($args['task'] == 'calendar' && $args['action'] != 'save-pref') {
if ($args['action'] != 'upload') {
$this->load_driver();
}
// register calendar actions
$this->register_action('index', [$this, 'calendar_view']);
$this->register_action('event', [$this, 'event_action']);
$this->register_action('calendar', [$this, 'calendar_action']);
$this->register_action('count', [$this, 'count_events']);
$this->register_action('load_events', [$this, 'load_events']);
$this->register_action('export_events', [$this, 'export_events']);
$this->register_action('import_events', [$this, 'import_events']);
$this->register_action('upload', [$this, 'attachment_upload']);
$this->register_action('get-attachment', [$this, 'attachment_get']);
$this->register_action('freebusy-status', [$this, 'freebusy_status']);
$this->register_action('freebusy-times', [$this, 'freebusy_times']);
$this->register_action('randomdata', [$this, 'generate_randomdata']);
$this->register_action('print', [$this,'print_view']);
$this->register_action('mailimportitip', [$this, 'mail_import_itip']);
$this->register_action('mailimportattach', [$this, 'mail_import_attachment']);
$this->register_action('dialog-ui', [$this, 'mail_message2event']);
$this->register_action('check-recent', [$this, 'check_recent']);
$this->register_action('itip-status', [$this, 'event_itip_status']);
$this->register_action('itip-remove', [$this, 'event_itip_remove']);
$this->register_action('itip-decline-reply', [$this, 'mail_itip_decline_reply']);
$this->register_action('itip-delegate', [$this, 'mail_itip_delegate']);
$this->register_action('resources-list', [$this, 'resources_list']);
$this->register_action('resources-owner', [$this, 'resources_owner']);
$this->register_action('resources-calendar', [$this, 'resources_calendar']);
$this->register_action('resources-autocomplete', [$this, 'resources_autocomplete']);
$this->register_action('talk-room-create', [$this, 'talk_room_create']);
$this->add_hook('refresh', [$this, 'refresh']);
// remove undo information...
if (!empty($_SESSION['calendar_event_undo'])) {
$undo = $_SESSION['calendar_event_undo'];
// ...after timeout
$undo_time = $this->rc->config->get('undo_timeout', 0);
if ($undo['ts'] < time() - $undo_time) {
$this->rc->session->remove('calendar_event_undo');
// @TODO: do EXPUNGE on kolab objects?
}
}
}
else if ($args['task'] == 'settings') {
// add hooks for Calendar settings
$this->add_hook('preferences_sections_list', [$this, 'preferences_sections_list']);
$this->add_hook('preferences_list', [$this, 'preferences_list']);
$this->add_hook('preferences_save', [$this, 'preferences_save']);
}
else if ($args['task'] == 'mail') {
// hooks to catch event invitations on incoming mails
if ($args['action'] == 'show' || $args['action'] == 'preview') {
$this->add_hook('template_object_messagebody', [$this, 'mail_messagebody_html']);
}
// add 'Create event' item to message menu
if ($this->api->output->type == 'html' && (empty($_GET['_rel']) || $_GET['_rel'] != 'event')) {
$this->api->output->add_label('calendar.createfrommail');
$this->api->add_content(
html::tag('li', ['role' => 'menuitem'],
$this->api->output->button([
'command' => 'calendar-create-from-mail',
'label' => 'calendar.createfrommail',
'type' => 'link',
'classact' => 'icon calendarlink active',
'class' => 'icon calendarlink disabled',
'innerclass' => 'icon calendar',
])
),
'messagemenu'
);
}
$this->add_hook('messages_list', [$this, 'mail_messages_list']);
$this->add_hook('message_compose', [$this, 'mail_message_compose']);
}
else if ($args['task'] == 'addressbook') {
if ($this->rc->config->get('calendar_contact_birthdays')) {
$this->add_hook('contact_update', [$this, 'contact_update']);
$this->add_hook('contact_create', [$this, 'contact_update']);
}
}
// add hooks to display alarms
$this->add_hook('pending_alarms', [$this, 'pending_alarms']);
$this->add_hook('dismiss_alarms', [$this, 'dismiss_alarms']);
}
/**
* Helper method to load the backend driver according to local config
*/
private function load_driver()
{
if (!empty($this->driver)) {
return;
}
$driver_name = $this->rc->config->get('calendar_driver', 'database');
$driver_class = $driver_name . '_driver';
require_once($this->home . '/drivers/calendar_driver.php');
require_once($this->home . '/drivers/' . $driver_name . '/' . $driver_class . '.php');
$this->driver = new $driver_class($this);
if ($this->driver->undelete) {
$this->driver->undelete = $this->rc->config->get('undo_timeout', 0) > 0;
}
}
/**
* Load iTIP functions
*/
private function load_itip()
{
if (empty($this->itip)) {
require_once($this->home . '/lib/calendar_itip.php');
$this->itip = new calendar_itip($this);
if ($this->rc->config->get('kolab_invitation_calendars')) {
$this->itip->set_rsvp_actions(['accepted','tentative','declined','delegated','needs-action']);
}
}
return $this->itip;
}
/**
* Load iCalendar functions
*/
public function get_ical()
{
if (empty($this->ical)) {
$this->ical = libcalendaring::get_ical();
}
return $this->ical;
}
/**
* Get properties of the calendar this user has specified as default
*/
public function get_default_calendar($calendars = null)
{
if ($calendars === null) {
$filter = calendar_driver::FILTER_PERSONAL | calendar_driver::FILTER_WRITEABLE;
$calendars = $this->driver->list_calendars($filter);
}
$default_id = $this->rc->config->get('calendar_default_calendar');
$calendar = !empty($calendars[$default_id]) ? $calendars[$default_id] : null;
$first = null;
if (!$calendar) {
foreach ($calendars as $cal) {
if (!empty($cal['default']) && $cal['editable']) {
$calendar = $cal;
}
if ($cal['editable']) {
$first = $cal;
}
}
}
return $calendar ?: $first;
}
/**
* Render the main calendar view from skin template
*/
function calendar_view()
{
$this->rc->output->set_pagetitle($this->gettext('calendar'));
// Add JS files to the page header
$this->ui->addJS();
$this->ui->init_templates();
$this->rc->output->add_label('lowest','low','normal','high','highest','delete',
'cancel','uploading','noemailwarning','close'
);
// initialize attendees autocompletion
$this->rc->autocomplete_init();
$this->rc->output->set_env('timezone', $this->timezone->getName());
$this->rc->output->set_env('calendar_driver', $this->rc->config->get('calendar_driver'), false);
$this->rc->output->set_env('calendar_resources', (bool)$this->rc->config->get('calendar_resources_driver'));
$this->rc->output->set_env('identities-selector', $this->ui->identity_select([
'id' => 'edit-identities-list',
'aria-label' => $this->gettext('roleorganizer'),
'class' => 'form-control custom-select',
]));
$view = rcube_utils::get_input_value('view', rcube_utils::INPUT_GPC);
if (in_array($view, ['agendaWeek', 'agendaDay', 'month', 'list'])) {
$this->rc->output->set_env('view', $view);
}
if ($date = rcube_utils::get_input_value('date', rcube_utils::INPUT_GPC)) {
$this->rc->output->set_env('date', $date);
}
if ($msgref = rcube_utils::get_input_value('itip', rcube_utils::INPUT_GPC)) {
$this->rc->output->set_env('itip_events', $this->itip_events($msgref));
}
$this->rc->output->send('calendar.calendar');
}
/**
* Handler for preferences_sections_list hook.
* Adds Calendar settings sections into preferences sections list.
*
* @param array Original parameters
*
* @return array Modified parameters
*/
function preferences_sections_list($p)
{
$p['list']['calendar'] = [
'id' => 'calendar',
'section' => $this->gettext('calendar'),
];
return $p;
}
/**
* Handler for preferences_list hook.
* Adds options blocks into Calendar settings sections in Preferences.
*
* @param array Original parameters
*
* @return array Modified parameters
*/
function preferences_list($p)
{
if ($p['section'] != 'calendar') {
return $p;
}
$no_override = array_flip((array) $this->rc->config->get('dont_override'));
$p['blocks']['view']['name'] = $this->gettext('mainoptions');
if (!isset($no_override['calendar_default_view'])) {
if (empty($p['current'])) {
$p['blocks']['view']['content'] = true;
return $p;
}
$field_id = 'rcmfd_default_view';
$view = $this->rc->config->get('calendar_default_view', $this->defaults['calendar_default_view']);
$select = new html_select(['name' => '_default_view', 'id' => $field_id]);
$select->add($this->gettext('day'), "agendaDay");
$select->add($this->gettext('week'), "agendaWeek");
$select->add($this->gettext('month'), "month");
$select->add($this->gettext('agenda'), "list");
$p['blocks']['view']['options']['default_view'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('default_view'))),
'content' => $select->show($view == 'table' ? 'list' : $view),
];
}
if (!isset($no_override['calendar_timeslots'])) {
if (empty($p['current'])) {
$p['blocks']['view']['content'] = true;
return $p;
}
$field_id = 'rcmfd_timeslots';
$choices = ['1', '2', '3', '4', '6'];
$timeslots = $this->rc->config->get('calendar_timeslots', $this->defaults['calendar_timeslots']);
$select = new html_select(['name' => '_timeslots', 'id' => $field_id]);
$select->add($choices, $choices);
$p['blocks']['view']['options']['timeslots'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('timeslots'))),
'content' => $select->show(strval($timeslots)),
];
}
if (!isset($no_override['calendar_first_day'])) {
if (empty($p['current'])) {
$p['blocks']['view']['content'] = true;
return $p;
}
$field_id = 'rcmfd_firstday';
$first_day = $this->rc->config->get('calendar_first_day', $this->defaults['calendar_first_day']);
$select = new html_select(['name' => '_first_day', 'id' => $field_id]);
$select->add($this->gettext('sunday'), '0');
$select->add($this->gettext('monday'), '1');
$select->add($this->gettext('tuesday'), '2');
$select->add($this->gettext('wednesday'), '3');
$select->add($this->gettext('thursday'), '4');
$select->add($this->gettext('friday'), '5');
$select->add($this->gettext('saturday'), '6');
$p['blocks']['view']['options']['first_day'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('first_day'))),
'content' => $select->show(strval($first_day)),
];
}
if (!isset($no_override['calendar_first_hour'])) {
if (empty($p['current'])) {
$p['blocks']['view']['content'] = true;
return $p;
}
$first_hour = $this->rc->config->get('calendar_first_hour', $this->defaults['calendar_first_hour']);
$time_format = $this->rc->config->get('calendar_time_format', $this->defaults['calendar_time_format']);
$time_format = $this->rc->config->get('time_format', libcalendaring::to_php_date_format($time_format));
$field_id = 'rcmfd_firsthour';
$select_hours = new html_select(['name' => '_first_hour', 'id' => $field_id]);
for ($h = 0; $h < 24; $h++) {
$select_hours->add(date($time_format, mktime($h, 0, 0)), $h);
}
$p['blocks']['view']['options']['first_hour'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('first_hour'))),
'content' => $select_hours->show($first_hour),
];
}
if (!isset($no_override['calendar_work_start'])) {
if (empty($p['current'])) {
$p['blocks']['view']['content'] = true;
return $p;
}
$field_id = 'rcmfd_workstart';
$work_start = $this->rc->config->get('calendar_work_start', $this->defaults['calendar_work_start']);
$work_end = $this->rc->config->get('calendar_work_end', $this->defaults['calendar_work_end']);
$p['blocks']['view']['options']['workinghours'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('workinghours'))),
'content' => html::div('input-group',
$select_hours->show($work_start, ['name' => '_work_start', 'id' => $field_id])
. html::span('input-group-append input-group-prepend', html::span('input-group-text',' &mdash; '))
. $select_hours->show($work_end, ['name' => '_work_end', 'id' => $field_id])
)
];
}
if (!isset($no_override['calendar_event_coloring'])) {
if (empty($p['current'])) {
$p['blocks']['view']['content'] = true;
return $p;
}
$field_id = 'rcmfd_coloring';
$mode = $this->rc->config->get('calendar_event_coloring', $this->defaults['calendar_event_coloring']);
$select_colors = new html_select(['name' => '_event_coloring', 'id' => $field_id]);
$select_colors->add($this->gettext('coloringmode0'), 0);
$select_colors->add($this->gettext('coloringmode1'), 1);
$select_colors->add($this->gettext('coloringmode2'), 2);
$select_colors->add($this->gettext('coloringmode3'), 3);
$p['blocks']['view']['options']['eventcolors'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('eventcoloring'))),
'content' => $select_colors->show($mode),
];
}
// loading driver is expensive, don't do it if not needed
$this->load_driver();
if (!isset($no_override['calendar_default_alarm_type']) || !isset($no_override['calendar_default_alarm_offset'])) {
if (empty($p['current'])) {
$p['blocks']['view']['content'] = true;
return $p;
}
$alarm_type = $alarm_offset = '';
if (!isset($no_override['calendar_default_alarm_type'])) {
$field_id = 'rcmfd_alarm';
$select_type = new html_select(['name' => '_alarm_type', 'id' => $field_id]);
$select_type->add($this->gettext('none'), '');
foreach ($this->driver->alarm_types as $type) {
$select_type->add($this->rc->gettext(strtolower("alarm{$type}option"), 'libcalendaring'), $type);
}
$alarm_type = $select_type->show($this->rc->config->get('calendar_default_alarm_type', ''));
}
if (!isset($no_override['calendar_default_alarm_offset'])) {
$field_id = 'rcmfd_alarm';
$input_value = new html_inputfield(['name' => '_alarm_value', 'id' => $field_id . 'value', 'size' => 3]);
$select_offset = new html_select(['name' => '_alarm_offset', 'id' => $field_id . 'offset']);
foreach (['-M','-H','-D','+M','+H','+D'] as $trigger) {
$select_offset->add($this->rc->gettext('trigger' . $trigger, 'libcalendaring'), $trigger);
}
$preset = libcalendaring::parse_alarm_value($this->rc->config->get('calendar_default_alarm_offset', '-15M'));
$alarm_offset = $input_value->show($preset[0]) . ' ' . $select_offset->show($preset[1]);
}
$p['blocks']['view']['options']['alarmtype'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('defaultalarmtype'))),
'content' => html::div('input-group', $alarm_type . ' ' . $alarm_offset),
];
}
if (!isset($no_override['calendar_default_calendar'])) {
if (empty($p['current'])) {
$p['blocks']['view']['content'] = true;
return $p;
}
// default calendar selection
$field_id = 'rcmfd_default_calendar';
$filter = calendar_driver::FILTER_PERSONAL | calendar_driver::FILTER_ACTIVE | calendar_driver::FILTER_INSERTABLE;
$select_cal = new html_select(['name' => '_default_calendar', 'id' => $field_id, 'is_escaped' => true]);
$default_calendar = null;
foreach ((array) $this->driver->list_calendars($filter) as $id => $prop) {
$select_cal->add($prop['name'], strval($id));
if (!empty($prop['default'])) {
$default_calendar = $id;
}
}
$p['blocks']['view']['options']['defaultcalendar'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('defaultcalendar'))),
'content' => $select_cal->show($this->rc->config->get('calendar_default_calendar', $default_calendar)),
];
}
if (!isset($no_override['calendar_show_weekno'])) {
if (empty($p['current'])) {
$p['blocks']['view']['content'] = true;
return $p;
}
$field_id = 'rcmfd_show_weekno';
$select = new html_select(['name' => '_show_weekno', 'id' => $field_id]);
$select->add($this->gettext('weeknonone'), -1);
$select->add($this->gettext('weeknodatepicker'), 0);
$select->add($this->gettext('weeknoall'), 1);
$p['blocks']['view']['options']['show_weekno'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('showweekno'))),
'content' => $select->show(intval($this->rc->config->get('calendar_show_weekno'))),
];
}
$p['blocks']['itip']['name'] = $this->gettext('itipoptions');
// Invitations handling
if (!isset($no_override['calendar_itip_after_action'])) {
if (empty($p['current'])) {
$p['blocks']['itip']['content'] = true;
return $p;
}
$field_id = 'rcmfd_after_action';
$select = new html_select([
'name' => '_after_action',
'id' => $field_id,
'onchange' => "\$('#{$field_id}_select')[this.value == 4 ? 'show' : 'hide']()"
]);
$select->add($this->gettext('afternothing'), '');
$select->add($this->gettext('aftertrash'), 1);
$select->add($this->gettext('afterdelete'), 2);
$select->add($this->gettext('afterflagdeleted'), 3);
$select->add($this->gettext('aftermoveto'), 4);
$val = $this->rc->config->get('calendar_itip_after_action', $this->defaults['calendar_itip_after_action']);
$folder = null;
if ($val !== null && $val !== '' && !is_int($val)) {
$folder = $val;
$val = 4;
}
$folders = $this->rc->folder_selector([
'id' => $field_id . '_select',
'name' => '_after_action_folder',
'maxlength' => 30,
'folder_filter' => 'mail',
'folder_rights' => 'w',
'style' => $val !== 4 ? 'display:none' : '',
]);
$p['blocks']['itip']['options']['after_action'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('afteraction'))),
'content' => html::div(
'input-group input-group-combo',
$select->show($val) . $folders->show($folder)
),
];
}
// category definitions
if (empty($this->driver->nocategories) && !isset($no_override['calendar_categories'])) {
$p['blocks']['categories']['name'] = $this->gettext('categories');
if (empty($p['current'])) {
$p['blocks']['categories']['content'] = true;
return $p;
}
$categories = (array) $this->driver->list_categories();
$categories_list = '';
foreach ($categories as $name => $color) {
$key = md5($name);
$field_class = 'rcmfd_category_' . str_replace(' ', '_', $name);
$category_remove = html::span('input-group-append',
html::a([
'class' => 'button icon delete input-group-text',
'onclick' => '$(this).parent().parent().remove()',
'title' => $this->gettext('remove_category'),
'href' => '#rcmfd_new_category',
],
html::span('inner', $this->gettext('delete'))
)
);
$category_name = new html_inputfield(array('name' => "_categories[$key]", 'class' => $field_class, 'size' => 30, 'disabled' => $this->driver->categoriesimmutable));
$category_color = new html_inputfield(array('name' => "_colors[$key]", 'class' => "$field_class colors", 'size' => 6));
$hidden = '';
if (!empty($this->driver->categoriesimmutable)) {
$hidden = html::tag('input', ['type' => 'hidden', 'name' => "_categories[$key]", 'value' => $name]);
}
$categories_list .= $hidden
. html::div('input-group', $category_name->show($name) . $category_color->show($color) . $category_remove);
}
$p['blocks']['categories']['options']['category_' . $name] = [
'content' => html::div(['id' => 'calendarcategories'], $categories_list),
];
$field_id = 'rcmfd_new_category';
$new_category = new html_inputfield(['name' => '_new_category', 'id' => $field_id, 'size' => 30]);
$add_category = html::span('input-group-append',
html::a(
[
'type' => 'button',
'class' => 'button create input-group-text',
'title' => $this->gettext('add_category'),
'onclick' => 'rcube_calendar_add_category()',
'href' => '#rcmfd_new_category',
],
html::span('inner', $this->gettext('add_category'))
)
);
$p['blocks']['categories']['options']['categories'] = [
'content' => html::div('input-group', $new_category->show('') . $add_category),
];
$this->rc->output->add_label('delete', 'calendar.remove_category');
$this->rc->output->add_script('
function rcube_calendar_add_category() {
var name = $("#rcmfd_new_category").val();
if (name.length) {
var button_label = rcmail.gettext("calendar.remove_category");
var input = $("<input>").attr({type: "text", name: "_categories[]", size: 30, "class": "form-control"}).val(name);
var color = $("<input>").attr({type: "text", name: "_colors[]", size: 6, "class": "colors form-control"}).val("000000");
var button = $("<a>").attr({"class": "button icon delete input-group-text", title: button_label, href: "#rcmfd_new_category"})
.click(function() { $(this).parent().parent().remove(); })
.append($("<span>").addClass("inner").text(rcmail.gettext("delete")));
$("<div>").addClass("input-group").append(input).append(color).append($("<span class=\'input-group-append\'>").append(button))
.appendTo("#calendarcategories");
color.minicolors(rcmail.env.minicolors_config || {});
$("#rcmfd_new_category").val("");
}
}',
'foot'
);
$this->rc->output->add_script('
$("#rcmfd_new_category").keypress(function(event) {
if (event.which == 13) {
rcube_calendar_add_category();
event.preventDefault();
}
});',
'docready'
);
// load miniColors js/css files
jqueryui::miniColors();
}
// virtual birthdays calendar
if (!isset($no_override['calendar_contact_birthdays'])) {
$p['blocks']['birthdays']['name'] = $this->gettext('birthdayscalendar');
if (empty($p['current'])) {
$p['blocks']['birthdays']['content'] = true;
return $p;
}
$field_id = 'rcmfd_contact_birthdays';
$input = new html_checkbox([
'name' => '_contact_birthdays',
'id' => $field_id,
'value' => 1,
'onclick' => '$(".calendar_birthday_props").prop("disabled",!this.checked)'
]);
$p['blocks']['birthdays']['options']['contact_birthdays'] = [
'title' => html::label($field_id, $this->gettext('displaybirthdayscalendar')),
'content' => $input->show($this->rc->config->get('calendar_contact_birthdays') ? 1 : 0),
];
$input_attrib = [
'class' => 'calendar_birthday_props',
'disabled' => !$this->rc->config->get('calendar_contact_birthdays'),
];
$sources = [];
$checkbox = new html_checkbox(['name' => '_birthday_adressbooks[]'] + $input_attrib);
foreach ($this->rc->get_address_sources(false, true) as $source) {
// Roundcube >= 1.5, Ignore Collected Recipients and Trusted Senders sources
if ((defined('rcube_addressbook::TYPE_RECIPIENT') && $source['id'] == (string) rcube_addressbook::TYPE_RECIPIENT)
|| (defined('rcube_addressbook::TYPE_TRUSTED_SENDER') && $source['id'] == (string) rcube_addressbook::TYPE_TRUSTED_SENDER)
) {
continue;
}
$active = in_array($source['id'], (array) $this->rc->config->get('calendar_birthday_adressbooks')) ? $source['id'] : '';
$sources[] = html::tag('li', null,
html::label(null,
$checkbox->show($active, ['value' => $source['id']])
. rcube::Q(!empty($source['realname']) ? $source['realname'] : $source['name'])
)
);
}
$p['blocks']['birthdays']['options']['birthday_adressbooks'] = [
'title' => rcube::Q($this->gettext('birthdayscalendarsources')),
'content' => html::tag('ul', 'proplist', implode("\n", $sources)),
];
$field_id = 'rcmfd_birthdays_alarm';
$select_type = new html_select(['name' => '_birthdays_alarm_type', 'id' => $field_id] + $input_attrib);
$select_type->add($this->gettext('none'), '');
foreach ($this->driver->alarm_types as $type) {
$select_type->add($this->rc->gettext(strtolower("alarm{$type}option"), 'libcalendaring'), $type);
}
$input_value = new html_inputfield(['name' => '_birthdays_alarm_value', 'id' => $field_id . 'value', 'size' => 3] + $input_attrib);
$select_offset = new html_select(['name' => '_birthdays_alarm_offset', 'id' => $field_id . 'offset'] + $input_attrib);
foreach (['-M','-H','-D'] as $trigger) {
$select_offset->add($this->rc->gettext('trigger' . $trigger, 'libcalendaring'), $trigger);
}
$preset = libcalendaring::parse_alarm_value($this->rc->config->get('calendar_birthdays_alarm_offset', '-1D'));
$preset_type = $this->rc->config->get('calendar_birthdays_alarm_type', '');
$p['blocks']['birthdays']['options']['birthdays_alarmoffset'] = [
'title' => html::label($field_id, rcube::Q($this->gettext('showalarms'))),
'content' => html::div('input-group',
$select_type->show($preset_type)
. $input_value->show($preset[0]) . ' ' . $select_offset->show($preset[1])
),
];
}
return $p;
}
/**
* Handler for preferences_save hook.
* Executed on Calendar settings form submit.
*
* @param array Original parameters
*
* @return array Modified parameters
*/
function preferences_save($p)
{
if ($p['section'] == 'calendar') {
$this->load_driver();
// compose default alarm preset value
$alarm_offset = rcube_utils::get_input_value('_alarm_offset', rcube_utils::INPUT_POST);
$alarm_value = rcube_utils::get_input_value('_alarm_value', rcube_utils::INPUT_POST);
$default_alarm = $alarm_offset[0] . intval($alarm_value) . $alarm_offset[1];
$birthdays_alarm_offset = rcube_utils::get_input_value('_birthdays_alarm_offset', rcube_utils::INPUT_POST);
$birthdays_alarm_value = rcube_utils::get_input_value('_birthdays_alarm_value', rcube_utils::INPUT_POST);
$birthdays_alarm_value = $birthdays_alarm_offset[0] . intval($birthdays_alarm_value) . $birthdays_alarm_offset[1];
$p['prefs'] = [
'calendar_default_view' => rcube_utils::get_input_value('_default_view', rcube_utils::INPUT_POST),
'calendar_timeslots' => intval(rcube_utils::get_input_value('_timeslots', rcube_utils::INPUT_POST)),
'calendar_first_day' => intval(rcube_utils::get_input_value('_first_day', rcube_utils::INPUT_POST)),
'calendar_first_hour' => intval(rcube_utils::get_input_value('_first_hour', rcube_utils::INPUT_POST)),
'calendar_work_start' => intval(rcube_utils::get_input_value('_work_start', rcube_utils::INPUT_POST)),
'calendar_work_end' => intval(rcube_utils::get_input_value('_work_end', rcube_utils::INPUT_POST)),
'calendar_show_weekno' => intval(rcube_utils::get_input_value('_show_weekno', rcube_utils::INPUT_POST)),
'calendar_event_coloring' => intval(rcube_utils::get_input_value('_event_coloring', rcube_utils::INPUT_POST)),
'calendar_default_alarm_type' => rcube_utils::get_input_value('_alarm_type', rcube_utils::INPUT_POST),
'calendar_default_alarm_offset' => $default_alarm,
'calendar_default_calendar' => rcube_utils::get_input_value('_default_calendar', rcube_utils::INPUT_POST),
'calendar_date_format' => null, // clear previously saved values
'calendar_time_format' => null,
'calendar_contact_birthdays' => (bool) rcube_utils::get_input_value('_contact_birthdays', rcube_utils::INPUT_POST),
'calendar_birthday_adressbooks' => (array) rcube_utils::get_input_value('_birthday_adressbooks', rcube_utils::INPUT_POST),
'calendar_birthdays_alarm_type' => rcube_utils::get_input_value('_birthdays_alarm_type', rcube_utils::INPUT_POST),
'calendar_birthdays_alarm_offset' => $birthdays_alarm_value ?: null,
'calendar_itip_after_action' => intval(rcube_utils::get_input_value('_after_action', rcube_utils::INPUT_POST)),
];
if ($p['prefs']['calendar_itip_after_action'] == 4) {
$p['prefs']['calendar_itip_after_action'] = rcube_utils::get_input_value('_after_action_folder', rcube_utils::INPUT_POST, true);
}
// categories
if (empty($this->driver->nocategories)) {
$old_categories = $new_categories = [];
foreach ($this->driver->list_categories() as $name => $color) {
$old_categories[md5($name)] = $name;
}
$categories = (array) rcube_utils::get_input_value('_categories', rcube_utils::INPUT_POST);
$colors = (array) rcube_utils::get_input_value('_colors', rcube_utils::INPUT_POST);
foreach ($categories as $key => $name) {
if (!isset($colors[$key])) {
continue;
}
$color = preg_replace('/^#/', '', strval($colors[$key]));
// rename categories in existing events -> driver's job
if (!empty($old_categories[$key])) {
$oldname = $old_categories[$key];
$this->driver->replace_category($oldname, $name, $color);
unset($old_categories[$key]);
}
else {
$this->driver->add_category($name, $color);
}
$new_categories[$name] = $color;
}
// these old categories have been removed, alter events accordingly -> driver's job
foreach ((array) $old_categories as $key => $name) {
$this->driver->remove_category($name);
}
$p['prefs']['calendar_categories'] = $new_categories;
}
}
return $p;
}
/**
* Dispatcher for calendar actions initiated by the client
*/
function calendar_action()
{
$action = rcube_utils::get_input_value('action', rcube_utils::INPUT_GPC);
$cal = rcube_utils::get_input_value('c', rcube_utils::INPUT_GPC);
$success = false;
$reload = false;
if (isset($cal['showalarms'])) {
$cal['showalarms'] = intval($cal['showalarms']);
}
switch ($action) {
case "form-new":
case "form-edit":
echo $this->ui->calendar_editform($action, $cal);
exit;
case "new":
$success = $this->driver->create_calendar($cal);
$reload = true;
break;
case "edit":
$success = $this->driver->edit_calendar($cal);
$reload = true;
break;
case "delete":
if ($success = $this->driver->delete_calendar($cal)) {
$this->rc->output->command('plugin.destroy_source', ['id' => $cal['id']]);
}
break;
case "subscribe":
if (!$this->driver->subscribe_calendar($cal)) {
$this->rc->output->show_message($this->gettext('errorsaving'), 'error');
}
else {
$calendars = $this->driver->list_calendars();
$calendar = !empty($calendars[$cal['id']]) ? $calendars[$cal['id']] : null;
// find parent folder and check if it's a "user calendar"
// if it's also activated we need to refresh it (#5340)
while (!empty($calendar['parent'])) {
if (isset($calendars[$calendar['parent']])) {
$calendar = $calendars[$calendar['parent']];
}
else {
break;
}
}
if ($calendar && $calendar['id'] != $cal['id']
&& !empty($calendar['active'])
&& $calendar['group'] == "other user"
) {
$this->rc->output->command('plugin.refresh_source', $calendar['id']);
}
}
return;
case "search":
$results = [];
$color_mode = $this->rc->config->get('calendar_event_coloring', $this->defaults['calendar_event_coloring']);
$query = rcube_utils::get_input_value('q', rcube_utils::INPUT_GPC);
$source = rcube_utils::get_input_value('source', rcube_utils::INPUT_GPC);
foreach ((array) $this->driver->search_calendars($query, $source) as $id => $prop) {
$editname = $prop['editname'];
unset($prop['editname']); // force full name to be displayed
$prop['active'] = false;
// let the UI generate HTML and CSS representation for this calendar
$html = $this->ui->calendar_list_item($id, $prop, $jsenv);
$cal = $jsenv[$id];
$cal['editname'] = $editname;
$cal['html'] = $html;
if (!empty($prop['color'])) {
$cal['css'] = $this->ui->calendar_css_classes($id, $prop, $color_mode);
}
$results[] = $cal;
}
// report more results available
if (!empty($this->driver->search_more_results)) {
$this->rc->output->show_message('autocompletemore', 'notice');
}
$reqid = rcube_utils::get_input_value('_reqid', rcube_utils::INPUT_GPC);
$this->rc->output->command('multi_thread_http_response', $results, $reqid);
return;
}
if ($success) {
$this->rc->output->show_message('successfullysaved', 'confirmation');
}
else {
$error_msg = $this->gettext('errorsaving');
if (!empty($this->driver->last_error)) {
$error_msg .= ': ' . $this->driver->last_error;
}
$this->rc->output->show_message($error_msg, 'error');
}
$this->rc->output->command('plugin.unlock_saving');
if ($success && $reload) {
$this->rc->output->command('plugin.reload_view');
}
}
/**
* Dispatcher for event actions initiated by the client
*/
function event_action()
{
$action = rcube_utils::get_input_value('action', rcube_utils::INPUT_GPC);
$event = rcube_utils::get_input_value('e', rcube_utils::INPUT_POST, true);
$success = $reload = $got_msg = false;
$old = null;
// read old event data in order to find changes
if ((!empty($event['_notify']) || !empty($event['_decline'])) && $action != 'new') {
$old = $this->driver->get_event($event);
// load main event if savemode is 'all' or if deleting 'future' events
if (($event['_savemode'] == 'all' || ($event['_savemode'] == 'future' && $action == 'remove' && empty($event['_decline'])))
&& !empty($old['recurrence_id'])
) {
$old['id'] = $old['recurrence_id'];
$old = $this->driver->get_event($old);
}
}
switch ($action) {
case "new":
// create UID for new event
$event['uid'] = $this->generate_uid();
if (!$this->write_preprocess($event, $action)) {
$got_msg = true;
}
else if ($success = $this->driver->new_event($event)) {
$event['id'] = $event['uid'];
$event['_savemode'] = 'all';
$this->cleanup_event($event);
$this->event_save_success($event, null, $action, true);
$this->talk_room_update($event);
}
$reload = $success && !empty($event['recurrence']) ? 2 : 1;
break;
case "edit":
if (!$this->write_preprocess($event, $action)) {
$got_msg = true;
}
else if ($success = $this->driver->edit_event($event)) {
$this->cleanup_event($event);
$this->event_save_success($event, $old, $action, $success);
$this->talk_room_update($event);
}
$reload = $success && (!empty($event['recurrence']) || !empty($event['_savemode']) || !empty($event['_fromcalendar'])) ? 2 : 1;
break;
case "resize":
if (!$this->write_preprocess($event, $action)) {
$got_msg = true;
}
else if ($success = $this->driver->resize_event($event)) {
$this->event_save_success($event, $old, $action, $success);
}
$reload = !empty($event['_savemode']) ? 2 : 1;
break;
case "move":
if (!$this->write_preprocess($event, $action)) {
$got_msg = true;
}
else if ($success = $this->driver->move_event($event)) {
$this->event_save_success($event, $old, $action, $success);
}
$reload = $success && !empty($event['_savemode']) ? 2 : 1;
break;
case "remove":
// remove previous deletes
$undo_time = $this->driver->undelete ? $this->rc->config->get('undo_timeout', 0) : 0;
// search for event if only UID is given
if (!isset($event['calendar']) && !empty($event['uid'])) {
if (!($event = $this->driver->get_event($event, calendar_driver::FILTER_WRITEABLE))) {
break;
}
$undo_time = 0;
}
// Note: the driver is responsible for setting $_SESSION['calendar_event_undo']
// containing 'ts' and 'data' elements
$success = $this->driver->remove_event($event, $undo_time < 1);
$reload = (!$success || !empty($event['_savemode'])) ? 2 : 1;
if ($undo_time > 0 && $success) {
// display message with Undo link.
$onclick = sprintf("%s.http_request('event', 'action=undo', %s.display_message('', 'loading'))",
rcmail_output::JS_OBJECT_NAME,
rcmail_output::JS_OBJECT_NAME
);
$msg = html::span(null, $this->gettext('successremoval'))
. ' ' . html::a(['onclick' => $onclick], $this->gettext('undo'));
$this->rc->output->show_message($msg, 'confirmation', null, true, $undo_time);
$got_msg = true;
}
else if ($success) {
$this->rc->output->show_message('calendar.successremoval', 'confirmation');
$got_msg = true;
}
// send cancellation for the main event
if ($event['_savemode'] == 'all') {
unset($old['_instance'], $old['recurrence_date'], $old['recurrence_id']);
}
// send an update for the main event's recurrence rule instead of a cancellation message
else if ($event['_savemode'] == 'future' && $success !== false && $success !== true) {
$event['_savemode'] = 'all'; // force event_save_success() to load master event
$action = 'edit';
$success = true;
}
// send iTIP reply that participant has declined the event
if ($success && !empty($event['_decline'])) {
$emails = $this->get_user_emails();
$organizer = null;
foreach ($old['attendees'] as $i => $attendee) {
if ($attendee['role'] == 'ORGANIZER') {
$organizer = $attendee;
}
else if (!empty($attendee['email']) && in_array(strtolower($attendee['email']), $emails)) {
$old['attendees'][$i]['status'] = 'DECLINED';
$reply_sender = $attendee['email'];
}
}
if ($event['_savemode'] == 'future' && $event['id'] != $old['id']) {
$old['thisandfuture'] = true;
}
$itip = $this->load_itip();
$itip->set_sender_email($reply_sender);
if ($organizer && $itip->send_itip_message($old, 'REPLY', $organizer, 'itipsubjectdeclined', 'itipmailbodydeclined')) {
$mailto = !empty($organizer['name']) ? $organizer['name'] : $organizer['email'];
$msg = $this->gettext(['name' => 'sentresponseto', 'vars' => ['mailto' => $mailto]]);
$this->rc->output->command('display_message', $msg, 'confirmation');
}
else {
$this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
}
}
else if ($success) {
$this->event_save_success($event, $old, $action, $success);
}
break;
case "undo":
// Restore deleted event
if (!empty($_SESSION['calendar_event_undo']['data'])) {
$event = $_SESSION['calendar_event_undo']['data'];
$success = $this->driver->restore_event($event);
}
if ($success) {
$this->rc->session->remove('calendar_event_undo');
$this->rc->output->show_message('calendar.successrestore', 'confirmation');
$got_msg = true;
$reload = 2;
}
break;
case "rsvp":
$itip_sending = $this->rc->config->get('calendar_itip_send_option', $this->defaults['calendar_itip_send_option']);
$status = rcube_utils::get_input_value('status', rcube_utils::INPUT_POST);
$attendees = rcube_utils::get_input_value('attendees', rcube_utils::INPUT_POST);
$reply_comment = $event['comment'];
$this->write_preprocess($event, 'edit');
$ev = $this->driver->get_event($event);
$ev['attendees'] = $event['attendees'];
$ev['free_busy'] = $event['free_busy'];
$ev['_savemode'] = $event['_savemode'];
$ev['comment'] = $reply_comment;
// send invitation to delegatee + add it as attendee
if ($status == 'delegated' && !empty($event['to'])) {
$itip = $this->load_itip();
if ($itip->delegate_to($ev, $event['to'], !empty($event['rsvp']), $attendees)) {
$this->rc->output->show_message('calendar.itipsendsuccess', 'confirmation');
$noreply = false;
}
}
$event = $ev;
// compose a list of attendees affected by this change
$updated_attendees = array_filter(array_map(function($j) use ($event) {
return $event['attendees'][$j];
},
$attendees
));
if ($success = $this->driver->edit_rsvp($event, $status, $updated_attendees)) {
$noreply = rcube_utils::get_input_value('noreply', rcube_utils::INPUT_GPC);
$noreply = intval($noreply) || $status == 'needs-action' || $itip_sending === 0;
$reload = $event['calendar'] != $ev['calendar'] || !empty($event['recurrence']) ? 2 : 1;
$emails = $this->get_user_emails();
$ownedResourceEmails = $this->owned_resources_emails();
$organizer = null;
$resourceConfirmation = false;
foreach ($event['attendees'] as $i => $attendee) {
if ($attendee['role'] == 'ORGANIZER') {
$organizer = $attendee;
}
else if (!empty($attendee['email']) && in_array_nocase($attendee['email'], $emails)) {
$reply_sender = $attendee['email'];
}
else if (!empty($attendee['cutype']) && $attendee['cutype'] == 'RESOURCE' && !empty($attendee['email']) && in_array_nocase($attendee['email'], $ownedResourceEmails)) {
$resourceConfirmation = true;
// Note on behalf of which resource this update is going to be sent out
$event['_resource'] = $attendee['email'];
}
}
if (!$noreply) {
$itip = $this->load_itip();
$itip->set_sender_email($reply_sender);
$event['thisandfuture'] = $event['_savemode'] == 'future';
$bodytextprefix = $resourceConfirmation ? 'itipmailbodyresource' : 'itipmailbody';
if ($organizer && $itip->send_itip_message($event, 'REPLY', $organizer, 'itipsubject' . $status, $bodytextprefix . $status)) {
$mailto = !empty($organizer['name']) ? $organizer['name'] : $organizer['email'];
$msg = $this->gettext(['name' => 'sentresponseto', 'vars' => ['mailto' => $mailto]]);
$this->rc->output->command('display_message', $msg, 'confirmation');
}
else {
$this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
}
}
// refresh all calendars
if ($event['calendar'] != $ev['calendar']) {
$this->rc->output->command('plugin.refresh_calendar', ['source' => null, 'refetch' => true]);
$reload = 0;
}
}
break;
case "dismiss":
$event['ids'] = explode(',', $event['id']);
$plugin = $this->rc->plugins->exec_hook('dismiss_alarms', $event);
$success = $plugin['success'];
foreach ($event['ids'] as $id) {
if (strpos($id, 'cal:') === 0) {
$success |= $this->driver->dismiss_alarm(substr($id, 4), $event['snooze']);
}
}
break;
case "changelog":
$data = $this->driver->get_event_changelog($event);
if (is_array($data) && !empty($data)) {
$lib = $this->lib;
$dtformat = $this->rc->config->get('date_format') . ' ' . $this->rc->config->get('time_format');
array_walk($data, function(&$change) use ($lib, $dtformat) {
if (!empty($change['date'])) {
$dt = $lib->adjust_timezone($change['date']);
- if ($dt instanceof DateTime) {
+ if ($dt instanceof DateTimeInterface) {
$change['date'] = $this->rc->format_date($dt, $dtformat, false);
}
}
});
$this->rc->output->command('plugin.render_event_changelog', $data);
}
else {
$this->rc->output->command('plugin.render_event_changelog', false);
}
$got_msg = true;
$reload = false;
break;
case "diff":
$data = $this->driver->get_event_diff($event, $event['rev1'], $event['rev2']);
if (is_array($data)) {
// convert some properties, similar to self::_client_event()
$lib = $this->lib;
array_walk($data['changes'], function(&$change, $i) use ($event, $lib) {
// convert date cols
foreach (['start', 'end', 'created', 'changed'] as $col) {
if ($change['property'] == $col) {
$change['old'] = $lib->adjust_timezone($change['old'], strlen($change['old']) == 10)->format('c');
$change['new'] = $lib->adjust_timezone($change['new'], strlen($change['new']) == 10)->format('c');
}
}
// create textual representation for alarms and recurrence
if ($change['property'] == 'alarms') {
if (is_array($change['old'])) {
$change['old_'] = libcalendaring::alarm_text($change['old']);
}
if (is_array($change['new'])) {
$change['new_'] = libcalendaring::alarm_text(array_merge((array)$change['old'], $change['new']));
}
}
if ($change['property'] == 'recurrence') {
if (is_array($change['old'])) {
$change['old_'] = $lib->recurrence_text($change['old']);
}
if (is_array($change['new'])) {
$change['new_'] = $lib->recurrence_text(array_merge((array)$change['old'], $change['new']));
}
}
if ($change['property'] == 'attachments') {
if (is_array($change['old'])) {
$change['old']['classname'] = rcube_utils::file2class($change['old']['mimetype'], $change['old']['name']);
}
if (is_array($change['new'])) {
$change['new']['classname'] = rcube_utils::file2class($change['new']['mimetype'], $change['new']['name']);
}
}
// compute a nice diff of description texts
if ($change['property'] == 'description') {
$change['diff_'] = libkolab::html_diff($change['old'], $change['new']);
}
});
$this->rc->output->command('plugin.event_show_diff', $data);
}
else {
$this->rc->output->command('display_message', $this->gettext('objectdiffnotavailable'), 'error');
}
$got_msg = true;
$reload = false;
break;
case "show":
if ($event = $this->driver->get_event_revison($event, $event['rev'])) {
$this->rc->output->command('plugin.event_show_revision', $this->_client_event($event));
}
else {
$this->rc->output->command('display_message', $this->gettext('objectnotfound'), 'error');
}
$got_msg = true;
$reload = false;
break;
case "restore":
if ($success = $this->driver->restore_event_revision($event, $event['rev'])) {
$_event = $this->driver->get_event($event);
$reload = $_event['recurrence'] ? 2 : 1;
$msg = $this->gettext(['name' => 'objectrestoresuccess', 'vars' => ['rev' => $event['rev']]]);
$this->rc->output->command('display_message', $msg, 'confirmation');
$this->rc->output->command('plugin.close_history_dialog');
}
else {
$this->rc->output->command('display_message', $this->gettext('objectrestoreerror'), 'error');
$reload = 0;
}
$got_msg = true;
break;
}
// show confirmation/error message
if (!$got_msg) {
if ($success) {
$this->rc->output->show_message('successfullysaved', 'confirmation');
}
else {
$this->rc->output->show_message('calendar.errorsaving', 'error');
}
}
// unlock client
$this->rc->output->command('plugin.unlock_saving', $success);
// update event object on the client or trigger a complete refresh if too complicated
if ($reload && empty($_REQUEST['_framed'])) {
$args = ['source' => $event['calendar']];
if ($reload > 1) {
$args['refetch'] = true;
}
else if ($success && $action != 'remove') {
$args['update'] = $this->_client_event($this->driver->get_event($event), true);
}
$this->rc->output->command('plugin.refresh_calendar', $args);
}
}
/**
* Helper method sending iTip notifications after successful event updates
*/
private function event_save_success(&$event, $old, $action, $success)
{
// $success is a new event ID
if ($success !== true) {
// send update notification on the main event
if ($event['_savemode'] == 'future' && !empty($event['_notify'])
&& !empty($old['attendees']) && !empty($old['recurrence_id'])
) {
$master = $this->driver->get_event(['id' => $old['recurrence_id'], 'calendar' => $old['calendar']], 0, true);
unset($master['_instance'], $master['recurrence_date']);
$sent = $this->notify_attendees($master, null, $action, $event['_comment'], false);
if ($sent < 0) {
$this->rc->output->show_message('calendar.errornotifying', 'error');
}
$event['attendees'] = $master['attendees']; // this tricks us into the next if clause
}
// delete old reference if saved as new
if ($event['_savemode'] == 'future' || $event['_savemode'] == 'new') {
$old = null;
}
$event['id'] = $success;
$event['_savemode'] = 'all';
}
// send out notifications
if (!empty($event['_notify']) && (!empty($event['attendees']) || !empty($old['attendees']))) {
$_savemode = $event['_savemode'];
// send notification for the main event when savemode is 'all'
if ($action != 'remove' && $_savemode == 'all'
&& (!empty($event['recurrence_id']) || !empty($old['recurrence_id']) || ($old && $old['id'] != $event['id']))
) {
if (!empty($event['recurrence_id'])) {
$event['id'] = $event['recurrence_id'];
}
else if (!empty($old['recurrence_id'])) {
$event['id'] = $old['recurrence_id'];
}
else {
$event['id'] = $old['id'];
}
$event = $this->driver->get_event($event, 0, true);
unset($event['_instance'], $event['recurrence_date']);
}
else {
// make sure we have the complete record
$event = $action == 'remove' ? $old : $this->driver->get_event($event, 0, true);
}
$event['_savemode'] = $_savemode;
if ($old) {
$old['thisandfuture'] = $_savemode == 'future';
}
// only notify if data really changed (TODO: do diff check on client already)
if (!$old || $action == 'remove' || self::event_diff($event, $old)) {
$comment = isset($event['_comment']) ? $event['_comment'] : null;
$sent = $this->notify_attendees($event, $old, $action, $comment);
if ($sent > 0) {
$this->rc->output->show_message('calendar.itipsendsuccess', 'confirmation');
}
else if ($sent < 0) {
$this->rc->output->show_message('calendar.errornotifying', 'error');
}
}
}
}
/**
* Handler for load-requests from fullcalendar
* This will return pure JSON formatted output
*/
function load_events()
{
$start = $this->input_timestamp('start', rcube_utils::INPUT_GET);
$end = $this->input_timestamp('end', rcube_utils::INPUT_GET);
$query = rcube_utils::get_input_value('q', rcube_utils::INPUT_GET);
$source = rcube_utils::get_input_value('source', rcube_utils::INPUT_GET);
$events = $this->driver->load_events($start, $end, $query, $source);
echo $this->encode($events, !empty($query));
exit;
}
/**
* Handler for requests fetching event counts for calendars
*/
public function count_events()
{
// don't update session on these requests (avoiding race conditions)
$this->rc->session->nowrite = true;
$start = rcube_utils::get_input_value('start', rcube_utils::INPUT_GET);
$source = rcube_utils::get_input_value('source', rcube_utils::INPUT_GET);
$end = rcube_utils::get_input_value('end', rcube_utils::INPUT_GET);
if (!$start) {
$start = new DateTime('today 00:00:00', $this->timezone);
$start = $start->format('U');
}
$counts = $this->driver->count_events($source, $start, $end);
$this->rc->output->command('plugin.update_counts', ['counts' => $counts]);
}
/**
* Load event data from an iTip message attachment
*/
public function itip_events($msgref)
{
$path = explode('/', $msgref);
$msg = array_pop($path);
$mbox = join('/', $path);
list($uid, $mime_id) = explode('#', $msg);
$events = [];
if ($event = $this->lib->mail_get_itip_object($mbox, $uid, $mime_id, 'event')) {
$partstat = 'NEEDS-ACTION';
$event['id'] = $event['uid'];
$event['temporary'] = true;
$event['readonly'] = true;
$event['calendar'] = '--invitation--itip';
$event['className'] = 'fc-invitation-' . strtolower($partstat);
$event['_mbox'] = $mbox;
$event['_uid'] = $uid;
$event['_part'] = $mime_id;
$events[] = $this->_client_event($event, true);
// add recurring instances
if (!empty($event['recurrence'])) {
// Some installations can't handle all occurrences (aborting the request w/o an error in log)
$freq = !empty($event['recurrence']['FREQ']) ? $event['recurrence']['FREQ'] : null;
$end = clone $event['start'];
$end->add(new DateInterval($freq == 'DAILY' ? 'P1Y' : 'P10Y'));
foreach ($this->driver->get_recurring_events($event, $event['start'], $end) as $recurring) {
$recurring['temporary'] = true;
$recurring['readonly'] = true;
$recurring['calendar'] = '--invitation--itip';
$events[] = $this->_client_event($recurring, true);
}
}
}
return $events;
}
/**
* Handler for keep-alive requests
* This will check for updated data in active calendars and sync them to the client
*/
public function refresh($attr)
{
// refresh the entire calendar every 10th time to also sync deleted events
if (rand(0, 10) == 10) {
$this->rc->output->command('plugin.refresh_calendar', ['refetch' => true]);
return;
}
$counts = [];
foreach ($this->driver->list_calendars(calendar_driver::FILTER_ACTIVE) as $cal) {
$events = $this->driver->load_events(
rcube_utils::get_input_value('start', rcube_utils::INPUT_GPC),
rcube_utils::get_input_value('end', rcube_utils::INPUT_GPC),
rcube_utils::get_input_value('q', rcube_utils::INPUT_GPC),
$cal['id'],
1,
$attr['last']
);
foreach ($events as $event) {
$this->rc->output->command(
'plugin.refresh_calendar',
['source' => $cal['id'], 'update' => $this->_client_event($event)]
);
}
// refresh count for this calendar
if (!empty($cal['counts'])) {
$today = new DateTime('today 00:00:00', $this->timezone);
$counts += $this->driver->count_events($cal['id'], $today->format('U'));
}
}
if (!empty($counts)) {
$this->rc->output->command('plugin.update_counts', ['counts' => $counts]);
}
}
/**
* Handler for pending_alarms plugin hook triggered by the calendar module on keep-alive requests.
* This will check for pending notifications and pass them to the client
*/
public function pending_alarms($p)
{
$this->load_driver();
$time = !empty($p['time']) ? $p['time'] : time();
if ($alarms = $this->driver->pending_alarms($time)) {
foreach ($alarms as $alarm) {
$alarm['id'] = 'cal:' . $alarm['id']; // prefix ID with cal:
$p['alarms'][] = $alarm;
}
}
// get alarms for birthdays calendar
if (
$this->rc->config->get('calendar_contact_birthdays')
&& $this->rc->config->get('calendar_birthdays_alarm_type') == 'DISPLAY'
) {
$cache = $this->rc->get_cache('calendar.birthdayalarms', 'db');
foreach ($this->driver->load_birthday_events($time, $time + 86400 * 60) as $e) {
$alarm = libcalendaring::get_next_alarm($e);
// overwrite alarm time with snooze value (or null if dismissed)
if ($dismissed = $cache->get($e['id'])) {
$alarm['time'] = $dismissed['notifyat'];
}
// add to list if alarm is set
if ($alarm && !empty($alarm['time']) && $alarm['time'] <= $time) {
$e['id'] = 'cal:bday:' . $e['id'];
$e['notifyat'] = $alarm['time'];
$p['alarms'][] = $e;
}
}
}
return $p;
}
/**
* Handler for alarm dismiss hook triggered by libcalendaring
*/
public function dismiss_alarms($p)
{
$this->load_driver();
foreach ((array) $p['ids'] as $id) {
if (strpos($id, 'cal:bday:') === 0) {
$p['success'] |= $this->driver->dismiss_birthday_alarm(substr($id, 9), $p['snooze']);
}
else if (strpos($id, 'cal:') === 0) {
$p['success'] |= $this->driver->dismiss_alarm(substr($id, 4), $p['snooze']);
}
}
return $p;
}
/**
* Handler for check-recent requests which are accidentally sent to calendar
*/
function check_recent()
{
// NOP
$this->rc->output->send();
}
/**
* Hook triggered when a contact is saved
*/
function contact_update($p)
{
// clear birthdays calendar cache
if (!empty($p['record']['birthday'])) {
$cache = $this->rc->get_cache('calendar.birthdays', 'db');
$cache->remove();
}
}
/**
*
*/
function import_events()
{
// Upload progress update
if (!empty($_GET['_progress'])) {
$this->rc->upload_progress();
}
@set_time_limit(0);
// process uploaded file if there is no error
$err = $_FILES['_data']['error'];
if (!$err && !empty($_FILES['_data']['tmp_name'])) {
$calendar = rcube_utils::get_input_value('calendar', rcube_utils::INPUT_GPC);
$rangestart = !empty($_REQUEST['_range']) ? date_create("now -" . intval($_REQUEST['_range']) . " months") : 0;
// extract zip file
if ($_FILES['_data']['type'] == 'application/zip') {
$count = 0;
if (class_exists('ZipArchive', false)) {
$zip = new ZipArchive();
if ($zip->open($_FILES['_data']['tmp_name'])) {
$randname = uniqid('zip-' . session_id(), true);
$tmpdir = slashify($this->rc->config->get('temp_dir', sys_get_temp_dir())) . $randname;
mkdir($tmpdir, 0700);
// extract each ical file from the archive and import it
for ($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
if (preg_match('/\.ics$/i', $filename)) {
$tmpfile = $tmpdir . '/' . basename($filename);
if (copy('zip://' . $_FILES['_data']['tmp_name'] . '#'.$filename, $tmpfile)) {
$count += $this->import_from_file($tmpfile, $calendar, $rangestart, $errors);
unlink($tmpfile);
}
}
}
rmdir($tmpdir);
$zip->close();
}
else {
$errors = 1;
$msg = 'Failed to open zip file.';
}
}
else {
$errors = 1;
$msg = 'Zip files are not supported for import.';
}
}
else {
// attempt to import teh uploaded file directly
$count = $this->import_from_file($_FILES['_data']['tmp_name'], $calendar, $rangestart, $errors);
}
if ($count) {
$this->rc->output->command('display_message', $this->gettext(['name' => 'importsuccess', 'vars' => ['nr' => $count]]), 'confirmation');
$this->rc->output->command('plugin.import_success', ['source' => $calendar, 'refetch' => true]);
}
else if (!$errors) {
$this->rc->output->command('display_message', $this->gettext('importnone'), 'notice');
$this->rc->output->command('plugin.import_success', ['source' => $calendar]);
}
else {
$this->rc->output->command('plugin.import_error', ['message' => $this->gettext('importerror') . ($msg ? ': ' . $msg : '')]);
}
}
else {
if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
$max = $this->rc->show_bytes(parse_bytes(ini_get('upload_max_filesize')));
$msg = $this->rc->gettext(['name' => 'filesizeerror', 'vars' => ['size' => $max]]);
}
else {
$msg = $this->rc->gettext('fileuploaderror');
}
$this->rc->output->command('plugin.import_error', ['message' => $msg]);
}
$this->rc->output->send('iframe');
}
/**
* Helper function to parse and import a single .ics file
*/
private function import_from_file($filepath, $calendar, $rangestart, &$errors)
{
$user_email = $this->rc->user->get_username();
$ical = $this->get_ical();
$errors = !$ical->fopen($filepath);
$count = $i = 0;
foreach ($ical as $event) {
// keep the browser connection alive on long import jobs
if (++$i > 100 && $i % 100 == 0) {
echo "<!-- -->";
ob_flush();
}
// TODO: correctly handle recurring events which start before $rangestart
if ($rangestart && $event['end'] < $rangestart
&& (empty($event['recurrence']) || (!empty($event['recurrence']['until']) && $event['recurrence']['until'] < $rangestart))
) {
continue;
}
$event['_owner'] = $user_email;
$event['calendar'] = $calendar;
if ($this->driver->new_event($event)) {
$count++;
}
else {
$errors++;
}
}
return $count;
}
/**
* Construct the ics file for exporting events to iCalendar format;
*/
function export_events($terminate = true)
{
$start = rcube_utils::get_input_value('start', rcube_utils::INPUT_GET);
$end = rcube_utils::get_input_value('end', rcube_utils::INPUT_GET);
$event_id = rcube_utils::get_input_value('id', rcube_utils::INPUT_GET);
$attachments = rcube_utils::get_input_value('attachments', rcube_utils::INPUT_GET);
$calid = rcube_utils::get_input_value('source', rcube_utils::INPUT_GET);
if (!isset($start)) {
$start = 'today -1 year';
}
if (!is_numeric($start)) {
$start = strtotime($start . ' 00:00:00');
}
if (!$end) {
$end = 'today +10 years';
}
if (!is_numeric($end)) {
$end = strtotime($end . ' 23:59:59');
}
$filename = $calid;
$calendars = $this->driver->list_calendars();
$events = [];
if (!empty($calendars[$calid])) {
$filename = !empty($calendars[$calid]['name']) ? $calendars[$calid]['name'] : $calid;
$filename = asciiwords(html_entity_decode($filename)); // to 7bit ascii
if (!empty($event_id)) {
if ($event = $this->driver->get_event(['calendar' => $calid, 'id' => $event_id], 0, true)) {
if (!empty($event['recurrence_id'])) {
$event = $this->driver->get_event(['calendar' => $calid, 'id' => $event['recurrence_id']], 0, true);
}
$events = [$event];
$filename = asciiwords($event['title']);
if (empty($filename)) {
$filename = 'event';
}
}
}
else {
$events = $this->driver->load_events($start, $end, null, $calid, 0);
if (empty($filename)) {
$filename = $calid;
}
}
}
header("Content-Type: text/calendar");
header("Content-Disposition: inline; filename=".$filename.'.ics');
$this->get_ical()->export($events, '', true, $attachments ? [$this->driver, 'get_attachment_body'] : null);
if ($terminate) {
exit;
}
}
/**
* Handler for iCal feed requests
*/
function ical_feed_export()
{
$session_exists = !empty($_SESSION['user_id']);
// process HTTP auth info
if (!empty($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
$_POST['_user'] = $_SERVER['PHP_AUTH_USER']; // used for rcmail::autoselect_host()
$auth = $this->rc->plugins->exec_hook('authenticate', [
'host' => $this->rc->autoselect_host(),
'user' => trim($_SERVER['PHP_AUTH_USER']),
'pass' => $_SERVER['PHP_AUTH_PW'],
'cookiecheck' => true,
'valid' => true,
]);
if ($auth['valid'] && !$auth['abort']) {
$this->rc->login($auth['user'], $auth['pass'], $auth['host']);
}
}
// require HTTP auth
if (empty($_SESSION['user_id'])) {
header('WWW-Authenticate: Basic realm="Kolab Calendar"');
header('HTTP/1.0 401 Unauthorized');
exit;
}
// decode calendar feed hash
$format = 'ics';
$calhash = rcube_utils::get_input_value('_cal', rcube_utils::INPUT_GET);
if (preg_match(($suff_regex = '/\.([a-z0-9]{3,5})$/i'), $calhash, $m)) {
$format = strtolower($m[1]);
$calhash = preg_replace($suff_regex, '', $calhash);
}
if (!strpos($calhash, ':')) {
$calhash = base64_decode($calhash);
}
list($user, $_GET['source']) = explode(':', $calhash, 2);
// sanity check user
if ($this->rc->user->get_username() == $user) {
$this->setup();
$this->load_driver();
$this->export_events(false);
}
else {
header('HTTP/1.0 404 Not Found');
}
// don't save session data
if (!$session_exists) {
session_destroy();
}
exit;
}
/**
*
*/
function load_settings()
{
$this->lib->load_settings();
$this->defaults += $this->lib->defaults;
$settings = [];
// configuration
$settings['default_view'] = (string) $this->rc->config->get('calendar_default_view', $this->defaults['calendar_default_view']);
$settings['timeslots'] = (int) $this->rc->config->get('calendar_timeslots', $this->defaults['calendar_timeslots']);
$settings['first_day'] = (int) $this->rc->config->get('calendar_first_day', $this->defaults['calendar_first_day']);
$settings['first_hour'] = (int) $this->rc->config->get('calendar_first_hour', $this->defaults['calendar_first_hour']);
$settings['work_start'] = (int) $this->rc->config->get('calendar_work_start', $this->defaults['calendar_work_start']);
$settings['work_end'] = (int) $this->rc->config->get('calendar_work_end', $this->defaults['calendar_work_end']);
$settings['agenda_range'] = (int) $this->rc->config->get('calendar_agenda_range', $this->defaults['calendar_agenda_range']);
$settings['event_coloring'] = (int) $this->rc->config->get('calendar_event_coloring', $this->defaults['calendar_event_coloring']);
$settings['time_indicator'] = (int) $this->rc->config->get('calendar_time_indicator', $this->defaults['calendar_time_indicator']);
$settings['invite_shared'] = (int) $this->rc->config->get('calendar_allow_invite_shared', $this->defaults['calendar_allow_invite_shared']);
$settings['itip_notify'] = (int) $this->rc->config->get('calendar_itip_send_option', $this->defaults['calendar_itip_send_option']);
$settings['show_weekno'] = (int) $this->rc->config->get('calendar_show_weekno', $this->defaults['calendar_show_weekno']);
$settings['default_calendar'] = $this->rc->config->get('calendar_default_calendar');
$settings['invitation_calendars'] = (bool) $this->rc->config->get('kolab_invitation_calendars', false);
// 'table' view has been replaced by 'list' view
if ($settings['default_view'] == 'table') {
$settings['default_view'] = 'list';
}
// get user identity to create default attendee
if ($this->ui->screen == 'calendar') {
foreach ($this->rc->user->list_emails() as $rec) {
if (empty($identity)) {
$identity = $rec;
}
$identity['emails'][] = $rec['email'];
$settings['identities'][$rec['identity_id']] = $rec['email'];
}
$identity['emails'][] = $this->rc->user->get_username();
$identity['ownedResources'] = $this->owned_resources_emails();
$settings['identity'] = [
'name' => $identity['name'],
'email' => strtolower($identity['email']),
'emails' => ';' . strtolower(join(';', $identity['emails'])),
'ownedResources' => ';' . strtolower(join(';', $identity['ownedResources']))
];
}
// freebusy token authentication URL
if (($url = $this->rc->config->get('calendar_freebusy_session_auth_url'))
&& ($uniqueid = $this->rc->config->get('kolab_uniqueid'))
) {
if ($url === true) {
$url = '/freebusy';
}
$url = rtrim(rcube_utils::resolve_url($url), '/ ');
$url .= '/' . urlencode($this->rc->get_user_name());
$url .= '/' . urlencode($uniqueid);
$settings['freebusy_url'] = $url;
}
return $settings;
}
/**
* Encode events as JSON
*
* @param array Events as array
* @param bool Add CSS class names according to calendar and categories
*
* @return string JSON encoded events
*/
function encode($events, $addcss = false)
{
$json = [];
foreach ($events as $event) {
$json[] = $this->_client_event($event, $addcss);
}
return rcube_output::json_serialize($json);
}
/**
* Convert an event object to be used on the client
*/
private function _client_event($event, $addcss = false)
{
// compose a human readable strings for alarms_text and recurrence_text
if (!empty($event['valarms'])) {
$event['alarms_text'] = libcalendaring::alarms_text($event['valarms']);
$event['valarms'] = libcalendaring::to_client_alarms($event['valarms']);
}
if (!empty($event['recurrence'])) {
$event['recurrence_text'] = $this->lib->recurrence_text($event['recurrence']);
$event['recurrence'] = $this->lib->to_client_recurrence($event['recurrence'], $event['allday']);
unset($event['recurrence_date']);
}
if (!empty($event['attachments'])) {
foreach ($event['attachments'] as $k => $attachment) {
$event['attachments'][$k]['classname'] = rcube_utils::file2class($attachment['mimetype'], $attachment['name']);
unset($event['attachments'][$k]['data'], $event['attachments'][$k]['content']);
if (empty($attachment['id'])) {
$event['attachments'][$k]['id'] = $k;
}
}
}
// convert link URIs references into structs
if (array_key_exists('links', $event)) {
foreach ((array) $event['links'] as $i => $link) {
if (strpos($link, 'imap://') === 0 && ($msgref = $this->driver->get_message_reference($link))) {
$event['links'][$i] = $msgref;
}
}
}
// check for organizer in attendees list
$organizer = null;
foreach ((array) $event['attendees'] as $i => $attendee) {
if ($attendee['role'] == 'ORGANIZER') {
$organizer = $attendee;
}
if (!empty($attendee['status']) && $attendee['status'] == 'DELEGATED' && empty($attendee['rsvp'])) {
$event['attendees'][$i]['noreply'] = true;
}
else {
unset($event['attendees'][$i]['noreply']);
}
}
if ($organizer === null && !empty($event['organizer'])) {
$organizer = $event['organizer'];
$organizer['role'] = 'ORGANIZER';
if (!is_array($event['attendees'])) {
$event['attendees'] = [$organizer];
}
}
// Convert HTML description into plain text
if ($this->is_html($event)) {
$h2t = new rcube_html2text($event['description'], false, true, 0);
$event['description'] = trim($h2t->get_text());
}
// mapping url => vurl, allday => allDay because of the fullcalendar client script
$event['vurl'] = $event['url'];
$event['allDay'] = !empty($event['allday']);
unset($event['url']);
unset($event['allday']);
$event['className'] = !empty($event['className']) ? explode(' ', $event['className']) : [];
if ($event['allDay']) {
$event['end'] = $event['end']->add(new DateInterval('P1D'));
}
if (!empty($_GET['mode']) && $_GET['mode'] == 'print') {
$event['editable'] = false;
}
return [
'_id' => $event['calendar'] . ':' . $event['id'], // unique identifier for fullcalendar
'start' => $this->lib->adjust_timezone($event['start'], $event['allDay'])->format('c'),
'end' => $this->lib->adjust_timezone($event['end'], $event['allDay'])->format('c'),
// 'changed' might be empty for event recurrences (Bug #2185)
'changed' => !empty($event['changed']) ? $this->lib->adjust_timezone($event['changed'])->format('c') : null,
'created' => !empty($event['created']) ? $this->lib->adjust_timezone($event['created'])->format('c') : null,
'title' => strval($event['title']),
'description' => strval($event['description']),
'location' => strval($event['location']),
] + $event;
}
/**
* Generate a unique identifier for an event
*/
public function generate_uid()
{
return strtoupper(md5(time() . uniqid(rand())) . '-' . substr(md5($this->rc->user->get_username()), 0, 16));
}
/**
* TEMPORARY: generate random event data for testing
* Create events by opening http://<roundcubeurl>/?_task=calendar&_action=randomdata&_num=500&_date=2014-08-01&_dev=120
*/
public function generate_randomdata()
{
@set_time_limit(0);
$num = !empty($_REQUEST['_num']) ? intval($_REQUEST['_num']) : 100;
$date = !empty($_REQUEST['_date']) ? $_REQUEST['_date'] : 'now';
$dev = !empty($_REQUEST['_dev']) ? $_REQUEST['_dev'] : 30;
$cats = array_keys($this->driver->list_categories());
$cals = $this->driver->list_calendars(calendar_driver::FILTER_ACTIVE);
$count = 0;
while ($count++ < $num) {
$spread = intval($dev) * 86400; // days
$refdate = strtotime($date);
$start = round(($refdate + rand(-$spread, $spread)) / 600) * 600;
$duration = round(rand(30, 360) / 30) * 30 * 60;
$allday = rand(0,20) > 18;
$alarm = rand(-30,12) * 5;
$fb = rand(0,2);
if (date('G', $start) > 23) {
$start -= 3600;
}
if ($allday) {
$start = strtotime(date('Y-m-d 00:00:00', $start));
$duration = 86399;
}
$title = '';
$len = rand(2, 12);
$words = explode(" ", "The Hough transform is named after Paul Hough who patented the method in 1962."
. " It is a technique which can be used to isolate features of a particular shape within an image."
. " Because it requires that the desired features be specified in some parametric form, the classical"
. " Hough transform is most commonly used for the de- tection of regular curves such as lines, circles,"
. " ellipses, etc. A generalized Hough transform can be employed in applications where a simple"
. " analytic description of a feature(s) is not possible. Due to the computational complexity of"
. " the generalized Hough algorithm, we restrict the main focus of this discussion to the classical"
. " Hough transform. Despite its domain restrictions, the classical Hough transform (hereafter"
. " referred to without the classical prefix ) retains many applications, as most manufac- tured"
. " parts (and many anatomical parts investigated in medical imagery) contain feature boundaries"
. " which can be described by regular curves. The main advantage of the Hough transform technique"
. " is that it is tolerant of gaps in feature boundary descriptions and is relatively unaffected"
. " by image noise.");
// $chars = "!# abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890";
for ($i = 0; $i < $len; $i++) {
$title .= $words[rand(0,count($words)-1)] . " ";
}
$this->driver->new_event([
'uid' => $this->generate_uid(),
'start' => new DateTime('@'.$start),
'end' => new DateTime('@'.($start + $duration)),
'allday' => $allday,
'title' => rtrim($title),
'free_busy' => $fb == 2 ? 'outofoffice' : ($fb ? 'busy' : 'free'),
'categories' => $cats[array_rand($cats)],
'calendar' => array_rand($cals),
'alarms' => $alarm > 0 ? "-{$alarm}M:DISPLAY" : '',
'priority' => rand(0,9),
]);
}
$this->rc->output->redirect('');
}
/**
* Handler for attachments upload
*/
public function attachment_upload()
{
$handler = new kolab_attachments_handler();
$handler->attachment_upload(self::SESSION_KEY, 'cal-');
}
/**
* Handler for attachments download/displaying
*/
public function attachment_get()
{
$handler = new kolab_attachments_handler();
// show loading page
if (!empty($_GET['_preload'])) {
return $handler->attachment_loading_page();
}
$event_id = rcube_utils::get_input_value('_event', rcube_utils::INPUT_GPC);
$calendar = rcube_utils::get_input_value('_cal', rcube_utils::INPUT_GPC);
$id = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC);
$rev = rcube_utils::get_input_value('_rev', rcube_utils::INPUT_GPC);
$event = ['id' => $event_id, 'calendar' => $calendar, 'rev' => $rev];
if ($calendar == '--invitation--itip') {
$uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GPC);
$part = rcube_utils::get_input_value('_part', rcube_utils::INPUT_GPC);
$mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GPC);
$event = $this->lib->mail_get_itip_object($mbox, $uid, $part, 'event');
$attachment = $event['attachments'][$id];
$attachment['body'] = &$attachment['data'];
}
else {
$attachment = $this->driver->get_attachment($id, $event);
}
// show part page
if (!empty($_GET['_frame'])) {
$handler->attachment_page($attachment);
}
// deliver attachment content
else if ($attachment) {
if ($calendar != '--invitation--itip') {
$attachment['body'] = $this->driver->get_attachment_body($id, $event);
}
$handler->attachment_get($attachment);
}
// if we arrive here, the requested part was not found
header('HTTP/1.1 404 Not Found');
exit;
}
/**
* Determine whether the given event description is HTML formatted
*/
private function is_html($event)
{
// check for opening and closing <html> or <body> tags
return preg_match('/<(html|body)(\s+[a-z]|>)/', $event['description'], $m)
&& strpos($event['description'], '</'.$m[1].'>') > 0;
}
/**
* Prepares new/edited event properties before save
*/
private function write_preprocess(&$event, $action)
{
// Remove double timezone specification (T2313)
$event['start'] = preg_replace('/\s*\(.*\)/', '', $event['start']);
$event['end'] = preg_replace('/\s*\(.*\)/', '', $event['end']);
// convert dates into DateTime objects in user's current timezone
$event['start'] = new DateTime($event['start'], $this->timezone);
$event['end'] = new DateTime($event['end'], $this->timezone);
$event['allday'] = !empty($event['allDay']);
unset($event['allDay']);
// start/end is all we need for 'move' action (#1480)
if ($action == 'move') {
return true;
}
// convert the submitted recurrence settings
if (!empty($event['recurrence'])) {
$event['recurrence'] = $this->lib->from_client_recurrence($event['recurrence'], $event['start']);
// align start date with the first occurrence
if (!empty($event['recurrence']) && !empty($event['syncstart'])
&& (empty($event['_savemode']) || $event['_savemode'] == 'all')
) {
$next = $this->find_first_occurrence($event);
if (!$next) {
$this->rc->output->show_message('calendar.recurrenceerror', 'error');
return false;
}
else if ($event['start'] != $next) {
$diff = $event['start']->diff($event['end'], true);
$event['start'] = $next;
$event['end'] = clone $next;
$event['end']->add($diff);
}
}
}
// convert the submitted alarm values
if (!empty($event['valarms'])) {
$event['valarms'] = libcalendaring::from_client_alarms($event['valarms']);
}
$attachments = [];
$eventid = 'cal-' . (!empty($event['id']) ? $event['id'] : 'new');
if (!empty($_SESSION[self::SESSION_KEY]) && $_SESSION[self::SESSION_KEY]['id'] == $eventid) {
if (!empty($_SESSION[self::SESSION_KEY]['attachments'])) {
foreach ($_SESSION[self::SESSION_KEY]['attachments'] as $id => $attachment) {
if (!empty($event['attachments']) && in_array($id, $event['attachments'])) {
$attachments[$id] = $this->rc->plugins->exec_hook('attachment_get', $attachment);
}
}
}
}
$event['attachments'] = $attachments;
// convert link references into simple URIs
if (array_key_exists('links', $event)) {
$event['links'] = array_map(function($link) {
return is_array($link) ? $link['uri'] : strval($link);
},
(array) $event['links']
);
}
// check for organizer in attendees
if ($action == 'new' || $action == 'edit') {
if (empty($event['attendees'])) {
$event['attendees'] = [];
}
$emails = $this->get_user_emails();
$organizer = $owner = false;
foreach ((array) $event['attendees'] as $i => $attendee) {
if ($attendee['role'] == 'ORGANIZER') {
$organizer = $i;
}
if (!empty($attendee['email']) && in_array(strtolower($attendee['email']), $emails)) {
$owner = $i;
}
if (!isset($attendee['rsvp'])) {
$event['attendees'][$i]['rsvp'] = true;
}
else if (is_string($attendee['rsvp'])) {
$event['attendees'][$i]['rsvp'] = $attendee['rsvp'] == 'true' || $attendee['rsvp'] == '1';
}
}
if (!empty($event['_identity'])) {
$identity = $this->rc->user->get_identity($event['_identity']);
}
// set new organizer identity
if ($organizer !== false && !empty($identity)) {
$event['attendees'][$organizer]['name'] = $identity['name'];
$event['attendees'][$organizer]['email'] = $identity['email'];
}
// set owner as organizer if yet missing
else if ($organizer === false && $owner !== false) {
$event['attendees'][$owner]['role'] = 'ORGANIZER';
unset($event['attendees'][$owner]['rsvp']);
}
// fallback to the selected identity
else if ($organizer === false && !empty($identity)) {
$event['attendees'][] = [
'role' => 'ORGANIZER',
'name' => $identity['name'],
'email' => $identity['email'],
];
}
}
// mapping url => vurl because of the fullcalendar client script
if (array_key_exists('vurl', $event)) {
$event['url'] = $event['vurl'];
unset($event['vurl']);
}
return true;
}
/**
* Releases some resources after successful event save
*/
private function cleanup_event(&$event)
{
// remove temp. attachment files
if (!empty($_SESSION[self::SESSION_KEY]) && ($eventid = $_SESSION[self::SESSION_KEY]['id'])) {
$this->rc->plugins->exec_hook('attachments_cleanup', ['group' => $eventid]);
$this->rc->session->remove(self::SESSION_KEY);
}
}
/**
* Send out an invitation/notification to all event attendees
*/
private function notify_attendees($event, $old, $action = 'edit', $comment = null, $rsvp = null)
{
$is_cancelled = false;
if ($action == 'remove' || ($event['status'] == 'CANCELLED' && $old['status'] != $event['status'])) {
$event['cancelled'] = true;
$is_cancelled = true;
}
if ($rsvp === null) {
$rsvp = !$old || $event['sequence'] > $old['sequence'];
}
$itip = $this->load_itip();
$emails = $this->get_user_emails();
$itip_notify = (int) $this->rc->config->get('calendar_itip_send_option', $this->defaults['calendar_itip_send_option']);
// add comment to the iTip attachment
$event['comment'] = $comment;
// set a valid recurrence-id if this is a recurrence instance
libcalendaring::identify_recurrence_instance($event);
// compose multipart message using PEAR:Mail_Mime
$method = $action == 'remove' ? 'CANCEL' : 'REQUEST';
$message = $itip->compose_itip_message($event, $method, $rsvp);
// list existing attendees from $old event
$old_attendees = [];
if (!empty($old['attendees'])) {
foreach ((array) $old['attendees'] as $attendee) {
$old_attendees[] = $attendee['email'];
}
}
// send to every attendee
$sent = 0;
$current = [];
foreach ((array) $event['attendees'] as $attendee) {
// skip myself for obvious reasons
if (empty($attendee['email']) || in_array(strtolower($attendee['email']), $emails)) {
continue;
}
$current[] = strtolower($attendee['email']);
// skip if notification is disabled for this attendee
if (!empty($attendee['noreply']) && $itip_notify & 2) {
continue;
}
// skip if this attendee has delegated and set RSVP=FALSE
if ($attendee['status'] == 'DELEGATED' && $attendee['rsvp'] === false) {
continue;
}
// which template to use for mail text
$is_new = !in_array($attendee['email'], $old_attendees);
$is_rsvp = $is_new || $event['sequence'] > $old['sequence'];
$bodytext = $is_cancelled ? 'eventcancelmailbody' : ($is_new ? 'invitationmailbody' : 'eventupdatemailbody');
$subject = $is_cancelled ? 'eventcancelsubject' : ($is_new ? 'invitationsubject' : ($event['title'] ? 'eventupdatesubject' : 'eventupdatesubjectempty'));
$event['comment'] = $comment;
// finally send the message
if ($itip->send_itip_message($event, $method, $attendee, $subject, $bodytext, $message, $is_rsvp)) {
$sent++;
}
else {
$sent = -100;
}
}
// TODO: on change of a recurring (main) event, also send updates to differing attendess of recurrence exceptions
// send CANCEL message to removed attendees
if (!empty($old['attendees'])) {
foreach ($old['attendees'] as $attendee) {
if ($attendee['role'] == 'ORGANIZER'
|| empty($attendee['email'])
|| in_array(strtolower($attendee['email']), $current)
) {
continue;
}
$vevent = $old;
$vevent['cancelled'] = $is_cancelled;
$vevent['attendees'] = [$attendee];
$vevent['comment'] = $comment;
if ($itip->send_itip_message($vevent, 'CANCEL', $attendee, 'eventcancelsubject', 'eventcancelmailbody')) {
$sent++;
}
else {
$sent = -100;
}
}
}
return $sent;
}
/**
* Echo simple free/busy status text for the given user and time range
*/
public function freebusy_status()
{
$email = rcube_utils::get_input_value('email', rcube_utils::INPUT_GPC);
$start = $this->input_timestamp('start', rcube_utils::INPUT_GPC);
$end = $this->input_timestamp('end', rcube_utils::INPUT_GPC);
if (!$start) $start = time();
if (!$end) $end = $start + 3600;
$status = 'UNKNOWN';
$fbtypemap = [
calendar::FREEBUSY_UNKNOWN => 'UNKNOWN',
calendar::FREEBUSY_FREE => 'FREE',
calendar::FREEBUSY_BUSY => 'BUSY',
calendar::FREEBUSY_TENTATIVE => 'TENTATIVE',
calendar::FREEBUSY_OOF => 'OUT-OF-OFFICE'
];
// if the backend has free-busy information
$fblist = $this->driver->get_freebusy_list($email, $start, $end);
if (is_array($fblist)) {
$status = 'FREE';
foreach ($fblist as $slot) {
list($from, $to, $type) = $slot;
if ($from < $end && $to > $start) {
$status = isset($type) && !empty($fbtypemap[$type]) ? $fbtypemap[$type] : 'BUSY';
break;
}
}
}
// let this information be cached for 5min
$this->rc->output->future_expire_header(300);
echo $status;
exit;
}
/**
* Return a list of free/busy time slots within the given period
* Echo data in JSON encoding
*/
public function freebusy_times()
{
$email = rcube_utils::get_input_value('email', rcube_utils::INPUT_GPC);
$start = $this->input_timestamp('start', rcube_utils::INPUT_GPC);
$end = $this->input_timestamp('end', rcube_utils::INPUT_GPC);
$interval = intval(rcube_utils::get_input_value('interval', rcube_utils::INPUT_GPC));
$strformat = $interval > 60 ? 'Ymd' : 'YmdHis';
if (!$start) $start = time();
if (!$end) $end = $start + 86400 * 30;
if (!$interval) $interval = 60; // 1 hour
if (!$dte) {
$dts = new DateTime('@'.$start);
$dts->setTimezone($this->timezone);
}
$fblist = $this->driver->get_freebusy_list($email, $start, $end);
$slots = '';
// prepare freebusy list before use (for better performance)
if (is_array($fblist)) {
foreach ($fblist as $idx => $slot) {
list($from, $to, ) = $slot;
// check for possible all-day times
if (gmdate('His', $from) == '000000' && gmdate('His', $to) == '235959') {
// shift into the user's timezone for sane matching
$fblist[$idx][0] -= $this->gmt_offset;
$fblist[$idx][1] -= $this->gmt_offset;
}
}
}
// build a list from $start till $end with blocks representing the fb-status
for ($s = 0, $t = $start; $t <= $end; $s++) {
$t_end = $t + $interval * 60;
$dt = new DateTime('@'.$t);
$dt->setTimezone($this->timezone);
// determine attendee's status
if (is_array($fblist)) {
$status = self::FREEBUSY_FREE;
foreach ($fblist as $slot) {
list($from, $to, $type) = $slot;
if ($from < $t_end && $to > $t) {
$status = isset($type) ? $type : self::FREEBUSY_BUSY;
if ($status == self::FREEBUSY_BUSY) {
// can't get any worse :-)
break;
}
}
}
}
else {
$status = self::FREEBUSY_UNKNOWN;
}
// use most compact format, assume $status is one digit/character
$slots .= $status;
$t = $t_end;
}
$dte = new DateTime('@'.$t_end);
$dte->setTimezone($this->timezone);
// let this information be cached for 5min
$this->rc->output->future_expire_header(300);
echo rcube_output::json_serialize([
'email' => $email,
'start' => $dts->format('c'),
'end' => $dte->format('c'),
'interval' => $interval,
'slots' => $slots,
]);
exit;
}
/**
* Handler for printing calendars
*/
public function print_view()
{
$title = $this->gettext('print');
$view = rcube_utils::get_input_value('view', rcube_utils::INPUT_GPC);
if (!in_array($view, ['agendaWeek', 'agendaDay', 'month', 'list'])) {
$view = 'agendaDay';
}
$this->rc->output->set_env('view', $view);
if ($date = rcube_utils::get_input_value('date', rcube_utils::INPUT_GPC)) {
$this->rc->output->set_env('date', $date);
}
if ($range = rcube_utils::get_input_value('range', rcube_utils::INPUT_GPC)) {
$this->rc->output->set_env('listRange', intval($range));
}
if ($search = rcube_utils::get_input_value('search', rcube_utils::INPUT_GPC)) {
$this->rc->output->set_env('search', $search);
$title .= ' "' . $search . '"';
}
// Add JS to the page
$this->ui->addJS();
$this->register_handler('plugin.calendar_css', [$this->ui, 'calendar_css']);
$this->register_handler('plugin.calendar_list', [$this->ui, 'calendar_list']);
$this->rc->output->set_pagetitle($title);
$this->rc->output->send('calendar.print');
}
/**
* Compare two event objects and return differing properties
*
* @param array Event A
* @param array Event B
*
* @return array List of differing event properties
*/
public static function event_diff($a, $b)
{
$diff = [];
$ignore = ['changed' => 1, 'attachments' => 1];
foreach (array_unique(array_merge(array_keys($a), array_keys($b))) as $key) {
if (empty($ignore[$key]) && $key[0] != '_') {
$av = isset($a[$key]) ? $a[$key] : null;
$bv = isset($b[$key]) ? $b[$key] : null;
if ($av != $bv) {
$diff[] = $key;
}
}
}
// only compare number of attachments
$ac = !empty($a['attachments']) ? count($a['attachments']) : 0;
$bc = !empty($b['attachments']) ? count($b['attachments']) : 0;
if ($ac != $bc) {
$diff[] = 'attachments';
}
return $diff;
}
/**
* Update attendee properties on the given event object
*
* @param array The event object to be altered
* @param array List of hash arrays each represeting an updated/added attendee
*/
public static function merge_attendee_data(&$event, $attendees, $removed = null)
{
if (!empty($attendees) && !is_array($attendees[0])) {
$attendees = [$attendees];
}
foreach ($attendees as $attendee) {
$found = false;
foreach ($event['attendees'] as $i => $candidate) {
if ($candidate['email'] == $attendee['email']) {
$event['attendees'][$i] = $attendee;
$found = true;
break;
}
}
if (!$found) {
$event['attendees'][] = $attendee;
}
}
// filter out removed attendees
if (!empty($removed)) {
$event['attendees'] = array_filter($event['attendees'], function($attendee) use ($removed) {
return !in_array($attendee['email'], $removed);
});
}
}
/**** Resource management functions ****/
/**
* Getter for the configured implementation of the resource directory interface
*/
private function resources_directory()
{
if (!empty($this->resources_dir)) {
return $this->resources_dir;
}
if ($driver_name = $this->rc->config->get('calendar_resources_driver')) {
$driver_class = 'resources_driver_' . $driver_name;
require_once($this->home . '/drivers/resources_driver.php');
require_once($this->home . '/drivers/' . $driver_name . '/' . $driver_class . '.php');
$this->resources_dir = new $driver_class($this);
}
return $this->resources_dir;
}
/**
* Handler for resoruce autocompletion requests
*/
public function resources_autocomplete()
{
$search = rcube_utils::get_input_value('_search', rcube_utils::INPUT_GPC, true);
$sid = rcube_utils::get_input_value('_reqid', rcube_utils::INPUT_GPC);
$maxnum = (int)$this->rc->config->get('autocomplete_max', 15);
$results = [];
if ($directory = $this->resources_directory()) {
foreach ($directory->load_resources($search, $maxnum) as $rec) {
$results[] = [
'name' => $rec['name'],
'email' => $rec['email'],
'type' => $rec['_type'],
];
}
}
$this->rc->output->command('ksearch_query_results', $results, $search, $sid);
$this->rc->output->send();
}
/**
* Handler for load-requests for resource data
*/
function resources_list()
{
$data = [];
if ($directory = $this->resources_directory()) {
foreach ($directory->load_resources() as $rec) {
$data[] = $rec;
}
}
$this->rc->output->command('plugin.resource_data', $data);
$this->rc->output->send();
}
/**
* Handler for requests loading resource owner information
*/
function resources_owner()
{
if ($directory = $this->resources_directory()) {
$id = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC);
$data = $directory->get_resource_owner($id);
}
$this->rc->output->command('plugin.resource_owner', $data);
$this->rc->output->send();
}
/**
* Deliver event data for a resource's calendar
*/
function resources_calendar()
{
$events = [];
if ($directory = $this->resources_directory()) {
$id = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC);
$start = $this->input_timestamp('start', rcube_utils::INPUT_GET);
$end = $this->input_timestamp('end', rcube_utils::INPUT_GET);
$events = $directory->get_resource_calendar($id, $start, $end);
}
echo $this->encode($events);
exit;
}
/**
* List email addressed of owned resources
*/
private function owned_resources_emails()
{
$results = [];
if ($directory = $this->resources_directory()) {
foreach ($directory->load_resources($_SESSION['kolab_dn'], 5000, 'owner') as $rec) {
$results[] = $rec['email'];
}
}
return $results;
}
/**** Event invitation plugin hooks ****/
/**
* Find an event in user calendars
*/
protected function find_event($event, &$mode)
{
$this->load_driver();
// We search for writeable calendars in personal namespace by default
$mode = calendar_driver::FILTER_WRITEABLE | calendar_driver::FILTER_PERSONAL;
$result = $this->driver->get_event($event, $mode);
// ... now check shared folders if not found
if (!$result) {
$result = $this->driver->get_event($event, calendar_driver::FILTER_WRITEABLE | calendar_driver::FILTER_SHARED);
if ($result) {
$mode |= calendar_driver::FILTER_SHARED;
}
}
return $result;
}
/**
* Handler for calendar/itip-status requests
*/
function event_itip_status()
{
$data = rcube_utils::get_input_value('data', rcube_utils::INPUT_POST, true);
$this->load_driver();
// find local copy of the referenced event (in personal namespace)
$existing = $this->find_event($data, $mode);
$is_shared = $mode & calendar_driver::FILTER_SHARED;
$itip = $this->load_itip();
$response = $itip->get_itip_status($data, $existing);
// get a list of writeable calendars to save new events to
if (
(!$existing || $is_shared)
&& empty($data['nosave'])
&& ($response['action'] == 'rsvp' || $response['action'] == 'import')
) {
$calendars = $this->driver->list_calendars($mode);
$calendar_select = new html_select([
'name' => 'calendar',
'id' => 'itip-saveto',
'is_escaped' => true,
'class' => 'form-control custom-select'
]);
$calendar_select->add('--', '');
$numcals = 0;
foreach ($calendars as $calendar) {
if (!empty($calendar['editable'])) {
$calendar_select->add($calendar['name'], $calendar['id']);
$numcals++;
}
}
if ($numcals < 1) {
$calendar_select = null;
}
}
if (!empty($calendar_select)) {
$default_calendar = $this->get_default_calendar($calendars);
$response['select'] = html::span('folder-select', $this->gettext('saveincalendar')
. '&nbsp;'
. $calendar_select->show($is_shared ? $existing['calendar'] : $default_calendar['id'])
);
}
else if (!empty($data['nosave'])) {
$response['select'] = html::tag('input', ['type' => 'hidden', 'name' => 'calendar', 'id' => 'itip-saveto', 'value' => '']);
}
// render small agenda view for the respective day
if ($data['method'] == 'REQUEST' && !empty($data['date']) && $response['action'] == 'rsvp') {
$event_start = rcube_utils::anytodatetime($data['date']);
$day_start = new Datetime(gmdate('Y-m-d 00:00', $data['date']), $this->lib->timezone);
$day_end = new Datetime(gmdate('Y-m-d 23:59', $data['date']), $this->lib->timezone);
// get events on that day from the user's personal calendars
$calendars = $this->driver->list_calendars(calendar_driver::FILTER_PERSONAL);
$events = $this->driver->load_events($day_start->format('U'), $day_end->format('U'), null, array_keys($calendars));
usort($events, function($a, $b) { return $a['start'] > $b['start'] ? 1 : -1; });
$before = $after = [];
foreach ($events as $event) {
// TODO: skip events with free_busy == 'free' ?
if ($event['uid'] == $data['uid']
|| $event['end'] < $day_start || $event['start'] > $day_end
|| $event['status'] == 'CANCELLED'
|| (!empty($event['className']) && strpos($event['className'], 'declined') !== false)
) {
continue;
}
if ($event['start'] < $event_start) {
$before[] = $this->mail_agenda_event_row($event);
}
else {
$after[] = $this->mail_agenda_event_row($event);
}
}
$response['append'] = [
'selector' => '.calendar-agenda-preview',
'replacements' => [
'%before%' => !empty($before) ? join("\n", array_slice($before, -3)) : html::div('event-row no-event', $this->gettext('noearlierevents')),
'%after%' => !empty($after) ? join("\n", array_slice($after, 0, 3)) : html::div('event-row no-event', $this->gettext('nolaterevents')),
],
];
}
$this->rc->output->command('plugin.update_itip_object_status', $response);
}
/**
* Handler for calendar/itip-remove requests
*/
function event_itip_remove()
{
$uid = rcube_utils::get_input_value('uid', rcube_utils::INPUT_POST);
$instance = rcube_utils::get_input_value('_instance', rcube_utils::INPUT_POST);
$savemode = rcube_utils::get_input_value('_savemode', rcube_utils::INPUT_POST);
$listmode = calendar_driver::FILTER_WRITEABLE | calendar_driver::FILTER_PERSONAL;
$success = false;
// search for event if only UID is given
if ($event = $this->driver->get_event(['uid' => $uid, '_instance' => $instance], $listmode)) {
$event['_savemode'] = $savemode;
$success = $this->driver->remove_event($event, true);
}
if ($success) {
$this->rc->output->show_message('calendar.successremoval', 'confirmation');
}
else {
$this->rc->output->show_message('calendar.errorsaving', 'error');
}
}
/**
* Handler for URLs that allow an invitee to respond on his invitation mail
*/
public function itip_attend_response($p)
{
$this->setup();
if ($p['action'] == 'attend') {
$this->ui->init();
$this->rc->output->set_env('task', 'calendar'); // override some env vars
$this->rc->output->set_env('refresh_interval', 0);
$this->rc->output->set_pagetitle($this->gettext('calendar'));
$itip = $this->load_itip();
$token = rcube_utils::get_input_value('_t', rcube_utils::INPUT_GPC);
// read event info stored under the given token
if ($invitation = $itip->get_invitation($token)) {
$this->token = $token;
$this->event = $invitation['event'];
// show message about cancellation
if (!empty($invitation['cancelled'])) {
$this->invitestatus = html::div('rsvp-status declined', $itip->gettext('eventcancelled'));
}
// save submitted RSVP status
else if (!empty($_POST['rsvp'])) {
$status = null;
foreach (['accepted', 'tentative', 'declined'] as $method) {
if ($_POST['rsvp'] == $itip->gettext('itip' . $method)) {
$status = $method;
break;
}
}
// send itip reply to organizer
$invitation['event']['comment'] = rcube_utils::get_input_value('_comment', rcube_utils::INPUT_POST);
if ($status && $itip->update_invitation($invitation, $invitation['attendee'], strtoupper($status))) {
$this->invitestatus = html::div('rsvp-status ' . strtolower($status), $itip->gettext('youhave'.strtolower($status)));
}
else {
$this->rc->output->command('display_message', $this->gettext('errorsaving'), 'error', -1);
}
// if user is logged in...
// FIXME: we should really consider removing this functionality
// it's confusing that it creates/updates an event only for logged-in user
// what if the logged-in user is not the same as the attendee?
if ($this->rc->user->ID) {
$this->load_driver();
$invitation = $itip->get_invitation($token);
$existing = $this->driver->get_event($this->event);
// save the event to his/her default calendar if not yet present
if (!$existing && ($calendar = $this->get_default_calendar())) {
$invitation['event']['calendar'] = $calendar['id'];
if ($this->driver->new_event($invitation['event'])) {
$msg = $this->gettext(['name' => 'importedsuccessfully', 'vars' => ['calendar' => $calendar['name']]]);
$this->rc->output->command('display_message', $msg, 'confirmation');
}
else {
$this->rc->output->command('display_message', $this->gettext('errorimportingevent'), 'error');
}
}
else if ($existing
&& ($this->event['sequence'] >= $existing['sequence']
|| $this->event['changed'] >= $existing['changed'])
&& ($calendar = $this->driver->get_calendar($existing['calendar']))
) {
$this->event = $invitation['event'];
$this->event['id'] = $existing['id'];
unset($this->event['comment']);
// merge attendees status
// e.g. preserve my participant status for regular updates
$this->lib->merge_attendees($this->event, $existing, $status);
// update attachments list
$event['deleted_attachments'] = true;
// show me as free when declined (#1670)
if ($status == 'declined') {
$this->event['free_busy'] = 'free';
}
if ($this->driver->edit_event($this->event)) {
$msg = $this->gettext(['name' => 'updatedsuccessfully', 'vars' => ['calendar' => $calendar->get_name()]]);
$this->rc->output->command('display_message', $msg, 'confirmation');
}
else {
$this->rc->output->command('display_message', $this->gettext('errorimportingevent'), 'error');
}
}
}
}
$this->register_handler('plugin.event_inviteform', [$this, 'itip_event_inviteform']);
$this->register_handler('plugin.event_invitebox', [$this->ui, 'event_invitebox']);
if (empty($this->invitestatus)) {
$this->itip->set_rsvp_actions(['accepted', 'tentative', 'declined']);
$this->register_handler('plugin.event_rsvp_buttons', [$this->ui, 'event_rsvp_buttons']);
}
$this->rc->output->set_pagetitle($itip->gettext('itipinvitation') . ' ' . $this->event['title']);
}
else {
$this->rc->output->command('display_message', $this->gettext('itipinvalidrequest'), 'error', -1);
}
$this->rc->output->send('calendar.itipattend');
}
}
/**
*
*/
public function itip_event_inviteform($attrib)
{
$hidden = new html_hiddenfield(['name' => "_t", 'value' => $this->token]);
return html::tag('form', [
'action' => $this->rc->url(['task' => 'calendar', 'action' => 'attend']),
'method' => 'post',
'noclose' => true
] + $attrib
) . $hidden->show();
}
/**
*
*/
private function mail_agenda_event_row($event, $class = '')
{
if (!empty($event['allday'])) {
$time = $this->gettext('all-day');
}
else {
$start = is_object($event['start']) ? clone $event['start'] : $event['start'];
$end = is_object($event['end']) ? clone $event['end'] : $event['end'];
$time = $this->rc->format_date($start, $this->rc->config->get('time_format'))
. ' - ' . $this->rc->format_date($end, $this->rc->config->get('time_format'));
}
return html::div(rtrim('event-row ' . ($class ?: $event['className'])),
html::span('event-date', $time)
. html::span('event-title', rcube::Q($event['title']))
);
}
/**
*
*/
public function mail_messages_list($p)
{
if (!empty($p['cols']) && in_array('attachment', (array) $p['cols']) && !empty($p['messages'])) {
foreach ($p['messages'] as $header) {
$part = new StdClass;
$part->mimetype = $header->ctype;
if (libcalendaring::part_is_vcalendar($part)) {
$header->list_flags['attachmentClass'] = 'ical';
}
else if (in_array($header->ctype, ['multipart/alternative', 'multipart/mixed'])) {
// TODO: fetch bodystructure and search for ical parts. Maybe too expensive?
if (!empty($header->structure) && !empty($header->structure->parts)) {
foreach ($header->structure->parts as $part) {
if (libcalendaring::part_is_vcalendar($part)
&& !empty($part->ctype_parameters['method'])
) {
$header->list_flags['attachmentClass'] = 'ical';
break;
}
}
}
}
}
}
}
/**
* Add UI element to copy event invitations or updates to the calendar
*/
public function mail_messagebody_html($p)
{
// load iCalendar functions (if necessary)
if (!empty($this->lib->ical_parts)) {
$this->get_ical();
$this->load_itip();
}
$html = '';
$has_events = false;
$ical_objects = $this->lib->get_mail_ical_objects();
// show a box for every event in the file
foreach ($ical_objects as $idx => $event) {
if ($event['_type'] != 'event') {
// skip non-event objects (#2928)
continue;
}
$has_events = true;
// get prepared inline UI for this event object
if ($ical_objects->method) {
$append = '';
$date_str = $this->rc->format_date(clone $event['start'], $this->rc->config->get('date_format'), empty($event['start']->_dateonly));
$date = new DateTime($event['start']->format('Y-m-d') . ' 12:00:00', new DateTimeZone('UTC'));
// prepare a small agenda preview to be filled with actual event data on async request
if ($ical_objects->method == 'REQUEST') {
$append = html::div('calendar-agenda-preview',
html::tag('h3', 'preview-title', $this->gettext('agenda') . ' ' . html::span('date', $date_str))
. '%before%' . $this->mail_agenda_event_row($event, 'current') . '%after%'
);
}
$html .= html::div('calendar-invitebox invitebox boxinformation',
$this->itip->mail_itip_inline_ui(
$event,
$ical_objects->method,
$ical_objects->mime_id . ':' . $idx,
'calendar',
rcube_utils::anytodatetime($ical_objects->message_date),
$this->rc->url(['task' => 'calendar']) . '&view=agendaDay&date=' . $date->format('U')
) . $append
);
}
// limit listing
if ($idx >= 3) {
break;
}
}
// prepend event boxes to message body
if ($html) {
$this->ui->init();
$p['content'] = $html . $p['content'];
$this->rc->output->add_label('calendar.savingdata','calendar.deleteventconfirm','calendar.declinedeleteconfirm');
}
// add "Save to calendar" button into attachment menu
if ($has_events) {
$this->add_button([
'id' => 'attachmentsavecal',
'name' => 'attachmentsavecal',
'type' => 'link',
'wrapper' => 'li',
'command' => 'attachment-save-calendar',
'class' => 'icon calendarlink disabled',
'classact' => 'icon calendarlink active',
'innerclass' => 'icon calendar',
'label' => 'calendar.savetocalendar',
],
'attachmentmenu'
);
}
return $p;
}
/**
* Handler for POST request to import an event attached to a mail message
*/
public function mail_import_itip()
{
$itip_sending = $this->rc->config->get('calendar_itip_send_option', $this->defaults['calendar_itip_send_option']);
$uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
$mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
$mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST);
$status = rcube_utils::get_input_value('_status', rcube_utils::INPUT_POST);
$delete = intval(rcube_utils::get_input_value('_del', rcube_utils::INPUT_POST));
$noreply = intval(rcube_utils::get_input_value('_noreply', rcube_utils::INPUT_POST));
$noreply = $noreply || $status == 'needs-action' || $itip_sending === 0;
$instance = rcube_utils::get_input_value('_instance', rcube_utils::INPUT_POST);
$savemode = rcube_utils::get_input_value('_savemode', rcube_utils::INPUT_POST);
$comment = rcube_utils::get_input_value('_comment', rcube_utils::INPUT_POST);
$error_msg = $this->gettext('errorimportingevent');
$success = false;
$deleted = false;
if ($status == 'delegated') {
$to = rcube_utils::get_input_value('_to', rcube_utils::INPUT_POST, true);
$delegates = rcube_mime::decode_address_list($to, 1, false);
$delegate = reset($delegates);
if (empty($delegate) || empty($delegate['mailto'])) {
$this->rc->output->command('display_message', $this->rc->gettext('libcalendaring.delegateinvalidaddress'), 'error');
return;
}
}
// successfully parsed events?
if ($event = $this->lib->mail_get_itip_object($mbox, $uid, $mime_id, 'event')) {
// forward iTip request to delegatee
if (!empty($delegate)) {
$rsvpme = rcube_utils::get_input_value('_rsvp', rcube_utils::INPUT_POST);
$itip = $this->load_itip();
$event['comment'] = $comment;
if ($itip->delegate_to($event, $delegate, !empty($rsvpme))) {
$this->rc->output->show_message('calendar.itipsendsuccess', 'confirmation');
}
else {
$this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
}
unset($event['comment']);
// the delegator is set to non-participant, thus save as non-blocking
$event['free_busy'] = 'free';
}
$mode = calendar_driver::FILTER_PERSONAL
| calendar_driver::FILTER_SHARED
| calendar_driver::FILTER_WRITEABLE;
// find writeable calendar to store event
$cal_id = rcube_utils::get_input_value('_folder', rcube_utils::INPUT_POST);
$dontsave = $cal_id === '' && $event['_method'] == 'REQUEST';
$calendars = $this->driver->list_calendars($mode);
$calendar = isset($calendars[$cal_id]) ? $calendars[$cal_id] : null;
// select default calendar except user explicitly selected 'none'
if (!$calendar && !$dontsave) {
$calendar = $this->get_default_calendar($calendars);
}
$metadata = [
'uid' => $event['uid'],
'_instance' => isset($event['_instance']) ? $event['_instance'] : null,
'changed' => is_object($event['changed']) ? $event['changed']->format('U') : 0,
'sequence' => intval($event['sequence']),
'fallback' => strtoupper($status),
'method' => $event['_method'],
'task' => 'calendar',
];
// update my attendee status according to submitted method
if (!empty($status)) {
$organizer = null;
$emails = $this->get_user_emails();
foreach ($event['attendees'] as $i => $attendee) {
if ($attendee['role'] == 'ORGANIZER') {
$organizer = $attendee;
}
else if (!empty($attendee['email']) && in_array(strtolower($attendee['email']), $emails)) {
$event['attendees'][$i]['status'] = strtoupper($status);
if (!in_array($event['attendees'][$i]['status'], ['NEEDS-ACTION', 'DELEGATED'])) {
$event['attendees'][$i]['rsvp'] = false; // unset RSVP attribute
}
$metadata['attendee'] = $attendee['email'];
$metadata['rsvp'] = $attendee['role'] != 'NON-PARTICIPANT';
$reply_sender = $attendee['email'];
$event_attendee = $attendee;
}
}
// add attendee with this user's default identity if not listed
if (!$reply_sender) {
$sender_identity = $this->rc->user->list_emails(true);
$event['attendees'][] = [
'name' => $sender_identity['name'],
'email' => $sender_identity['email'],
'role' => 'OPT-PARTICIPANT',
'status' => strtoupper($status),
];
$metadata['attendee'] = $sender_identity['email'];
}
}
// save to calendar
if ($calendar && !empty($calendar['editable'])) {
// check for existing event with the same UID
$existing = $this->find_event($event, $mode);
// we'll create a new copy if user decided to change the calendar
if ($existing && $cal_id && $calendar && $calendar['id'] != $existing['calendar']) {
$existing = null;
}
if ($existing) {
$calendar = $calendars[$existing['calendar']];
// forward savemode for correct updates of recurring events
$existing['_savemode'] = $savemode ?: (!empty($event['_savemode']) ? $event['_savemode'] : null);
// only update attendee status
if ($event['_method'] == 'REPLY') {
$existing_attendee_index = -1;
$event_attendee = null;
$update_attendees = [];
if ($attendee = $this->itip->find_reply_attendee($event)) {
$event_attendee = $attendee;
$update_attendees[] = $attendee;
$metadata['fallback'] = $attendee['status'];
$metadata['attendee'] = $attendee['email'];
$metadata['rsvp'] = !empty($attendee['rsvp']) || $attendee['role'] != 'NON-PARTICIPANT';
$existing_attendee_emails = [];
// Find the attendee to update
foreach ($existing['attendees'] as $i => $existing_attendee) {
$existing_attendee_emails[] = $existing_attendee['email'];
if ($this->itip->compare_email($existing_attendee['email'], $attendee['email'])) {
$existing_attendee_index = $i;
}
}
if ($attendee['status'] == 'DELEGATED') {
//Also find and copy the delegatee
$delegatee_email = $attendee['email'];
$delegatees = array_filter($event['attendees'], function($attendee) use ($delegatee_email){ return $attendee['role'] != 'ORGANIZER' && $this->itip->compare_email($attendee['delegated-from'], $delegatee_email); });
if ($delegatee = $this->itip->find_attendee_by_email($event['attendees'], 'delegated-from', $attendee['email'])) {
$update_attendees[] = $delegatee;
if (!in_array_nocase($delegatee['email'], $existing_attendee_emails)) {
$existing['attendees'][] = $delegated_attendee;
}
}
}
}
// if delegatee has declined, set delegator's RSVP=True
if ($event_attendee
&& $event_attendee['status'] == 'DECLINED'
&& !empty($event_attendee['delegated-from'])
) {
foreach ($existing['attendees'] as $i => $attendee) {
if ($attendee['email'] == $event_attendee['delegated-from']) {
$existing['attendees'][$i]['rsvp'] = true;
break;
}
}
}
// found matching attendee entry in both existing and new events
if ($existing_attendee_index >= 0 && $event_attendee) {
$existing['attendees'][$existing_attendee_index] = $event_attendee;
$success = $this->driver->update_attendees($existing, $update_attendees);
}
// update the entire attendees block
else if (
($event['sequence'] >= $existing['sequence'] || $event['changed'] >= $existing['changed'])
&& $event_attendee
) {
$existing['attendees'][] = $event_attendee;
$success = $this->driver->update_attendees($existing, $update_attendees);
}
else if (!$event_attendee) {
$error_msg = $this->gettext('errorunknownattendee');
}
else {
$error_msg = $this->gettext('newerversionexists');
}
}
// delete the event when declined (#1670)
else if ($status == 'declined' && $delete) {
$deleted = $this->driver->remove_event($existing, true);
$success = true;
}
// import the (newer) event
else if ($event['sequence'] >= $existing['sequence'] || $event['changed'] >= $existing['changed']) {
$event['id'] = $existing['id'];
$event['calendar'] = $existing['calendar'];
// merge attendees status
// e.g. preserve my participant status for regular updates
$this->lib->merge_attendees($event, $existing, $status);
// set status=CANCELLED on CANCEL messages
if ($event['_method'] == 'CANCEL') {
$event['status'] = 'CANCELLED';
}
// update attachments list, allow attachments update only on REQUEST (#5342)
if ($event['_method'] == 'REQUEST') {
$event['deleted_attachments'] = true;
}
else {
unset($event['attachments']);
}
// show me as free when declined (#1670)
if ($status == 'declined'
|| (!empty($event['status']) && $event['status'] == 'CANCELLED')
|| $event_attendee['role'] == 'NON-PARTICIPANT'
) {
$event['free_busy'] = 'free';
}
$success = $this->driver->edit_event($event);
}
else if (!empty($status)) {
$existing['attendees'] = $event['attendees'];
if ($status == 'declined' || $event_attendee['role'] == 'NON-PARTICIPANT') {
// show me as free when declined (#1670)
$existing['free_busy'] = 'free';
}
$success = $this->driver->edit_event($existing);
}
else {
$error_msg = $this->gettext('newerversionexists');
}
}
else if (!$existing && ($status != 'declined' || $this->rc->config->get('kolab_invitation_calendars'))) {
if ($status == 'declined'
|| $event['status'] == 'CANCELLED'
|| $event_attendee['role'] == 'NON-PARTICIPANT'
) {
$event['free_busy'] = 'free';
}
// if the RSVP reply only refers to a single instance:
// store unmodified master event with current instance as exception
if (!empty($instance) && !empty($savemode) && $savemode != 'all') {
$master = $this->lib->mail_get_itip_object($mbox, $uid, $mime_id, 'event');
if ($master['recurrence'] && empty($master['_instance'])) {
// compute recurring events until this instance's date
if ($recurrence_date = rcube_utils::anytodatetime($instance, $master['start']->getTimezone())) {
$recurrence_date->setTime(23,59,59);
foreach ($this->driver->get_recurring_events($master, $master['start'], $recurrence_date) as $recurring) {
if ($recurring['_instance'] == $instance) {
// copy attendees block with my partstat to exception
$recurring['attendees'] = $event['attendees'];
$master['recurrence']['EXCEPTIONS'][] = $recurring;
$event = $recurring; // set reference for iTip reply
break;
}
}
$master['calendar'] = $event['calendar'] = $calendar['id'];
$success = $this->driver->new_event($master);
}
else {
$master = null;
}
}
else {
$master = null;
}
}
// save to the selected/default calendar
if (!$master) {
$event['calendar'] = $calendar['id'];
$success = $this->driver->new_event($event);
}
}
else if ($status == 'declined') {
$error_msg = null;
}
}
else if ($status == 'declined' || $dontsave) {
$error_msg = null;
}
else {
$error_msg = $this->gettext('nowritecalendarfound');
}
}
if ($success) {
if ($event['_method'] == 'REPLY') {
$message = 'attendeupdateesuccess';
}
else {
$message = $deleted ? 'successremoval' : ($existing ? 'updatedsuccessfully' : 'importedsuccessfully');
}
$msg = $this->gettext(['name' => $message, 'vars' => ['calendar' => $calendar['name']]]);
$this->rc->output->command('display_message', $msg, 'confirmation');
}
if ($success || $dontsave) {
$metadata['calendar'] = isset($event['calendar']) ? $event['calendar'] : null;
$metadata['nosave'] = $dontsave;
$metadata['rsvp'] = !empty($metadata['rsvp']);
$metadata['after_action'] = $this->rc->config->get('calendar_itip_after_action', $this->defaults['calendar_itip_after_action']);
$this->rc->output->command('plugin.itip_message_processed', $metadata);
$error_msg = null;
}
else if ($error_msg) {
$this->rc->output->command('display_message', $error_msg, 'error');
}
// send iTip reply
if ($event['_method'] == 'REQUEST' && !empty($organizer) && !$noreply
&& !in_array(strtolower($organizer['email']), $emails) && !$error_msg
) {
$event['comment'] = $comment;
$itip = $this->load_itip();
$itip->set_sender_email($reply_sender);
if ($itip->send_itip_message($event, 'REPLY', $organizer, 'itipsubject' . $status, 'itipmailbody' . $status)) {
$mailto = $organizer['name'] ? $organizer['name'] : $organizer['email'];
$msg = $this->gettext(['name' => 'sentresponseto', 'vars' => ['mailto' => $mailto]]);
$this->rc->output->command('display_message', $msg, 'confirmation');
}
else {
$this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
}
}
$this->rc->output->send();
}
/**
* Handler for calendar/itip-remove requests
*/
function mail_itip_decline_reply()
{
$uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
$mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
$mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST);
if (($event = $this->lib->mail_get_itip_object($mbox, $uid, $mime_id, 'event'))
&& $event['_method'] == 'REPLY'
) {
$event['comment'] = rcube_utils::get_input_value('_comment', rcube_utils::INPUT_POST);
foreach ($event['attendees'] as $_attendee) {
if ($_attendee['role'] != 'ORGANIZER') {
$attendee = $_attendee;
break;
}
}
$itip = $this->load_itip();
if ($itip->send_itip_message($event, 'CANCEL', $attendee, 'itipsubjectcancel', 'itipmailbodycancel')) {
$mailto = !empty($attendee['name']) ? $attendee['name'] : $attendee['email'];
$msg = $this->gettext(['name' => 'sentresponseto', 'vars' => ['mailto' => $mailto]]);
$this->rc->output->command('display_message', $msg, 'confirmation');
}
else {
$this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
}
}
else {
$this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
}
}
/**
* Handler for calendar/itip-delegate requests
*/
function mail_itip_delegate()
{
// forward request to mail_import_itip() with the right status
$_POST['_status'] = $_REQUEST['_status'] = 'delegated';
$this->mail_import_itip();
}
/**
* Import the full payload from a mail message attachment
*/
public function mail_import_attachment()
{
$uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
$mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
$mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST);
$charset = RCUBE_CHARSET;
// establish imap connection
$imap = $this->rc->get_storage();
$imap->set_folder($mbox);
if ($uid && $mime_id) {
$part = $imap->get_message_part($uid, $mime_id);
// $headers = $imap->get_message_headers($uid);
if ($part) {
if (!empty($part->ctype_parameters['charset'])) {
$charset = $part->ctype_parameters['charset'];
}
$events = $this->get_ical()->import($part, $charset);
}
}
$success = $existing = 0;
if (!empty($events)) {
// find writeable calendar to store event
$cal_id = !empty($_REQUEST['_calendar']) ? rcube_utils::get_input_value('_calendar', rcube_utils::INPUT_POST) : null;
$calendars = $this->driver->list_calendars(calendar_driver::FILTER_PERSONAL);
foreach ($events as $event) {
// save to calendar
$calendar = !empty($calendars[$cal_id]) ? $calendars[$cal_id] : $this->get_default_calendar();
if ($calendar && $calendar['editable'] && $event['_type'] == 'event') {
$event['calendar'] = $calendar['id'];
if (!$this->driver->get_event($event['uid'], calendar_driver::FILTER_WRITEABLE)) {
$success += (bool)$this->driver->new_event($event);
}
else {
$existing++;
}
}
}
}
if ($success) {
$msg = $this->gettext(['name' => 'importsuccess', 'vars' => ['nr' => $success]]);
$this->rc->output->command('display_message', $msg, 'confirmation');
}
else if ($existing) {
$this->rc->output->command('display_message', $this->gettext('importwarningexists'), 'warning');
}
else {
$this->rc->output->command('display_message', $this->gettext('errorimportingevent'), 'error');
}
}
/**
* Read email message and return contents for a new event based on that message
*/
public function mail_message2event()
{
$this->ui->init();
$this->ui->addJS();
$this->ui->init_templates();
$this->ui->calendar_list([], true); // set env['calendars']
$uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET);
$mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GET);
$event = [];
// establish imap connection
$imap = $this->rc->get_storage();
$message = new rcube_message($uid, $mbox);
if ($message->headers) {
$event['title'] = trim($message->subject);
$event['description'] = trim($message->first_text_part());
$this->load_driver();
// add a reference to the email message
if ($msgref = $this->driver->get_message_reference($message->headers, $mbox)) {
$event['links'] = [$msgref];
}
// copy mail attachments to event
else if ($message->attachments) {
$eventid = 'cal-';
if (empty($_SESSION[self::SESSION_KEY]) || $_SESSION[self::SESSION_KEY]['id'] != $eventid) {
$_SESSION[self::SESSION_KEY] = [
'id' => $eventid,
'attachments' => [],
];
}
foreach ((array) $message->attachments as $part) {
$attachment = [
'data' => $imap->get_message_part($uid, $part->mime_id, $part),
'size' => $part->size,
'name' => $part->filename,
'mimetype' => $part->mimetype,
'group' => $eventid,
];
$attachment = $this->rc->plugins->exec_hook('attachment_save', $attachment);
if (!empty($attachment['status']) && !$attachment['abort']) {
$id = $attachment['id'];
$attachment['classname'] = rcube_utils::file2class($attachment['mimetype'], $attachment['name']);
// store new attachment in session
unset($attachment['status'], $attachment['abort'], $attachment['data']);
$_SESSION[self::SESSION_KEY]['attachments'][$id] = $attachment;
$attachment['id'] = 'rcmfile' . $attachment['id']; // add prefix to consider it 'new'
$event['attachments'][] = $attachment;
}
}
}
$this->rc->output->set_env('event_prop', $event);
}
else {
$this->rc->output->command('display_message', $this->gettext('messageopenerror'), 'error');
}
$this->rc->output->send('calendar.dialog');
}
/**
* Handler for the 'message_compose' plugin hook. This will check for
* a compose parameter 'calendar_event' and create an attachment with the
* referenced event in iCal format
*/
public function mail_message_compose($args)
{
// set the submitted event ID as attachment
if (!empty($args['param']['calendar_event'])) {
$this->load_driver();
list($cal, $id) = explode(':', $args['param']['calendar_event'], 2);
if ($event = $this->driver->get_event(['id' => $id, 'calendar' => $cal])) {
$filename = asciiwords($event['title']);
if (empty($filename)) {
$filename = 'event';
}
// save ics to a temp file and register as attachment
$tmp_path = tempnam($this->rc->config->get('temp_dir'), 'rcmAttmntCal');
$export = $this->get_ical()->export([$event], '', false, [$this->driver, 'get_attachment_body']);
file_put_contents($tmp_path, $export);
$args['attachments'][] = [
'path' => $tmp_path,
'name' => $filename . '.ics',
'mimetype' => 'text/calendar',
'size' => filesize($tmp_path),
];
$args['param']['subject'] = $event['title'];
}
}
return $args;
}
/**
* Create a Nextcould Talk room
*/
public function talk_room_create()
{
require_once __DIR__ . '/lib/calendar_nextcloud_api.php';
$api = new calendar_nextcloud_api();
$name = (string) rcube_utils::get_input_value('_name', rcube_utils::INPUT_POST);
$room_url = $api->talk_room_create($name);
if ($room_url) {
$this->rc->output->command('plugin.talk_room_created', ['url' => $room_url]);
}
else {
$this->rc->output->command('display_message', $this->gettext('talkroomcreateerror'), 'error');
}
}
/**
* Update a Nextcould Talk room
*/
public function talk_room_update($event)
{
// If a room is assigned to the event...
if (
($talk_url = $this->rc->config->get('calendar_nextcloud_url'))
&& isset($event['attendees'])
&& !empty($event['location'])
&& strpos($event['location'], unslashify($talk_url) . '/call/') === 0
) {
$participants = [];
$organizer = null;
// ollect participants' and organizer's email addresses
foreach ($event['attendees'] as $attendee) {
if (!empty($attendee['email'])) {
if ($attendee['role'] == 'ORGANIZER') {
$organizer = $attendee['email'];
}
else if ($attendee['cutype'] == 'INDIVIDUAL') {
$participants[] = $attendee['email'];
}
}
}
// If the event is owned by the current user update the room
if ($organizer && in_array($organizer, $this->get_user_emails())) {
require_once __DIR__ . '/lib/calendar_nextcloud_api.php';
$api = new calendar_nextcloud_api();
$api->talk_room_update($event['location'], $participants);
}
}
}
/**
* Get a list of email addresses of the current user (from login and identities)
*/
public function get_user_emails()
{
return $this->lib->get_user_emails();
}
/**
* Build an absolute URL with the given parameters
*/
public function get_url($param = [])
{
$param += ['task' => 'calendar'];
return $this->rc->url($param, true, true);
}
public function ical_feed_hash($source)
{
return base64_encode($this->rc->user->get_username() . ':' . $source);
}
/**
* Handler for user_delete plugin hook
*/
public function user_delete($args)
{
// delete itipinvitations entries related to this user
$db = $this->rc->get_dbh();
$table_itipinvitations = $db->table_name('itipinvitations', true);
$db->query("DELETE FROM $table_itipinvitations WHERE `user_id` = ?", $args['user']->ID);
$this->setup();
$this->load_driver();
return $this->driver->user_delete($args);
}
/**
* Find first occurrence of a recurring event excluding start date
*
* @param array $event Event data (with 'start' and 'recurrence')
*
* @return DateTime Date of the first occurrence
*/
public function find_first_occurrence($event)
{
// Make sure libkolab plugin is loaded in case of Kolab driver
$this->load_driver();
// Use libkolab to compute recurring events (and libkolab plugin)
// Horde-based fallback has many bugs
if (class_exists('kolabformat') && class_exists('kolabcalendaring') && class_exists('kolab_date_recurrence')) {
$object = kolab_format::factory('event', 3.0);
$object->set($event);
$recurrence = new kolab_date_recurrence($object);
}
else {
// fallback to libcalendaring (Horde-based) recurrence implementation
require_once(__DIR__ . '/lib/calendar_recurrence.php');
$recurrence = new calendar_recurrence($this, $event);
}
return $recurrence->first_occurrence();
}
/**
* Get date-time input from UI and convert to unix timestamp
*/
protected function input_timestamp($name, $type)
{
$ts = rcube_utils::get_input_value($name, $type);
if ($ts && (!is_numeric($ts) || strpos($ts, 'T'))) {
$ts = new DateTime($ts, $this->timezone);
$ts = $ts->getTimestamp();
}
return $ts;
}
/**
* Magic getter for public access to protected members
*/
public function __get($name)
{
switch ($name) {
case 'ical':
return $this->get_ical();
case 'itip':
return $this->load_itip();
case 'driver':
$this->load_driver();
return $this->driver;
}
return null;
}
}
diff --git a/plugins/calendar/composer.json b/plugins/calendar/composer.json
index 0f7028a2..c1bfe40e 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": ">=5.4.0",
+ "php": ">=7.4.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 ac0d8b41..40648922 100644
--- a/plugins/calendar/drivers/caldav/caldav_calendar.php
+++ b/plugins/calendar/drivers/caldav/caldav_calendar.php
@@ -1,897 +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'] = str_replace('-invitation', '', $record['className']);
+ $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['recurrence_id']) && empty($record['_instance'])) {
+ 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')) {
$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/caldav/caldav_driver.php b/plugins/calendar/drivers/caldav/caldav_driver.php
index b26c2f23..1f6c0bdd 100644
--- a/plugins/calendar/drivers/caldav/caldav_driver.php
+++ b/plugins/calendar/drivers/caldav/caldav_driver.php
@@ -1,603 +1,604 @@
<?php
/**
* CalDAV driver for the Calendar plugin.
*
* @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/>.
*/
require_once(__DIR__ . '/../kolab/kolab_driver.php');
class caldav_driver extends kolab_driver
{
// features this backend supports
public $alarms = true;
public $attendees = true;
public $freebusy = true;
public $attachments = false; // TODO
public $undelete = false; // TODO
public $alarm_types = ['DISPLAY', 'AUDIO'];
public $categoriesimmutable = true;
/**
* Default constructor
*/
public function __construct($cal)
{
$cal->require_plugin('libkolab');
// load helper classes *after* libkolab has been loaded (#3248)
require_once(__DIR__ . '/caldav_calendar.php');
// require_once(__DIR__ . '/kolab_user_calendar.php');
// require_once(__DIR__ . '/caldav_invitation_calendar.php');
$this->cal = $cal;
$this->rc = $cal->rc;
// Initialize the CalDAV storage
$url = $this->rc->config->get('calendar_caldav_server', 'http://localhost');
$this->storage = new kolab_storage_dav($url);
$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);
// TODO: get configuration for the Bonnie API
// $this->bonnie_api = libkolab::get_bonnie_api();
}
/**
* Read available calendars from server
*/
protected function _read_calendars()
{
// already read sources
if (isset($this->calendars)) {
return $this->calendars;
}
// get all folders that support VEVENT, sorted by namespace/name
$folders = $this->storage->get_folders('event');
// + $this->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 caldav_calendar
*/
protected function _to_calendar($folder)
{
if ($folder instanceof caldav_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 caldav_calendar($folder, $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();
$folders = $this->filter_calendars($filter);
$calendars = [];
$prefs = $this->rc->config->get('kolab_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) {
+ $parent_id = null;
/*
$path = explode('/', $cal->name);
// find parent
do {
array_pop($path);
$parent_id = $this->storage->folder_id(implode('/', $path));
}
while (count($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_dav::folder_hierarchy() above
// make sure we deal with caldav_calendar instances
$cal = $this->_to_calendar($cal);
$this->calendars[$cal->id] = $cal;
$is_user = ($cal instanceof caldav_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' => !isset($prefs[$cal->id]['active']) || !empty($prefs[$cal->id]['active']),
'owner' => $cal->get_owner(),
'removable' => !$cal->default,
// extras to hide some elements in the UI
'subscriptions' => $cal->subscriptions,
'driver' => 'caldav',
];
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 caldav_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 the caldav_calendar instance for the given calendar ID
*
* @param string Calendar identifier
*
* @return ?caldav_calendar Object nor null if calendar doesn't exist
*/
public function get_calendar($id)
{
$this->_read_calendars();
// create calendar object if necessary
if (empty($this->calendars[$id])) {
if (in_array($id, [self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED])) {
return new caldav_invitation_calendar($id, $this->cal);
}
// for unsubscribed calendar folders
if ($id !== self::BIRTHDAY_CALENDAR_ID) {
$calendar = caldav_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['alarms'] = !empty($prop['showalarms']);
$id = $this->storage->folder_update($prop);
if ($id === false) {
return false;
}
$prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []);
$prefs['kolab_calendars'][$id]['active'] = true;
$this->rc->user->save_prefs($prefs);
return $id;
}
/**
* Update properties of an existing calendar
*
* @see calendar_driver::edit_calendar()
*/
public function edit_calendar($prop)
{
$id = $prop['id'];
if (!in_array($id, [self::BIRTHDAY_CALENDAR_ID, self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED])) {
$prop['type'] = 'event';
$prop['alarms'] = !empty($prop['showalarms']);
return $this->storage->folder_update($prop) !== false;
}
// fallback to local prefs for special calendars
$prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []);
unset($prefs['kolab_calendars'][$id]['showalarms']);
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'])) {
return false;
}
// save state in local prefs
if (isset($prop['active'])) {
$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;
}
/**
* Delete the given calendar with all its contents
*
* @see calendar_driver::delete_calendar()
*/
public function delete_calendar($prop)
{
if (!empty($prop['id'])) {
if ($this->storage->folder_delete($prop['id'], 'event')) {
// remove folder from user prefs
$prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []);
if (isset($prefs['kolab_calendars'][$prop['id']])) {
unset($prefs['kolab_calendars'][$prop['id']]);
$this->rc->user->save_prefs($prefs);
}
return true;
}
}
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)
{
$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 caldav_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 caldav_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();
}
/**
* 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, 'caldav_driver::to_rcube_event');
return $events;
}
/**
* 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
$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
$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;
}
/**
* 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');
}
$form['props'] = [
'name' => $this->rc->gettext('properties'),
'fields' => [
'location' => $formfields['name'],
'color' => $formfields['color'],
'alarms' => $formfields['showalarms'],
],
];
return kolab_utils::folder_form($form, $folder, 'calendar', [], true);
}
}
diff --git a/plugins/calendar/drivers/calendar_driver.php b/plugins/calendar/drivers/calendar_driver.php
index 2c0fc6c8..c81421e7 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')) {
$valid = false;
}
if (empty($event['end']) || !is_object($event['end']) || !is_a($event['end'], 'DateTime')) {
$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 DateTime) {
- $bday = new DateTime($bday, new DateTimezone('UTC'));
+ 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/database/database_driver.php b/plugins/calendar/drivers/database/database_driver.php
index caa53316..e1ee1490 100644
--- a/plugins/calendar/drivers/database/database_driver.php
+++ b/plugins/calendar/drivers/database/database_driver.php
@@ -1,1530 +1,1531 @@
<?php
/**
* Database driver for the Calendar plugin
*
* @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/>.
*/
class database_driver extends calendar_driver
{
const DB_DATE_FORMAT = 'Y-m-d H:i:s';
public static $scheduling_properties = array('start', 'end', 'allday', 'recurrence', 'location', 'cancelled');
// features this backend supports
public $alarms = true;
public $attendees = true;
public $freebusy = false;
public $attachments = true;
public $alarm_types = array('DISPLAY');
private $rc;
private $cal;
private $cache = array();
private $calendars = array();
private $calendar_ids = '';
private $free_busy_map = array('free' => 0, 'busy' => 1, 'out-of-office' => 2, 'outofoffice' => 2, 'tentative' => 3);
private $sensitivity_map = array('public' => 0, 'private' => 1, 'confidential' => 2);
private $server_timezone;
private $db_events = 'events';
private $db_calendars = 'calendars';
private $db_attachments = 'attachments';
/**
* Default constructor
*/
public function __construct($cal)
{
$this->cal = $cal;
$this->rc = $cal->rc;
$this->server_timezone = new DateTimeZone(date_default_timezone_get());
// read database config
$db = $this->rc->get_dbh();
$this->db_events = $db->table_name($this->rc->config->get('db_table_events', $this->db_events));
$this->db_calendars = $db->table_name($this->rc->config->get('db_table_calendars', $this->db_calendars));
$this->db_attachments = $db->table_name($this->rc->config->get('db_table_attachments', $this->db_attachments));
$this->_read_calendars();
}
/**
* Read available calendars for the current user and store them internally
*/
private function _read_calendars()
{
$hidden = array_filter(explode(',', $this->rc->config->get('hidden_calendars', '')));
if (!empty($this->rc->user->ID)) {
$calendar_ids = array();
$result = $this->rc->db->query(
"SELECT *, `calendar_id` AS id FROM `{$this->db_calendars}`"
. " WHERE `user_id` = ?"
. " ORDER BY `name`",
$this->rc->user->ID
);
while ($result && ($arr = $this->rc->db->fetch_assoc($result))) {
$arr['showalarms'] = intval($arr['showalarms']);
$arr['active'] = !in_array($arr['id'], $hidden);
$arr['name'] = html::quote($arr['name']);
$arr['listname'] = html::quote($arr['name']);
$arr['rights'] = 'lrswikxteav';
$arr['editable'] = true;
$this->calendars[$arr['calendar_id']] = $arr;
$calendar_ids[] = $this->rc->db->quote($arr['calendar_id']);
}
$this->calendar_ids = join(',', $calendar_ids);
}
}
/**
* Get a list of available calendars from this source
*
* @param integer Bitmask defining filter criterias
*
* @return array List of calendars
*/
public function list_calendars($filter = 0)
{
// attempt to create a default calendar for this user
if (empty($this->calendars)) {
if ($this->create_calendar(array('name' => 'Default', 'color' => 'cc0000', 'showalarms' => true))) {
$this->_read_calendars();
}
}
$calendars = $this->calendars;
// filter active calendars
if ($filter & self::FILTER_ACTIVE) {
foreach ($calendars as $idx => $cal) {
if (!$cal['active']) {
unset($calendars[$idx]);
}
}
}
// 'personal' is unsupported in this driver
// append the virtual birthdays calendar
if ($this->rc->config->get('calendar_contact_birthdays', false)) {
$prefs = $this->rc->config->get('birthday_calendar', array('color' => '87CEFA'));
$hidden = array_filter(explode(',', $this->rc->config->get('hidden_calendars', '')));
$id = self::BIRTHDAY_CALENDAR_ID;
if (empty($active) || !in_array($id, $hidden)) {
$calendars[$id] = array(
'id' => $id,
'name' => $this->cal->gettext('birthdays'),
'listname' => $this->cal->gettext('birthdays'),
'color' => $prefs['color'],
'showalarms' => (bool)$this->rc->config->get('calendar_birthdays_alarm_type'),
'active' => !in_array($id, $hidden),
'group' => 'x-birthdays',
'editable' => false,
'default' => false,
'children' => false,
);
}
}
return $calendars;
}
/**
* 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)
{
$result = $this->rc->db->query(
"INSERT INTO `{$this->db_calendars}`"
. " (`user_id`, `name`, `color`, `showalarms`)"
. " VALUES (?, ?, ?, ?)",
$this->rc->user->ID,
$prop['name'],
strval($prop['color']),
!empty($prop['showalarms']) ? 1 : 0
);
if ($result) {
return $this->rc->db->insert_id($this->db_calendars);
}
return false;
}
/**
* Update properties of an existing calendar
*
* @see calendar_driver::edit_calendar()
*/
public function edit_calendar($prop)
{
// birthday calendar properties are saved in user prefs
if ($prop['id'] == self::BIRTHDAY_CALENDAR_ID) {
$prefs['birthday_calendar'] = $this->rc->config->get('birthday_calendar', array('color' => '87CEFA'));
if (isset($prop['color'])) {
$prefs['birthday_calendar']['color'] = $prop['color'];
}
if (isset($prop['showalarms'])) {
$prefs['calendar_birthdays_alarm_type'] = $prop['showalarms'] ? $this->alarm_types[0] : '';
}
$this->rc->user->save_prefs($prefs);
return true;
}
$query = $this->rc->db->query(
"UPDATE `{$this->db_calendars}`"
. " SET `name` = ?, `color` = ?, `showalarms` = ?"
. " WHERE `calendar_id` = ? AND `user_id` = ?",
$prop['name'],
strval($prop['color']),
$prop['showalarms'] ? 1 : 0,
$prop['id'],
$this->rc->user->ID
);
return $this->rc->db->affected_rows($query);
}
/**
* Set active/subscribed state of a calendar
* Save a list of hidden calendars in user prefs
*
* @see calendar_driver::subscribe_calendar()
*/
public function subscribe_calendar($prop)
{
$hidden = array_flip(explode(',', $this->rc->config->get('hidden_calendars', '')));
if ($prop['active']) {
unset($hidden[$prop['id']]);
}
else {
$hidden[$prop['id']] = 1;
}
return $this->rc->user->save_prefs(array('hidden_calendars' => join(',', array_keys($hidden))));
}
/**
* Delete the given calendar with all its contents
*
* @see calendar_driver::delete_calendar()
*/
public function delete_calendar($prop)
{
if (!$this->calendars[$prop['id']]) {
return false;
}
// events and attachments will be deleted by foreign key cascade
$query = $this->rc->db->query(
"DELETE FROM `{$this->db_calendars}` WHERE `calendar_id` = ? AND `user_id` = ?",
$prop['id'],
$this->rc->user->ID
);
return $this->rc->db->affected_rows($query);
}
/**
* 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)
{
// not implemented
return array();
}
/**
* Add a single event to the database
*
* @param array Hash array with event properties
* @see calendar_driver::new_event()
*/
public function new_event($event)
{
if (!$this->validate($event)) {
return false;
}
if (!empty($this->calendars)) {
if ($event['calendar'] && !$this->calendars[$event['calendar']]) {
return false;
}
if (!$event['calendar']) {
$event['calendar'] = reset(array_keys($this->calendars));
}
if ($event_id = $this->_insert_event($event)) {
$this->_update_recurring($event);
}
return $event_id;
}
return false;
}
/**
*
*/
private function _insert_event(&$event)
{
$event = $this->_save_preprocess($event);
$now = $this->rc->db->now();
$this->rc->db->query(
"INSERT INTO `{$this->db_events}`"
. " (`calendar_id`, `created`, `changed`, `uid`, `recurrence_id`, `instance`,"
. " `isexception`, `start`, `end`, `all_day`, `recurrence`, `title`, `description`,"
. " `location`, `categories`, `url`, `free_busy`, `priority`, `sensitivity`,"
. " `status`, `attendees`, `alarms`, `notifyat`)"
. " VALUES (?, $now, $now, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
$event['calendar'],
strval($event['uid']),
isset($event['recurrence_id']) ? intval($event['recurrence_id']) : 0,
isset($event['_instance']) ? strval($event['_instance']) : '',
isset($event['isexception']) ? intval($event['isexception']) : 0,
$event['start']->format(self::DB_DATE_FORMAT),
$event['end']->format(self::DB_DATE_FORMAT),
intval($event['all_day']),
$event['_recurrence'],
strval($event['title']),
isset($event['description']) ? strval($event['description']) : '',
isset($event['location']) ? strval($event['location']) : '',
isset($event['categories']) ? join(',', (array) $event['categories']) : '',
isset($event['url']) ? strval($event['url']) : '',
intval($event['free_busy']),
intval($event['priority']),
intval($event['sensitivity']),
isset($event['status']) ? strval($event['status']) : '',
$event['attendees'],
isset($event['alarms']) ? $event['alarms'] : null,
$event['notifyat']
);
$event_id = $this->rc->db->insert_id($this->db_events);
if ($event_id) {
$event['id'] = $event_id;
// add attachments
if (!empty($event['attachments'])) {
foreach ($event['attachments'] as $attachment) {
$this->add_attachment($attachment, $event_id);
unset($attachment);
}
}
return $event_id;
}
return false;
}
/**
* Update an event entry with the given data
*
* @param array Hash array with event properties
* @see calendar_driver::edit_event()
*/
public function edit_event($event)
{
if (!empty($this->calendars)) {
$update_master = false;
$update_recurring = true;
$old = $this->get_event($event);
$ret = true;
// check if update affects scheduling and update attendee status accordingly
$reschedule = $this->_check_scheduling($event, $old, true);
// increment sequence number
if (empty($event['sequence']) && $reschedule) {
$event['sequence'] = $old['sequence'] + 1;
}
// modify a recurring event, check submitted savemode to do the right things
if ($old['recurrence'] || $old['recurrence_id']) {
$master = $old['recurrence_id'] ? $this->get_event(array('id' => $old['recurrence_id'])) : $old;
// keep saved exceptions (not submitted by the client)
if (!empty($old['recurrence']['EXDATE'])) {
$event['recurrence']['EXDATE'] = $old['recurrence']['EXDATE'];
}
$savemode = isset($event['_savemode']) ? $event['_savemode'] : null;
switch ($savemode) {
case 'new':
$event['uid'] = $this->cal->generate_uid();
return $this->new_event($event);
case 'current':
// save as exception
$event['isexception'] = 1;
$update_recurring = false;
// set exception to first instance (= master)
if ($event['id'] == $master['id']) {
$event += $old;
$event['recurrence_id'] = $master['id'];
$event['_instance'] = libcalendaring::recurrence_instance_identifier($old, $master['allday']);
$event['isexception'] = 1;
$event_id = $this->_insert_event($event);
return $event_id;
}
break;
case 'future':
if ($master['id'] != $event['id']) {
// set until-date on master event, then save this instance as new recurring event
$master['recurrence']['UNTIL'] = clone $event['start'];
$master['recurrence']['UNTIL']->sub(new DateInterval('P1D'));
unset($master['recurrence']['COUNT']);
$update_master = true;
// if recurrence COUNT, update value to the correct number of future occurences
if ($event['recurrence']['COUNT']) {
$fromdate = clone $event['start'];
$fromdate->setTimezone($this->server_timezone);
$query = $this->rc->db->query(
"SELECT `event_id` FROM `{$this->db_events}`"
. " WHERE `calendar_id` IN ({$this->calendar_ids})"
. " AND `start` >= ? AND `recurrence_id` = ?",
$fromdate->format(self::DB_DATE_FORMAT),
$master['id']
);
if ($count = $this->rc->db->num_rows($query)) {
$event['recurrence']['COUNT'] = $count;
}
}
$update_recurring = true;
$event['recurrence_id'] = 0;
$event['isexception'] = 0;
$event['_instance'] = '';
break;
}
// else: 'future' == 'all' if modifying the master event
default: // 'all' is default
$event['id'] = $master['id'];
$event['recurrence_id'] = 0;
// 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 = $old['allday'] ? '' : $old['start']->format('H:i');
$old_duration = $old['end']->format('U') - $old['start']->format('U');
$new_start_date = $event['start']->format('Y-m-d');
$new_start_time = $event['allday'] ? '' : $event['start']->format('H:i');
$new_duration = $event['end']->format('U') - $event['start']->format('U');
$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($old['start']->diff($event['start']));
$event['end'] = clone $event['start'];
$event['end']->add(new DateInterval('PT'.$new_duration.'S'));
}
// 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'];
}
// adjust recurrence-id when start changed and therefore the entire recurrence chain changes
if (is_array($event['recurrence'])
&& ($old_start_date != $new_start_date || $old_start_time != $new_start_time)
&& ($exceptions = $this->_load_exceptions($old))
) {
$recurrence_id_format = libcalendaring::recurrence_id_format($event);
foreach ($exceptions as $exception) {
$recurrence_id = rcube_utils::anytodatetime($exception['_instance'], $old['start']->getTimezone());
if (is_a($recurrence_id, 'DateTime')) {
$recurrence_id->add($date_shift);
$exception['_instance'] = $recurrence_id->format($recurrence_id_format);
$this->_update_event($exception, false);
}
}
}
$ret = $event['id']; // return master ID
break;
}
}
$success = $this->_update_event($event, $update_recurring);
if ($success && $update_master) {
$this->_update_event($master, true);
}
return $success ? $ret : false;
}
return false;
}
/**
* 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 boolean 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' && $event['recurrence_id']) {
$update_event = $this->get_event(array('id' => $event['recurrence_id']));
$update_event['_savemode'] = $event['_savemode'];
calendar::merge_attendee_data($update_event, $attendees);
}
if ($ret = $this->update_attendees($update_event, $attendees)) {
// replace $event with effectively updated event (for iTip reply)
if ($ret !== true && $ret != $update_event['id'] && ($new_event = $this->get_event(array('id' => $ret)))) {
$event = $new_event;
}
else {
$event = $update_event;
}
}
return $ret;
}
/**
* Update the participant status for the given attendees
*
* @see calendar_driver::update_attendees()
*/
public function update_attendees(&$event, $attendees)
{
$success = $this->edit_event($event, true);
// apply attendee updates to recurrence exceptions too
if ($success && $event['_savemode'] == 'all'
&& !empty($event['recurrence'])
&& empty($event['recurrence_id'])
&& ($exceptions = $this->_load_exceptions($event))
) {
foreach ($exceptions as $exception) {
calendar::merge_attendee_data($exception, $attendees);
$this->_update_event($exception, false);
}
}
return $success;
}
/**
* Determine whether the current change affects scheduling and reset attendee status accordingly
*/
private function _check_scheduling(&$event, $old, $update = true)
{
// skip this check when importing iCal/iTip events
if (isset($event['sequence']) || !empty($event['_method'])) {
return false;
}
$reschedule = false;
// iterate through the list of properties considered 'significant' for scheduling
foreach (self::$scheduling_properties as $prop) {
$a = isset($old[$prop]) ? $old[$prop] : null;
$b = isset($event[$prop]) ? $event[$prop] : null;
if (!empty($event['allday']) && ($prop == 'start' || $prop == 'end')
- && $a instanceof DateTime && $b instanceof DateTime
+ && $a instanceof DateTimeInterface
+ && $b instanceof DateTimeInterface
) {
$a = $a->format('Y-m-d');
$b = $b->format('Y-m-d');
}
if ($prop == 'recurrence' && is_array($a) && is_array($b)) {
unset($a['EXCEPTIONS'], $b['EXCEPTIONS']);
$a = array_filter($a);
$b = array_filter($b);
// advanced rrule comparison: no rescheduling if series was shortened
if (!empty($a['COUNT']) && !empty($b['COUNT']) && $b['COUNT'] < $a['COUNT']) {
unset($a['COUNT'], $b['COUNT']);
}
else if (!empty($a['UNTIL']) && !empty($b['UNTIL']) && $b['UNTIL'] < $a['UNTIL']) {
unset($a['UNTIL'], $b['UNTIL']);
}
}
if ($a != $b) {
$reschedule = true;
break;
}
}
// reset all attendee status to needs-action (#4360)
if ($update && $reschedule && is_array($event['attendees'])) {
$is_organizer = false;
$emails = $this->cal->get_user_emails();
$attendees = $event['attendees'];
foreach ($attendees as $i => $attendee) {
if ($attendee['role'] == 'ORGANIZER' && $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 || ($event['organizer'] && in_array(strtolower($event['organizer']['email']), $emails))) {
$event['attendees'] = $attendees;
}
}
return $reschedule;
}
/**
* Convert save data to be used in SQL statements
*/
private function _save_preprocess($event)
{
// shift dates to server's timezone (except for all-day events)
if (!$event['allday']) {
$event['start'] = clone $event['start'];
$event['start']->setTimezone($this->server_timezone);
$event['end'] = clone $event['end'];
$event['end']->setTimezone($this->server_timezone);
}
// compose vcalendar-style recurrencue rule from structured data
$rrule = !empty($event['recurrence']) ? libcalendaring::to_rrule($event['recurrence']) : '';
$sensitivity = isset($event['sensitivity']) ? strtolower($event['sensitivity']) : '';
$free_busy = isset($event['free_busy']) ? strtolower($event['free_busy']) : '';
$event['_recurrence'] = rtrim($rrule, ';');
$event['free_busy'] = isset($this->free_busy_map[$free_busy]) ? $this->free_busy_map[$free_busy] : null;
$event['sensitivity'] = isset($this->sensitivity_map[$sensitivity]) ? $this->sensitivity_map[$sensitivity] : null;
$event['all_day'] = !empty($event['allday']) ? 1 : 0;
if ($event['free_busy'] == 'tentative') {
$event['status'] = 'TENTATIVE';
}
// compute absolute time to notify the user
$event['notifyat'] = $this->_get_notification($event);
if (!empty($event['valarms'])) {
$event['alarms'] = $this->serialize_alarms($event['valarms']);
}
// process event attendees
if (!empty($event['attendees'])) {
$event['attendees'] = json_encode((array)$event['attendees']);
}
else {
$event['attendees'] = '';
}
return $event;
}
/**
* Compute absolute time to notify the user
*/
private function _get_notification($event)
{
if (!empty($event['valarms']) && $event['start'] > new DateTime()) {
$alarm = libcalendaring::get_next_alarm($event);
if ($alarm['time'] && in_array($alarm['action'], $this->alarm_types)) {
return date('Y-m-d H:i:s', $alarm['time']);
}
}
}
/**
* Save the given event record to database
*
* @param array Event data
* @param boolean True if recurring events instances should be updated, too
*/
private function _update_event($event, $update_recurring = true)
{
$event = $this->_save_preprocess($event);
$sql_args = array();
$set_cols = array('start', 'end', 'all_day', 'recurrence_id', 'isexception', 'sequence',
'title', 'description', 'location', 'categories', 'url', 'free_busy', 'priority',
'sensitivity', 'status', 'attendees', 'alarms', 'notifyat'
);
foreach ($set_cols as $col) {
if (!empty($event[$col]) && is_a($event[$col], 'DateTime')) {
$sql_args[$col] = $event[$col]->format(self::DB_DATE_FORMAT);
}
else if (array_key_exists($col, $event)) {
$sql_args[$col] = is_array($event[$col]) ? join(',', $event[$col]) : $event[$col];
}
}
if (!empty($event['_recurrence'])) {
$sql_args['recurrence'] = $event['_recurrence'];
}
if (!empty($event['_instance'])) {
$sql_args['instance'] = $event['_instance'];
}
if (!empty($event['_fromcalendar']) && $event['_fromcalendar'] != $event['calendar']) {
$sql_args['calendar_id'] = $event['calendar'];
}
$sql_set = '';
foreach (array_keys($sql_args) as $col) {
$sql_set .= ", `$col` = ?";
}
$sql_args = array_values($sql_args);
$sql_args[] = $event['id'];
$query = $this->rc->db->query(
"UPDATE `{$this->db_events}`"
. " SET `changed` = " . $this->rc->db->now() . $sql_set
. " WHERE `event_id` = ? AND `calendar_id` IN ({$this->calendar_ids})",
$sql_args
);
$success = $this->rc->db->affected_rows($query);
// add attachments
if ($success && !empty($event['attachments'])) {
foreach ($event['attachments'] as $attachment) {
$this->add_attachment($attachment, $event['id']);
unset($attachment);
}
}
// remove attachments
if ($success && !empty($event['deleted_attachments']) && is_array($event['deleted_attachments'])) {
foreach ($event['deleted_attachments'] as $attachment) {
$this->remove_attachment($attachment, $event['id']);
}
}
if ($success) {
unset($this->cache[$event['id']]);
if ($update_recurring) {
$this->_update_recurring($event);
}
}
return $success;
}
/**
* Insert "fake" entries for recurring occurences of this event
*/
private function _update_recurring($event)
{
if (empty($this->calendars)) {
return;
}
if (!empty($event['recurrence'])) {
$exdata = array();
$exceptions = $this->_load_exceptions($event);
foreach ($exceptions as $exception) {
$exdate = substr($exception['_instance'], 0, 8);
$exdata[$exdate] = $exception;
}
}
// clear existing recurrence copies
$this->rc->db->query(
"DELETE FROM `{$this->db_events}`"
. " WHERE `recurrence_id` = ? AND `isexception` = 0 AND `calendar_id` IN ({$this->calendar_ids})",
$event['id']
);
// create new fake entries
if (!empty($event['recurrence'])) {
// include library class
require_once($this->cal->home . '/lib/calendar_recurrence.php');
$recurrence = new calendar_recurrence($this->cal, $event);
$count = 0;
$event['allday'] = $event['all_day'];
$duration = $event['start']->diff($event['end']);
$recurrence_id_format = libcalendaring::recurrence_id_format($event);
while ($next_start = $recurrence->next_start()) {
$instance = $next_start->format($recurrence_id_format);
$datestr = substr($instance, 0, 8);
// skip exceptions
// TODO: merge updated data from master event
if (!empty($exdata[$datestr])) {
continue;
}
$next_start->setTimezone($this->server_timezone);
$next_end = clone $next_start;
$next_end->add($duration);
$notify_at = $this->_get_notification(array(
'alarms' => !empty($event['alarms']) ? $event['alarms'] : null,
'start' => $next_start,
'end' => $next_end,
'status' => $event['status']
));
$now = $this->rc->db->now();
$query = $this->rc->db->query(
"INSERT INTO `{$this->db_events}`"
. " (`calendar_id`, `recurrence_id`, `created`, `changed`, `uid`, `instance`, `start`, `end`,"
. " `all_day`, `sequence`, `recurrence`, `title`, `description`, `location`, `categories`,"
. " `url`, `free_busy`, `priority`, `sensitivity`, `status`, `alarms`, `attendees`, `notifyat`)"
. " SELECT `calendar_id`, ?, $now, $now, `uid`, ?, ?, ?,"
. " `all_day`, `sequence`, `recurrence`, `title`, `description`, `location`, `categories`,"
. " `url`, `free_busy`, `priority`, `sensitivity`, `status`, `alarms`, `attendees`, ?"
. " FROM `{$this->db_events}` WHERE `event_id` = ? AND `calendar_id` IN ({$this->calendar_ids})",
$event['id'],
$instance,
$next_start->format(self::DB_DATE_FORMAT),
$next_end->format(self::DB_DATE_FORMAT),
$notify_at,
$event['id']
);
if (!$this->rc->db->affected_rows($query)) {
break;
}
// stop adding events for inifinite recurrence after 20 years
if (++$count > 999 || (empty($recurrence->recurEnd) && empty($recurrence->recurCount) && $next_start->format('Y') > date('Y') + 20)) {
break;
}
}
// remove all exceptions after recurrence end
if (!empty($next_end) && !empty($exceptions)) {
$this->rc->db->query(
"DELETE FROM `{$this->db_events}`"
. " WHERE `recurrence_id` = ? AND `isexception` = 1 AND `start` > ?"
. " AND `calendar_id` IN ({$this->calendar_ids})",
$event['id'],
$next_end->format(self::DB_DATE_FORMAT)
);
}
}
}
/**
*
*/
private function _load_exceptions($event, $instance_id = null)
{
$sql_add_where = '';
if (!empty($instance_id)) {
$sql_add_where = " AND `instance` = ?";
}
$result = $this->rc->db->query(
"SELECT * FROM `{$this->db_events}`"
. " WHERE `recurrence_id` = ? AND `isexception` = 1"
. " AND `calendar_id` IN ({$this->calendar_ids})" . $sql_add_where
. " ORDER BY `instance`, `start`",
$event['id'],
$instance_id
);
$exceptions = array();
while (($sql_arr = $this->rc->db->fetch_assoc($result)) && $sql_arr['event_id']) {
$exception = $this->_read_postprocess($sql_arr);
$instance = $exception['_instance'] ?: $exception['start']->format($exception['allday'] ? 'Ymd' : 'Ymd\THis');
$exceptions[$instance] = $exception;
}
return $exceptions;
}
/**
* Move a single event
*
* @param array Hash array with event properties
* @see calendar_driver::move_event()
*/
public function move_event($event)
{
// let edit_event() do all the magic
return $this->edit_event($event + (array)$this->get_event($event));
}
/**
* Resize a single event
*
* @param array Hash array with event properties
* @see calendar_driver::resize_event()
*/
public function resize_event($event)
{
// let edit_event() do all the magic
return $this->edit_event($event + (array)$this->get_event($event));
}
/**
* Remove a single event from the database
*
* @param array Hash array with event properties
* @param boolean Remove record irreversible (@TODO)
*
* @see calendar_driver::remove_event()
*/
public function remove_event($event, $force = true)
{
if (!empty($this->calendars)) {
$event += (array)$this->get_event($event);
$master = $event;
$update_master = false;
$savemode = 'all';
$ret = true;
// read master if deleting a recurring event
if ($event['recurrence'] || $event['recurrence_id']) {
$master = $event['recurrence_id'] ? $this->get_event(array('id' => $event['recurrence_id'])) : $event;
$savemode = $event['_savemode'];
}
switch ($savemode) {
case 'current':
// add exception to master event
$master['recurrence']['EXDATE'][] = $event['start'];
$update_master = true;
// just delete this single occurence
$query = $this->rc->db->query(
"DELETE FROM `{$this->db_events}`"
. " WHERE `calendar_id` IN ({$this->calendar_ids}) AND `event_id` = ?",
$event['id']
);
break;
case 'future':
if ($master['id'] != $event['id']) {
// set until-date on master event
$master['recurrence']['UNTIL'] = clone $event['start'];
$master['recurrence']['UNTIL']->sub(new DateInterval('P1D'));
unset($master['recurrence']['COUNT']);
$update_master = true;
// delete this and all future instances
$fromdate = clone $event['start'];
$fromdate->setTimezone($this->server_timezone);
$query = $this->rc->db->query(
"DELETE FROM `{$this->db_events}`"
. " WHERE `calendar_id` IN ({$this->calendar_ids}) AND `start` >= ? AND `recurrence_id` = ?",
$fromdate->format(self::DB_DATE_FORMAT),
$master['id']
);
$ret = $master['id'];
break;
}
// else: future == all if modifying the master event
default: // 'all' is default
$query = $this->rc->db->query(
"DELETE FROM `{$this->db_events}`"
. " WHERE (`event_id` = ? OR `recurrence_id` = ?) AND `calendar_id` IN ({$this->calendar_ids})",
$master['id'],
$master['id']
);
break;
}
$success = $this->rc->db->affected_rows($query);
if ($success && $update_master) {
$this->_update_event($master, true);
}
return $success ? $ret : false;
}
return false;
}
/**
* Return data of a specific event
*
* @param mixed Hash array with event properties or event UID
* @param integer Bitmask defining the scope to search events in
* @param boolean If true, recurrence exceptions shall be added
*
* @return array Hash array with event properties
*/
public function get_event($event, $scope = 0, $full = false)
{
$id = is_array($event) ? (!empty($event['id']) ? $event['id'] : $event['uid']) : $event;
$cal = is_array($event) && !empty($event['calendar']) ? $event['calendar'] : null;
$col = is_array($event) && is_numeric($id) ? 'event_id' : 'uid';
if (!empty($this->cache[$id])) {
return $this->cache[$id];
}
// get event from the address books birthday calendar
if ($cal == self::BIRTHDAY_CALENDAR_ID) {
return $this->get_birthday_event($id);
}
$where_add = '';
if (is_array($event) && empty($event['id']) && !empty($event['_instance'])) {
$where_add = " AND e.instance = " . $this->rc->db->quote($event['_instance']);
}
if ($scope & self::FILTER_ACTIVE) {
$calendars = [];
foreach ($this->calendars as $idx => $cal) {
if (!empty($cal['active'])) {
$calendars[] = $idx;
}
}
$cals = join(',', $calendars);
}
else {
$cals = $this->calendar_ids;
}
$result = $this->rc->db->query(
"SELECT e.*, (SELECT COUNT(`attachment_id`) FROM `{$this->db_attachments}`"
. " WHERE `event_id` = e.event_id OR `event_id` = e.recurrence_id) AS _attachments"
. " FROM `{$this->db_events}` AS e"
. " WHERE e.calendar_id IN ($cals) AND e.$col = ?" . $where_add,
$id
);
if ($result && ($sql_arr = $this->rc->db->fetch_assoc($result)) && $sql_arr['event_id']) {
$event = $this->_read_postprocess($sql_arr);
// also load recurrence exceptions
if (!empty($event['recurrence']) && $full) {
$event['recurrence']['EXCEPTIONS'] = array_values($this->_load_exceptions($event));
}
$this->cache[$id] = $event;
return $this->cache[$id];
}
return false;
}
/**
* Get event data
*
* @see calendar_driver::load_events()
*/
public function load_events($start, $end, $query = null, $calendars = null, $virtual = 1, $modifiedsince = null)
{
if (empty($calendars)) {
$calendars = array_keys($this->calendars);
}
else if (!is_array($calendars)) {
$calendars = explode(',', strval($calendars));
}
// only allow to select from calendars of this use
$calendar_ids = array_map(array($this->rc->db, 'quote'), array_intersect($calendars, array_keys($this->calendars)));
// compose (slow) SQL query for searching
// FIXME: improve searching using a dedicated col and normalized values
$sql_add = '';
if ($query) {
foreach (array('title','location','description','categories','attendees') as $col) {
$sql_query[] = $this->rc->db->ilike($col, '%'.$query.'%');
}
$sql_add .= " AND (" . join(' OR ', $sql_query) . ")";
}
if (!$virtual) {
$sql_add .= " AND e.recurrence_id = 0";
}
if ($modifiedsince) {
$sql_add .= " AND e.changed >= " . $this->rc->db->quote(date('Y-m-d H:i:s', $modifiedsince));
}
$events = array();
if (!empty($calendar_ids)) {
$result = $this->rc->db->query(
"SELECT e.*, (SELECT COUNT(`attachment_id`) FROM `{$this->db_attachments}`"
. " WHERE `event_id` = e.event_id OR `event_id` = e.recurrence_id) AS _attachments"
. " FROM `{$this->db_events}` e"
. " WHERE e.calendar_id IN (" . join(',', $calendar_ids) . ")"
. " AND e.start <= " . $this->rc->db->fromunixtime($end)
. " AND e.end >= " . $this->rc->db->fromunixtime($start)
. $sql_add
);
while ($result && ($sql_arr = $this->rc->db->fetch_assoc($result))) {
$event = $this->_read_postprocess($sql_arr);
$add = true;
if (!empty($event['recurrence']) && !$event['recurrence_id']) {
// load recurrence exceptions (i.e. for export)
if (!$virtual) {
$event['recurrence']['EXCEPTIONS'] = $this->_load_exceptions($event);
}
// check for exception on first instance
else {
$instance = libcalendaring::recurrence_instance_identifier($event);
$exceptions = $this->_load_exceptions($event, $instance);
if ($exceptions && is_array($exceptions[$instance])) {
$event = $exceptions[$instance];
$add = false;
}
}
}
if ($add) {
$events[] = $event;
}
}
}
// add events from the address books birthday calendar
if (in_array(self::BIRTHDAY_CALENDAR_ID, $calendars) && empty($query)) {
$events = array_merge($events, $this->load_birthday_events($start, $end, null, $modifiedsince));
}
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 integer Date range start (unix timestamp)
* @param integer Date range end (unix timestamp)
*
* @return array Hash array with counts grouped by calendar ID
*/
public function count_events($calendars, $start, $end = null)
{
// not implemented
return array();
}
/**
* Convert sql record into a rcube style event object
*/
private function _read_postprocess($event)
{
$free_busy_map = array_flip($this->free_busy_map);
$sensitivity_map = array_flip($this->sensitivity_map);
$event['id'] = $event['event_id'];
$event['start'] = new DateTime($event['start']);
$event['end'] = new DateTime($event['end']);
$event['allday'] = intval($event['all_day']);
$event['created'] = new DateTime($event['created']);
$event['changed'] = new DateTime($event['changed']);
$event['free_busy'] = $free_busy_map[$event['free_busy']];
$event['sensitivity'] = $sensitivity_map[$event['sensitivity']];
$event['calendar'] = $event['calendar_id'];
$event['recurrence_id'] = intval($event['recurrence_id']);
$event['isexception'] = intval($event['isexception']);
// parse recurrence rule
if ($event['recurrence'] && preg_match_all('/([A-Z]+)=([^;]+);?/', $event['recurrence'], $m, PREG_SET_ORDER)) {
$event['recurrence'] = array();
foreach ($m as $rr) {
if (is_numeric($rr[2])) {
$rr[2] = intval($rr[2]);
}
else if ($rr[1] == 'UNTIL') {
$rr[2] = date_create($rr[2]);
}
else if ($rr[1] == 'RDATE') {
$rr[2] = array_map('date_create', explode(',', $rr[2]));
}
else if ($rr[1] == 'EXDATE') {
$rr[2] = array_map('date_create', explode(',', $rr[2]));
}
$event['recurrence'][$rr[1]] = $rr[2];
}
}
if ($event['recurrence_id']) {
libcalendaring::identify_recurrence_instance($event);
}
if (strlen($event['instance'])) {
$event['_instance'] = $event['instance'];
if (empty($event['recurrence_id'])) {
$event['recurrence_date'] = rcube_utils::anytodatetime($event['_instance'], $event['start']->getTimezone());
}
}
if (!empty($event['_attachments'])) {
$event['attachments'] = (array)$this->list_attachments($event);
}
// decode serialized event attendees
if (strlen($event['attendees'])) {
$event['attendees'] = $this->unserialize_attendees($event['attendees']);
}
else {
$event['attendees'] = array();
}
// decode serialized alarms
if ($event['alarms']) {
$event['valarms'] = $this->unserialize_alarms($event['alarms']);
}
unset($event['event_id'], $event['calendar_id'], $event['notifyat'], $event['all_day'], $event['instance'], $event['_attachments']);
return $event;
}
/**
* Get a list of pending alarms to be displayed to the user
*
* @see calendar_driver::pending_alarms()
*/
public function pending_alarms($time, $calendars = null)
{
if (empty($calendars)) {
$calendars = array_keys($this->calendars);
}
else if (!is_array($calendars)) {
$calendars = explode(',', (array) $calendars);
}
// only allow to select from calendars with activated alarms
$calendar_ids = array();
foreach ($calendars as $cid) {
if ($this->calendars[$cid] && $this->calendars[$cid]['showalarms']) {
$calendar_ids[] = $cid;
}
}
$calendar_ids = array_map(array($this->rc->db, 'quote'), $calendar_ids);
$alarms = array();
if (!empty($calendar_ids)) {
$stime = $this->rc->db->fromunixtime($time);
$result = $this->rc->db->query(
"SELECT * FROM `{$this->db_events}`"
. " WHERE `calendar_id` IN (" . join(',', $calendar_ids) . ")"
. " AND `notifyat` <= $stime AND `end` > $stime"
);
while ($event = $this->rc->db->fetch_assoc($result)) {
$alarms[] = $this->_read_postprocess($event);
}
}
return $alarms;
}
/**
* Feedback after showing/sending an alarm notification
*
* @see calendar_driver::dismiss_alarm()
*/
public function dismiss_alarm($event_id, $snooze = 0)
{
// set new notifyat time or unset if not snoozed
$notify_at = $snooze > 0 ? date(self::DB_DATE_FORMAT, time() + $snooze) : null;
$query = $this->rc->db->query(
"UPDATE `{$this->db_events}`"
. " SET `changed` = " . $this->rc->db->now() . ", `notifyat` = ?"
. " WHERE `event_id` = ? AND `calendar_id` IN ({$this->calendar_ids})",
$notify_at,
$event_id
);
return $this->rc->db->affected_rows($query);
}
/**
* Save an attachment related to the given event
*/
private function add_attachment($attachment, $event_id)
{
if (isset($attachment['data'])) {
$data = $attachment['data'];
}
else if (!empty($attachment['path'])) {
$data = file_get_contents($attachment['path']);
}
else {
return false;
}
$query = $this->rc->db->query(
"INSERT INTO `{$this->db_attachments}`"
. " (`event_id`, `filename`, `mimetype`, `size`, `data`)"
. " VALUES (?, ?, ?, ?, ?)",
$event_id,
$attachment['name'],
$attachment['mimetype'],
strlen($data),
base64_encode($data)
);
return $this->rc->db->affected_rows($query);
}
/**
* Remove a specific attachment from the given event
*/
private function remove_attachment($attachment_id, $event_id)
{
$query = $this->rc->db->query(
"DELETE FROM `{$this->db_attachments}`"
. " WHERE `attachment_id` = ? AND `event_id` IN ("
. "SELECT `event_id` FROM `{$this->db_events}`"
. " WHERE `event_id` = ? AND `calendar_id` IN ({$this->calendar_ids}))",
$attachment_id,
$event_id
);
return $this->rc->db->affected_rows($query);
}
/**
* List attachments of specified event
*/
public function list_attachments($event)
{
$attachments = array();
if (!empty($this->calendar_ids)) {
$result = $this->rc->db->query(
"SELECT `attachment_id` AS id, `filename` AS name, `mimetype`, `size`"
. " FROM `{$this->db_attachments}`"
. " WHERE `event_id` IN ("
. "SELECT `event_id` FROM `{$this->db_events}`"
. " WHERE `event_id` = ? AND `calendar_id` IN ({$this->calendar_ids}))"
. " ORDER BY `filename`",
$event['recurrence_id'] ? $event['recurrence_id'] : $event['event_id']
);
while ($arr = $this->rc->db->fetch_assoc($result)) {
$attachments[] = $arr;
}
}
return $attachments;
}
/**
* Get attachment properties
*/
public function get_attachment($id, $event)
{
if (!empty($this->calendar_ids)) {
$result = $this->rc->db->query(
"SELECT `attachment_id` AS id, `filename` AS name, `mimetype`, `size` "
. " FROM `{$this->db_attachments}`"
. " WHERE `attachment_id` = ? AND `event_id` IN ("
. "SELECT `event_id` FROM `{$this->db_events}`"
. " WHERE `event_id` = ? AND `calendar_id` IN ({$this->calendar_ids}))",
$id,
!empty($event['recurrence_id']) ? $event['recurrence_id'] : $event['id']
);
if ($result && ($arr = $this->rc->db->fetch_assoc($result))) {
return $arr;
}
}
}
/**
* Get attachment body
*/
public function get_attachment_body($id, $event)
{
if (!empty($this->calendar_ids)) {
$result = $this->rc->db->query(
"SELECT `data` FROM `{$this->db_attachments}`"
. " WHERE `attachment_id` = ? AND `event_id` IN ("
. "SELECT `event_id` FROM `{$this->db_events}`"
. " WHERE `event_id` = ? AND `calendar_id` IN ({$this->calendar_ids}))",
$id,
$event['id']
);
if ($arr = $this->rc->db->fetch_assoc($result)) {
return base64_decode($arr['data']);
}
}
}
/**
* Remove the given category
*/
public function remove_category($name)
{
$query = $this->rc->db->query(
"UPDATE `{$this->db_events}` SET `categories` = ''"
. " WHERE `categories` = ? AND `calendar_id` IN ({$this->calendar_ids})",
$name
);
return $this->rc->db->affected_rows($query);
}
/**
* Update/replace a category
*/
public function replace_category($oldname, $name, $color)
{
$query = $this->rc->db->query(
"UPDATE `{$this->db_events}` SET `categories` = ?"
. " WHERE `categories` = ? AND `calendar_id` IN ({$this->calendar_ids})",
$name,
$oldname
);
return $this->rc->db->affected_rows($query);
}
/**
* Helper method to serialize the list of alarms into a string
*/
private function serialize_alarms($valarms)
{
foreach ((array)$valarms as $i => $alarm) {
- if ($alarm['trigger'] instanceof DateTime) {
+ if ($alarm['trigger'] instanceof DateTimeInterface) {
$valarms[$i]['trigger'] = '@' . $alarm['trigger']->format('c');
}
}
return $valarms ? json_encode($valarms) : null;
}
/**
* Helper method to decode a serialized list of alarms
*/
private function unserialize_alarms($alarms)
{
// decode json serialized alarms
if ($alarms && $alarms[0] == '[') {
$valarms = json_decode($alarms, true);
foreach ($valarms as $i => $alarm) {
if ($alarm['trigger'][0] == '@') {
try {
$valarms[$i]['trigger'] = new DateTime(substr($alarm['trigger'], 1));
}
catch (Exception $e) {
unset($valarms[$i]);
}
}
}
}
// convert legacy alarms data
else if (strlen($alarms)) {
list($trigger, $action) = explode(':', $alarms, 2);
if ($trigger = libcalendaring::parse_alarm_value($trigger)) {
$valarms = array(array('action' => $action, 'trigger' => $trigger[3] ?: $trigger[0]));
}
}
return $valarms;
}
/**
* Helper method to decode the attendees list from string
*/
private function unserialize_attendees($s_attendees)
{
$attendees = array();
// decode json serialized string
if ($s_attendees[0] == '[') {
$attendees = json_decode($s_attendees, true);
}
// decode the old serialization format
else {
foreach (explode("\n", $s_attendees) as $line) {
$att = array();
foreach (rcube_utils::explode_quoted_string(';', $line) as $prop) {
list($key, $value) = explode("=", $prop);
$att[strtolower($key)] = stripslashes(trim($value, '""'));
}
$attendees[] = $att;
}
}
return $attendees;
}
}
diff --git a/plugins/calendar/drivers/kolab/kolab_driver.php b/plugins/calendar/drivers/kolab/kolab_driver.php
index 42ef7cf6..b4cee8cc 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')) {
$recurrence_id = $exception['recurrence_date'];
}
else {
$recurrence_id = rcube_utils::anytodatetime($exception['_instance'], $old['start']->getTimezone());
}
- if ($recurrence_id instanceof DateTime) {
+ 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')) {
$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 DateTime && $overlay['recurrence_date'] instanceof DateTime) {
+ 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 DateTime) {
+ 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'])) {
$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/libcalendaring/README b/plugins/libcalendaring/README
index 11c10f02..55d40c33 100644
--- a/plugins/libcalendaring/README
+++ b/plugins/libcalendaring/README
@@ -1,16 +1,16 @@
Library providing common functions for calendar-based plugins
-------------------------------------------------------------
Provides utility functions for calendar-related modules such as
* alarms display and dismissal
* attachment handling
* iCal parsing and exporting
* iTip invitations handling
iCal parsing and exporting is done with the help of the Sabre VObject
library [1]. It needs to be insalled with Roundcube using composer:
- $ composer require "sabre/vobject" "~3.3.3"
+ $ composer require "sabre/vobject" "~4.5.1"
[1]: http://sabre.io/vobject/
diff --git a/plugins/libcalendaring/composer.json b/plugins/libcalendaring/composer.json
index 498c7689..b70587af 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": ">=5.4.0",
+ "php": ">=7.4.0",
"roundcube/plugin-installer": ">=0.1.3",
- "sabre/vobject": "~3.5.3"
+ "sabre/vobject": "~4.5.1"
}
}
diff --git a/plugins/libcalendaring/lib/libcalendaring_datetime.php b/plugins/libcalendaring/lib/libcalendaring_datetime.php
new file mode 100644
index 00000000..95bdb94e
--- /dev/null
+++ b/plugins/libcalendaring/lib/libcalendaring_datetime.php
@@ -0,0 +1,29 @@
+<?php
+
+/**
+ * DateTime wrapper. Main reason for its existence is that
+ * you can't set undefined properties on DateTime without
+ * a deprecation warning on PHP >= 8.1
+ *
+ * @author Aleksander Machniak <machniak@apheleia-it.ch>
+ *
+ * Copyright (C) 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 libcalendaring_datetime extends DateTime
+{
+ public $_dateonly = false;
+}
diff --git a/plugins/libcalendaring/lib/libcalendaring_itip.php b/plugins/libcalendaring/lib/libcalendaring_itip.php
index c59f3740..27ac89d8 100644
--- a/plugins/libcalendaring/lib/libcalendaring_itip.php
+++ b/plugins/libcalendaring/lib/libcalendaring_itip.php
@@ -1,1040 +1,1040 @@
<?php
/**
* iTIP functions for the calendar-based Roudncube plugins
*
* Class providing functionality to manage iTIP invitations
*
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2011-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_itip
{
protected $rc;
protected $lib;
protected $plugin;
protected $sender;
protected $domain;
protected $itip_send = false;
protected $rsvp_actions = array('accepted','tentative','declined','delegated');
protected $rsvp_status = array('accepted','tentative','declined','delegated');
function __construct($plugin, $domain = 'libcalendaring')
{
$this->plugin = $plugin;
$this->rc = rcube::get_instance();
$this->lib = libcalendaring::get_instance();
$this->domain = $domain;
$hook = $this->rc->plugins->exec_hook('calendar_load_itip',
array('identity' => $this->rc->user->list_emails(true)));
$this->sender = $hook['identity'];
$this->plugin->add_hook('smtp_connect', array($this, 'smtp_connect_hook'));
}
public function set_sender_email($email)
{
if (!empty($email))
$this->sender['email'] = $email;
}
public function set_rsvp_actions($actions)
{
$this->rsvp_actions = (array)$actions;
$this->rsvp_status = array_merge($this->rsvp_actions, array('delegated'));
}
public function set_rsvp_status($status)
{
$this->rsvp_status = $status;
}
/**
* Wrapper for rcube_plugin::gettext()
* Checking for a label in different domains
*
* @see rcube::gettext()
*/
public function gettext($p)
{
$label = is_array($p) ? $p['name'] : $p;
$domain = $this->domain;
if (!$this->rc->text_exists($label, $domain)) {
$domain = 'libcalendaring';
}
return $this->rc->gettext($p, $domain);
}
/**
* Send an iTip mail message
*
* @param array Event object to send
* @param string iTip method (REQUEST|REPLY|CANCEL)
* @param array Hash array with recipient data (name, email)
* @param string Mail subject
* @param string Mail body text label
* @param object Mail_mime object with message data
* @param boolean Request RSVP
* @return boolean True on success, false on failure
*/
public function send_itip_message($event, $method, $recipient, $subject, $bodytext, $message = null, $rsvp = true)
{
if (!$this->sender['name']) {
$this->sender['name'] = $this->sender['email'];
}
if (!$message) {
libcalendaring::identify_recurrence_instance($event);
$message = $this->compose_itip_message($event, $method, $rsvp);
}
$mailto = rcube_utils::idn_to_ascii($recipient['email']);
$headers = $message->headers();
$headers['To'] = format_email_recipient($mailto, $recipient['name']);
$headers['Subject'] = $this->gettext(array(
'name' => $subject,
'vars' => array(
'title' => $event['title'],
'name' => $this->sender['name'],
)
));
// compose a list of all event attendees
$attendees_list = array();
foreach ((array)$event['attendees'] as $attendee) {
$attendees_list[] = (!empty($attendee['name']) && !empty($attendee['email'])) ?
$attendee['name'] . ' <' . $attendee['email'] . '>' :
(!empty($attendee['name']) ? $attendee['name'] : $attendee['email']);
}
$recurrence_info = '';
if (!empty($event['recurrence_id'])) {
$msg = $this->gettext(!empty($event['thisandfuture']) ? 'itipmessagefutureoccurrence' : 'itipmessagesingleoccurrence');
$recurrence_info = "\n\n** $msg **";
}
else if (!empty($event['recurrence'])) {
$recurrence_info = sprintf("\n%s: %s", $this->gettext('recurring'), $this->lib->recurrence_text($event['recurrence']));
}
$mailbody = $this->gettext(array(
'name' => $bodytext,
'vars' => array(
'title' => $event['title'],
'date' => $this->lib->event_date_text($event) . $recurrence_info,
'attendees' => join(",\n ", $attendees_list),
'sender' => $this->sender['name'],
'organizer' => $this->sender['name'],
'description' => isset($event['description']) ? $event['description'] : '',
)
));
// remove redundant empty lines (e.g. when an event description is empty)
$mailbody = preg_replace('/\n{3,}/', "\n\n", $mailbody);
// if (!empty($event['comment'])) {
// $mailbody .= "\n\n" . $this->gettext('itipsendercomment') . $event['comment'];
// }
// append links for direct invitation replies
if ($method == 'REQUEST' && $rsvp
&& $this->rc->config->get('calendar_itip_smtp_server')
&& ($token = $this->store_invitation($event, $recipient['email']))
) {
$mailbody .= "\n\n" . $this->gettext(array(
'name' => 'invitationattendlinks',
'vars' => array('url' => $this->plugin->get_url(array('action' => 'attend', 't' => $token))),
));
}
else if ($method == 'CANCEL' && $event['cancelled']) {
$this->cancel_itip_invitation($event);
}
$message->headers($headers, true);
$message->setTXTBody(rcube_mime::format_flowed($mailbody, 79));
if ($this->rc->config->get('libcalendaring_itip_debug', false)) {
rcube::console('iTip ' . $method, $message->txtHeaders() . "\r\n" . $message->get());
}
// finally send the message
$this->itip_send = true;
$sent = $this->rc->deliver_message($message, $headers['X-Sender'], $mailto, $smtp_error);
$this->itip_send = false;
return $sent;
}
/**
* Plugin hook to alter SMTP authentication.
* This is used if iTip messages are to be sent from an unauthenticated session
*/
public function smtp_connect_hook($p)
{
// replace smtp auth settings if we're not in an authenticated session
if ($this->itip_send && !$this->rc->user->ID) {
foreach (array('smtp_server', 'smtp_user', 'smtp_pass') as $prop) {
$p[$prop] = $this->rc->config->get("calendar_itip_$prop", $p[$prop]);
}
}
return $p;
}
/**
* Helper function to build a Mail_mime object to send an iTip message
*
* @param array Event object to send
* @param string iTip method (REQUEST|REPLY|CANCEL)
* @param boolean Request RSVP
* @return object Mail_mime object with message data
*/
public function compose_itip_message($event, $method, $rsvp = true)
{
$from = rcube_utils::idn_to_ascii($this->sender['email']);
$from_utf = rcube_utils::idn_to_utf8($from);
$sender = format_email_recipient($from, $this->sender['name']);
// truncate list attendees down to the recipient of the iTip Reply.
// constraints for a METHOD:REPLY according to RFC 5546
if ($method == 'REPLY') {
$replying_attendee = null;
$reply_attendees = array();
foreach ($event['attendees'] as $attendee) {
if ($attendee['role'] == 'ORGANIZER') {
$reply_attendees[] = $attendee;
}
// we accept on behalf of a resource
else if (strcasecmp($attendee['email'], $event['_resource']) == 0) {
$replying_attendee = $attendee;
$replying_attendee['sent-by'] = 'mailto:' . $from_utf;
}
else if (strcasecmp($attendee['email'], $from) == 0 || strcasecmp($attendee['email'], $from_utf) == 0) {
$replying_attendee = $attendee;
if ($attendee['status'] != 'DELEGATED') {
unset($replying_attendee['rsvp']); // unset the RSVP attribute
}
}
// include attendees relevant for delegation (RFC 5546, Section 4.2.5)
else if ((!empty($attendee['delegated-to']) &&
(strcasecmp($attendee['delegated-to'], $from) == 0 || strcasecmp($attendee['delegated-to'], $from_utf) == 0)) ||
(!empty($attendee['delegated-from']) &&
(strcasecmp($attendee['delegated-from'], $from) == 0 || strcasecmp($attendee['delegated-from'], $from_utf) == 0))) {
$reply_attendees[] = $attendee;
}
}
if ($replying_attendee) {
array_unshift($reply_attendees, $replying_attendee);
$event['attendees'] = $reply_attendees;
}
if ($event['recurrence']) {
unset($event['recurrence']['EXCEPTIONS']);
}
}
// set RSVP for every attendee
else if ($method == 'REQUEST') {
foreach ($event['attendees'] as $i => $attendee) {
if (
($rsvp || !isset($attendee['rsvp']))
&& (
(empty($attendee['status']) || $attendee['status'] != 'DELEGATED')
&& $attendee['role'] != 'NON-PARTICIPANT'
)
) {
$event['attendees'][$i]['rsvp']= (bool) $rsvp;
}
}
}
else if ($method == 'CANCEL') {
if ($event['recurrence']) {
unset($event['recurrence']['EXCEPTIONS']);
}
}
// Set SENT-BY property if the sender is not the organizer
if ($method == 'CANCEL' || $method == 'REQUEST') {
foreach ((array)$event['attendees'] as $idx => $attendee) {
if ($attendee['role'] == 'ORGANIZER'
&& $attendee['email']
&& strcasecmp($attendee['email'], $from) != 0
&& strcasecmp($attendee['email'], $from_utf) != 0
) {
$attendee['sent-by'] = 'mailto:' . $from_utf;
$event['organizer'] = $event['attendees'][$idx] = $attendee;
break;
}
}
}
// compose multipart message using PEAR:Mail_Mime
$message = new Mail_mime("\r\n");
$message->setParam('text_encoding', 'quoted-printable');
$message->setParam('head_encoding', 'quoted-printable');
$message->setParam('head_charset', RCUBE_CHARSET);
$message->setParam('text_charset', RCUBE_CHARSET . ";\r\n format=flowed");
$message->setContentType('multipart/alternative');
// compose common headers array
$headers = array(
'From' => $sender,
'Date' => $this->rc->user_date(),
'Message-ID' => $this->rc->gen_message_id(),
'X-Sender' => $from,
);
if ($agent = $this->rc->config->get('useragent')) {
$headers['User-Agent'] = $agent;
}
$message->headers($headers);
// attach ics file for this event
$ical = libcalendaring::get_ical();
$ics = $ical->export(array($event), $method, false, $method == 'REQUEST' && $this->plugin->driver ? array($this->plugin->driver, 'get_attachment_body') : false);
$filename = !empty($event['_type']) && $event['_type'] == 'task' ? 'todo.ics' : 'event.ics';
$message->addAttachment($ics, 'text/calendar', $filename, false, '8bit', '', RCUBE_CHARSET . "; method=" . $method);
return $message;
}
/**
* Forward the given iTip event as delegation to another person
*
* @param array Event object to delegate
* @param mixed Delegatee as string or hash array with keys 'name' and 'mailto'
* @param boolean The delegator's RSVP flag
* @param array List with indexes of new/updated attendees
* @return boolean True on success, False on failure
*/
public function delegate_to(&$event, $delegate, $rsvp = false, &$attendees = array())
{
if (is_string($delegate)) {
$delegates = rcube_mime::decode_address_list($delegate, 1, false);
if (count($delegates) > 0) {
$delegate = reset($delegates);
}
}
$emails = $this->lib->get_user_emails();
$me = $this->rc->user->list_emails(true);
// find/create the delegate attendee
$delegate_attendee = array(
'email' => $delegate['mailto'],
'name' => $delegate['name'],
'role' => 'REQ-PARTICIPANT',
);
$delegate_index = count($event['attendees']);
foreach ($event['attendees'] as $i => $attendee) {
// set myself the DELEGATED-TO parameter
if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) {
$event['attendees'][$i]['delegated-to'] = $delegate['mailto'];
$event['attendees'][$i]['status'] = 'DELEGATED';
$event['attendees'][$i]['role'] = 'NON-PARTICIPANT';
$event['attendees'][$i]['rsvp'] = $rsvp;
$me['email'] = $attendee['email'];
$delegate_attendee['role'] = $attendee['role'];
}
// the disired delegatee is already listed as an attendee
else if (stripos($delegate['mailto'], $attendee['email']) !== false && $attendee['role'] != 'ORGANIZER') {
$delegate_attendee = $attendee;
$delegate_index = $i;
break;
}
// TODO: remove previous delegatee (i.e. attendee that has DELEGATED-FROM == $me)
}
// set/add delegate attendee with RSVP=TRUE and DELEGATED-FROM parameter
$delegate_attendee['rsvp'] = true;
$delegate_attendee['status'] = 'NEEDS-ACTION';
$delegate_attendee['delegated-from'] = $me['email'];
$event['attendees'][$delegate_index] = $delegate_attendee;
$attendees[] = $delegate_index;
$this->set_sender_email($me['email']);
return $this->send_itip_message($event, 'REQUEST', $delegate_attendee, 'itipsubjectdelegatedto', 'itipmailbodydelegatedto');
}
/**
* Handler for calendar/itip-status requests
*/
public function get_itip_status($event, $existing = null)
{
$action = $event['rsvp'] ? 'rsvp' : '';
$status = $event['fallback'];
$latest = $rescheduled = false;
$html = '';
if (is_numeric($event['changed'])) {
$event['changed'] = new DateTime('@'.$event['changed']);
}
// check if the given itip object matches the last state
if ($existing) {
$latest = (isset($event['sequence']) && intval($existing['sequence']) == intval($event['sequence'])) ||
(!isset($event['sequence']) && $existing['changed'] && $existing['changed'] >= $event['changed']);
}
// determine action for REQUEST
if ($event['method'] == 'REQUEST') {
$html = html::div('rsvp-status', $this->gettext('acceptinvitation'));
if ($existing) {
$rsvp = $event['rsvp'];
$emails = $this->lib->get_user_emails();
foreach ($existing['attendees'] as $attendee) {
if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) {
$status = strtoupper($attendee['status']);
break;
}
}
}
else {
$rsvp = $event['rsvp'] && $this->rc->config->get('calendar_allow_itip_uninvited', true);
}
$status_lc = strtolower($status);
if ($status_lc == 'unknown' && !$this->rc->config->get('calendar_allow_itip_uninvited', true)) {
$html = html::div('rsvp-status', $this->gettext('notanattendee'));
$action = 'import';
}
else if (in_array($status_lc, $this->rsvp_status)) {
$status_text = $this->gettext(($latest ? 'youhave' : 'youhavepreviously') . $status_lc);
if ($existing && ($existing['sequence'] > $event['sequence']
|| (!isset($event['sequence']) && $existing['changed'] && $existing['changed'] > $event['changed']))
) {
$action = ''; // nothing to do here, outdated invitation
if ($status_lc == 'needs-action') {
$status_text = $this->gettext('outdatedinvitation');
}
}
else if (!$existing && !$rsvp) {
$action = 'import';
}
else {
if ($latest) {
$diff = $this->get_itip_diff($event, $existing);
// Detect re-scheduling
// FIXME: This is probably to simplistic, or maybe we should just check
// attendee's RSVP flag in the new event?
$rescheduled = !empty($diff['start']) || !empty($diff['end']);
unset($diff['start'], $diff['end']);
}
if ($rescheduled) {
$action = 'rsvp';
$latest = false;
}
else if ($status_lc != 'needs-action') {
// check if there are any changes
if ($latest) {
$latest = empty($diff);
}
$action = !$latest ? 'update' : '';
}
}
$html = html::div('rsvp-status ' . $status_lc, $status_text);
}
}
// determine action for REPLY
else if ($event['method'] == 'REPLY') {
// check whether the sender already is an attendee
if ($existing) {
// Relax checking if that is a reply to the latest version of the event
// We accept versions with older SEQUENCE but no significant changes (Bifrost#T78144)
if (!$latest) {
$num = $got = 0;
foreach (array('start', 'end', 'due', 'allday', 'recurrence', 'location') as $key) {
if (isset($existing[$key])) {
if ($key == 'allday') {
$event[$key] = $event[$key] == 'true';
}
- $value = $existing[$key] instanceof DateTime ? $existing[$key]->format('c') : $existing[$key];
+ $value = $existing[$key] instanceof DateTimeInterface ? $existing[$key]->format('c') : $existing[$key];
$num++;
$got += intval($value == $event[$key]);
}
}
$latest = $num === $got;
}
$action = $this->rc->config->get('calendar_allow_itip_uninvited', true) ? 'accept' : '';
$listed = false;
foreach ($existing['attendees'] as $attendee) {
if ($attendee['role'] != 'ORGANIZER' && strcasecmp($attendee['email'], $event['attendee']) == 0) {
$status_lc = strtolower($status);
if (in_array($status_lc, $this->rsvp_status)) {
$html = html::div('rsvp-status ' . $status_lc, $this->gettext(array(
'name' => 'attendee' . $status_lc,
'vars' => array(
'delegatedto' => rcube::Q($event['delegated-to'] ?: ($attendee['delegated-to'] ?: '?')),
)
)));
}
$action = $attendee['status'] == $status || !$latest ? '' : 'update';
$listed = true;
break;
}
}
if (!$listed) {
$html = html::div('rsvp-status', $this->gettext('itipnewattendee'));
}
}
else {
$html = html::div('rsvp-status hint', $this->gettext('itipobjectnotfound'));
$action = '';
}
}
else if ($event['method'] == 'CANCEL') {
if (!$existing) {
$html = html::div('rsvp-status hint', $this->gettext('itipobjectnotfound'));
$action = '';
}
}
return array(
'uid' => $event['uid'],
'id' => asciiwords($event['uid'], true),
'existing' => $existing ? true : false,
'saved' => $existing ? true : false,
'latest' => $latest,
'status' => $status,
'action' => $action,
'rescheduled' => $rescheduled,
'html' => $html,
);
}
protected function get_itip_diff($event, $existing)
{
if (empty($event) || empty($existing) || empty($event['message_uid']) || empty($event['mime_id'])) {
return;
}
$itip = $this->lib->mail_get_itip_object($event['mbox'], $event['message_uid'], $event['mime_id'],
$event['task'] == 'calendar' ? 'event' : 'task');
if ($itip) {
// List of properties that could change without SEQUENCE bump
$attrs = array('description', 'title', 'location', 'url');
$diff = array();
foreach ($attrs as $attr) {
if (isset($itip[$attr]) && $itip[$attr] != $existing[$attr]) {
$diff[$attr] = array(
'new' => $itip[$attr],
'old' => $existing[$attr]
);
}
}
$status = array();
$itip_attendees = array();
$existing_attendees = array();
$emails = $this->lib->get_user_emails();
// Compare list of attendees (ignoring current user status)
foreach ((array) $existing['attendees'] as $idx => $attendee) {
if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) {
$status[strtolower($attendee['email'])] = $attendee['status'];
}
if ($attendee['role'] == 'ORGANIZER') {
$attendee['status'] = 'ACCEPTED'; // sometimes is not set for exceptions
$existing['attendees'][$idx] = $attendee;
}
$existing_attendees[] = $attendee['email'] . (isset($attendee['name']) ? $attendee['name'] : '');
}
foreach ((array) $itip['attendees'] as $idx => $attendee) {
if (!empty($attendee['email']) && !empty($status[strtolower($attendee['email'])])) {
$attendee['status'] = $status[strtolower($attendee['email'])];
$itip['attendees'][$idx] = $attendee;
}
$itip_attendees[] = $attendee['email'] . (isset($attendee['name']) ? $attendee['name'] : '');
}
if ($itip_attendees != $existing_attendees) {
$diff['attendees'] = array(
'new' => $itip['attendees'],
'old' => $existing['attendees']
);
}
if ($existing['start'] != $itip['start']) {
$diff['start'] = array(
'new' => $itip['start'],
'old' => $existing['start'],
);
}
if ($existing['end'] != $itip['end']) {
$diff['end'] = array(
'new' => $itip['end'],
'old' => $existing['end'],
);
}
return $diff;
}
}
/**
* Build inline UI elements for iTip messages
*/
public function mail_itip_inline_ui($event, $method, $mime_id, $task, $message_date = null, $preview_url = null)
{
$buttons = array();
$dom_id = asciiwords($event['uid'], true);
$rsvp_status = 'unknown';
$rsvp_buttons = '';
// pass some metadata about the event and trigger the asynchronous status check
$changed = is_object($event['changed']) ? $event['changed'] : $message_date;
$metadata = array(
'uid' => $event['uid'],
'_instance' => isset($event['_instance']) ? $event['_instance'] : null,
'changed' => $changed ? $changed->format('U') : 0,
'sequence' => intval($event['sequence']),
'method' => $method,
'task' => $task,
'mime_id' => $mime_id,
);
// create buttons to be activated from async request checking existence of this event in local calendars
$buttons[] = html::div(array('id' => 'loading-'.$dom_id, 'class' => 'rsvp-status loading'), $this->gettext('loading'));
// on iTip REPLY we have two options:
if ($method == 'REPLY') {
$title = $this->gettext('itipreply');
$attendee = self::find_reply_attendee($event);
if ($attendee) {
$metadata['attendee'] = $attendee['email'];
$rsvp_status = strtoupper($attendee['status']);
if ($attendee['delegated-to']) {
$metadata['delegated-to'] = $attendee['delegated-to'];
}
}
// 1. update the attendee status on our copy
$update_button = html::tag('input', array(
'type' => 'button',
'class' => 'button',
'onclick' => "rcube_libcalendaring.add_from_itip_mail('" . rcube::JQ($mime_id) . "', '$task')",
'value' => $this->gettext('updateattendeestatus'),
));
// 2. accept or decline a new or delegate attendee
$accept_buttons = html::tag('input', array(
'type' => 'button',
'class' => "button accept",
'onclick' => "rcube_libcalendaring.add_from_itip_mail('" . rcube::JQ($mime_id) . "', '$task')",
'value' => $this->gettext('acceptattendee'),
));
$accept_buttons .= html::tag('input', array(
'type' => 'button',
'class' => "button decline",
'onclick' => "rcube_libcalendaring.decline_attendee_reply('" . rcube::JQ($mime_id) . "', '$task')",
'value' => $this->gettext('declineattendee'),
));
$buttons[] = html::div(array('id' => 'update-'.$dom_id, 'style' => 'display:none'), $update_button);
$buttons[] = html::div(array('id' => 'accept-'.$dom_id, 'style' => 'display:none'), $accept_buttons);
// For replies we need more metadata
foreach (array('start', 'end', 'due', 'allday', 'recurrence', 'location') as $key) {
if (isset($event[$key])) {
- $metadata[$key] = $event[$key] instanceof DateTime ? $event[$key]->format('c') : $event[$key];
+ $metadata[$key] = $event[$key] instanceof DateTimeInterface ? $event[$key]->format('c') : $event[$key];
}
}
}
// when receiving iTip REQUEST messages:
else if ($method == 'REQUEST') {
$emails = $this->lib->get_user_emails();
$title = $event['sequence'] > 0 ? $this->gettext('itipupdate') : $this->gettext('itipinvitation');
$metadata['rsvp'] = true;
if (is_object($event['start'])) {
$metadata['date'] = $event['start']->format('U');
}
// check for X-KOLAB-INVITATIONTYPE property and only show accept/decline buttons
if (self::get_custom_property($event, 'X-KOLAB-INVITATIONTYPE') == 'CONFIRMATION') {
$this->rsvp_actions = array('accepted','declined');
$metadata['nosave'] = true;
}
// 1. display RSVP buttons (if the user was invited)
foreach ($this->rsvp_actions as $method) {
$rsvp_buttons .= html::tag('input', array(
'type' => 'button',
'class' => "button $method",
'onclick' => "rcube_libcalendaring.add_from_itip_mail('" . rcube::JQ($mime_id) . "', '$task', '$method', '$dom_id')",
'value' => $this->gettext('itip' . $method),
));
}
// add button to open calendar/preview
if (!empty($preview_url)) {
$msgref = $this->lib->ical_message->folder . '/' . $this->lib->ical_message->uid . '#' . $mime_id;
$rsvp_buttons .= html::tag('input', array(
'type' => 'button',
// TODO: Temp. disable this button on small screen in Elastic (Bifrost#T105747)
'class' => "button preview hidden-phone hidden-small",
'onclick' => "rcube_libcalendaring.open_itip_preview('" . rcube::JQ($preview_url) . "', '" . rcube::JQ($msgref) . "')",
'value' => $this->gettext('openpreview'),
));
}
// 2. update the local copy with minor changes
$update_button = html::tag('input', array(
'type' => 'button',
'class' => 'button',
'onclick' => "rcube_libcalendaring.add_from_itip_mail('" . rcube::JQ($mime_id) . "', '$task')",
'value' => $this->gettext('updatemycopy'),
));
// 3. Simply import the event without replying
$import_button = html::tag('input', array(
'type' => 'button',
'class' => 'button',
'onclick' => "rcube_libcalendaring.add_from_itip_mail('" . rcube::JQ($mime_id) . "', '$task')",
'value' => $this->gettext('importtocalendar'),
));
// check my status as an attendee
foreach ($event['attendees'] as $attendee) {
if ($attendee['email'] && $attendee['role'] != 'ORGANIZER' && in_array(strtolower($attendee['email']), $emails)) {
$metadata['attendee'] = $attendee['email'];
$metadata['rsvp'] = $attendee['rsvp'] || $attendee['role'] != 'NON-PARTICIPANT';
$rsvp_status = !empty($attendee['status']) ? strtoupper($attendee['status']) : 'NEEDS-ACTION';
break;
}
}
// add itip reply message controls
$rsvp_buttons .= html::div('itip-reply-controls', $this->itip_rsvp_options_ui($dom_id, !empty($metadata['nosave'])));
$buttons[] = html::div(array('id' => 'rsvp-'.$dom_id, 'class' => 'rsvp-buttons', 'style' => 'display:none'), $rsvp_buttons);
$buttons[] = html::div(array('id' => 'update-'.$dom_id, 'style' => 'display:none'), $update_button);
// prepare autocompletion for delegation dialog
if (in_array('delegated', $this->rsvp_actions)) {
$this->rc->autocomplete_init();
}
}
// for CANCEL messages, we can:
else if ($method == 'CANCEL') {
$title = $this->gettext('itipcancellation');
$event_prop = array_filter(array(
'uid' => $event['uid'],
'_instance' => isset($event['_instance']) ? $event['_instance'] : null,
'_savemode' => isset($event['_savemode']) ? $event['_savemode'] : null,
));
// 1. remove the event from our calendar
$button_remove = html::tag('input', array(
'type' => 'button',
'class' => 'button',
'onclick' => "rcube_libcalendaring.remove_from_itip(" . rcube_output::json_serialize($event_prop) . ", '$task', '" . rcube::JQ($event['title']) . "')",
'value' => $this->gettext('removefromcalendar'),
));
// 2. update our copy with status=cancelled
$button_update = html::tag('input', array(
'type' => 'button',
'class' => 'button',
'onclick' => "rcube_libcalendaring.add_from_itip_mail('" . rcube::JQ($mime_id) . "', '$task')",
'value' => $this->gettext('updatemycopy'),
));
$buttons[] = html::div(array('id' => 'rsvp-'.$dom_id, 'style' => 'display:none'), $button_remove . $button_update);
$rsvp_status = 'CANCELLED';
$metadata['rsvp'] = true;
}
// append generic import button
if (!empty($import_button)) {
$buttons[] = html::div(array('id' => 'import-'.$dom_id, 'style' => 'display:none'), $import_button);
}
// pass some metadata about the event and trigger the asynchronous status check
$metadata['fallback'] = $rsvp_status;
$metadata['rsvp'] = intval($metadata['rsvp']);
$this->rc->output->add_script("rcube_libcalendaring.fetch_itip_object_status(" . rcube_output::json_serialize($metadata) . ")", 'docready');
// get localized texts from the right domain
foreach (array('savingdata','deleteobjectconfirm','declinedeleteconfirm','declineattendee',
'cancel','itipdelegated','declineattendeeconfirm','itipcomment','delegateinvitation',
'delegateto','delegatersvpme','delegateinvalidaddress') as $label) {
$this->rc->output->command('add_label', "itip.$label", $this->gettext($label));
}
// show event details with buttons
return $this->itip_object_details_table($event, $title) .
html::div(array('class' => 'itip-buttons', 'id' => 'itip-buttons-' . asciiwords($metadata['uid'], true)), join('', $buttons));
}
/**
* Render an RSVP UI widget with buttons to respond on iTip invitations
*/
function itip_rsvp_buttons($attrib = array(), $actions = null)
{
$attrib += array('type' => 'button');
if (!$actions) {
$actions = $this->rsvp_actions;
}
$buttons = '';
foreach ($actions as $method) {
$buttons .= html::tag('input', array(
'type' => $attrib['type'],
'name' => !empty($attrib['iname']) ? $attrib['iname'] : null,
'class' => 'button',
'rel' => $method,
'value' => $this->gettext('itip' . $method),
));
}
// add localized texts for the delegation dialog
if (in_array('delegated', $actions)) {
foreach (array('itipdelegated','itipcomment','delegateinvitation',
'delegateto','delegatersvpme','delegateinvalidaddress','cancel') as $label) {
$this->rc->output->command('add_label', "itip.$label", $this->gettext($label));
}
}
foreach (array('all','current','future') as $mode) {
$this->rc->output->command('add_label', "rsvpmode$mode", $this->gettext("rsvpmode$mode"));
}
$savemode_radio = new html_radiobutton(array('name' => '_rsvpmode', 'class' => 'rsvp-replymode'));
return html::div($attrib,
html::div('label', $this->gettext('acceptinvitation')) .
html::div('rsvp-buttons itip-buttons',
$buttons .
html::div('itip-reply-controls', $this->itip_rsvp_options_ui($attrib['id']))
)
);
}
/**
* Render UI elements to control iTip reply message sending
*/
public function itip_rsvp_options_ui($dom_id, $disable = false)
{
$itip_sending = $this->rc->config->get('calendar_itip_send_option', 3);
// itip sending is entirely disabled
if ($itip_sending === 0) {
return '';
}
// add checkbox to suppress itip reply message
else if ($itip_sending >= 2) {
$toggle_attrib = array(
'type' => 'checkbox',
'id' => 'noreply-'.$dom_id,
'value' => 1,
'disabled' => $disable,
'checked' => ($itip_sending & 1) == 0,
'class' => 'pretty-checkbox',
);
$rsvp_additions = html::label(array('class' => 'noreply-toggle'),
html::tag('input', $toggle_attrib) . ' ' . $this->gettext('itipsuppressreply')
);
}
// add input field for reply comment
$toggle_attrib = array(
'href' => '#toggle',
'class' => 'reply-comment-toggle',
'onclick' => '$(this).hide().parent().find(\'textarea\').show().focus()'
);
$textarea_attrib = array(
'id' => 'reply-comment-' . $dom_id,
'name' => '_comment',
'cols' => 40,
'rows' => 4,
'class' => 'form-control',
'style' => 'display:none',
'placeholder' => $this->gettext('itipcomment')
);
$rsvp_additions .= html::a($toggle_attrib, $this->gettext('itipeditresponse'))
. html::div('itip-reply-comment', html::tag('textarea', $textarea_attrib, ''));
return $rsvp_additions;
}
/**
* Render event/task details in a table
*/
function itip_object_details_table($event, $title)
{
$table = new html_table(array('cols' => 2, 'border' => 0, 'class' => 'calendar-eventdetails'));
$table->add('ititle', $title);
$table->add('title', rcube::Q(trim($event['title'])));
if ($event['start'] && $event['end']) {
$table->add('label', $this->gettext('date'));
$table->add('date', rcube::Q($this->lib->event_date_text($event)));
}
else if ($event['due'] && $event['_type'] == 'task') {
$table->add('label', $this->gettext('date'));
$table->add('date', rcube::Q($this->lib->event_date_text($event)));
}
if (!empty($event['recurrence_date'])) {
$table->add('label', '');
$table->add('recurrence-id', $this->gettext($event['thisandfuture'] ? 'itipfutureoccurrence' : 'itipsingleoccurrence'));
}
else if (!empty($event['recurrence'])) {
$table->add('label', $this->gettext('recurring'));
$table->add('recurrence', $this->lib->recurrence_text($event['recurrence']));
}
if (isset($event['location']) && ($location = trim($event['location']))) {
$table->add('label', $this->gettext('location'));
$table->add('location', rcube::Q($location));
}
if (!empty($event['status']) && ($event['status'] == 'COMPLETED' || $event['status'] == 'CANCELLED')) {
$table->add('label', $this->gettext('status'));
$table->add('status', $this->gettext('status-' . strtolower($event['status'])));
}
if (isset($event['comment']) && ($comment = trim($event['comment']))) {
$table->add('label', $this->gettext('comment'));
$table->add('location', rcube::Q($comment));
}
return $table->show();
}
/**
* Create iTIP invitation token for later replies via URL
*
* @param array Hash array with event properties
* @param string Attendee email address
* @return string Invitation token
*/
public function store_invitation($event, $attendee)
{
// empty stub
return false;
}
/**
* Mark invitations for the given event as cancelled
*
* @param array Hash array with event properties
*/
public function cancel_itip_invitation($event)
{
// empty stub
return false;
}
/**
* Utility function to get the value of a custom property
*/
public static function get_custom_property($event, $name)
{
$ret = false;
if (is_array($event['x-custom'])) {
array_walk($event['x-custom'], function($prop, $i) use ($name, &$ret) {
if (strcasecmp($prop[0], $name) === 0) {
$ret = $prop[1];
}
});
}
return $ret;
}
/**
* Compare email address
*/
public static function compare_email($value, $email, $email_utf = null)
{
$v1 = !empty($email) && strcasecmp($value, $email) === 0;
$v2 = !empty($email_utf) && strcasecmp($value, $email_utf) === 0;
return $v1 || $v2;
}
/**
* Find an attendee that is not the organizer and has an email matching $email_field
*/
public function find_attendee_by_email($attendees, $email_field, $email, $email_utf = null) {
foreach ($attendees as $_attendee) {
if ($attendee['role'] == 'ORGANIZER') {
continue;
}
if (!empty($attendee[$email_field]) && self::compare_email($attendee[$email_field], $email, $email_utf)) {
return $attendee;
}
}
return null;
}
/**
* Find the replying attendee in a REPLY
*/
public static function find_reply_attendee($event) {
// remove the organizer
$itip_attendees = array_filter($event['attendees'], function($item) { return $item['role'] != 'ORGANIZER' && !empty($item['email']); });
$attendee = null;
// According to rfc there should only be one attendee for a REPLY
if (count($itip_attendees) == 1) {
return array_pop($itip_attendees);
}
// If we don't have anything to match by, pick the first and hope for the best.
if (empty($event['_sender'])) {
return array_shift($itip_attendees);
}
// try to match by sent-by
if ($attendee = self::find_attendee_by_email($itip_attendees, 'sent-by', $event['_sender'], $event['_sender_utf'])) {
return $attendee;
}
// try to match by email
if ($attendee = self::find_attendee_by_email($itip_attendees, 'email', $event['_sender'], $event['_sender_utf'])) {
return $attendee;
}
return null;
}
}
diff --git a/plugins/libcalendaring/lib/libcalendaring_recurrence.php b/plugins/libcalendaring/lib/libcalendaring_recurrence.php
index 4eebd68d..8a336112 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 object calendar The calendar plugin instance
+ * @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 object DateTime The recurrence start date
+ * @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')) {
$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')) {
$this->engine->addRDate($rdate->format('Y'), $rdate->format('n'), $rdate->format('j'));
}
}
}
}
/**
* Setter for (new) recurrence start date
*
- * @param object DateTime The 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 mixed DateTime object or False if recurrence ended
+ * @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 DateTime) {
+ 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 DateTime) {
- return $last;
+ 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/libcalendaring.php b/plugins/libcalendaring/libcalendaring.php
index 29f26171..6d7c2d6a 100644
--- a/plugins/libcalendaring/libcalendaring.php
+++ b/plugins/libcalendaring/libcalendaring.php
@@ -1,1582 +1,1582 @@
<?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()
{
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();
}
/**
* 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 DateTime && empty($dt->_dateonly) && !$dateonly) {
+ 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 DateTime) {
+ 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 DateTime) {
+ 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 DateTime) {
+ 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
*/
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 DateTime) {
+ 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/libvcalendar.php b/plugins/libcalendaring/libvcalendar.php
index c8f3cb1e..17629e04 100644
--- a/plugins/libcalendaring/libvcalendar.php
+++ b/plugins/libcalendaring/libvcalendar.php
@@ -1,1532 +1,1538 @@
<?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
{
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) {
+ 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) {
+ 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 DateTime) {
+ if (!empty($event['start']) && $event['start'] instanceof DateTimeInterface) {
$this->_apply_timezone($event['start']);
}
else {
unset($event['start']);
}
- if (!empty($event['end']) && $event['end'] instanceof DateTime) {
+ 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 DateTime(null, $this->timezone);
+ $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) {
+ 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 ? array() : null;
+ return $as_array ? [] : null;
}
- else if ($prop instanceof VObject\Property\iCalendar\DateTime) {
+
+ if ($prop instanceof VObject\Property\ICalendar\DateTime) {
if (count($prop->getDateTimes()) > 1) {
- $dt = array();
+ $dt = [];
$dateonly = !$prop->hasTime();
+
foreach ($prop->getDateTimes() as $item) {
+ $item = libcalendaring_datetime::createFromImmutable($item);
$item->_dateonly = $dateonly;
$dt[] = $item;
}
}
else {
- $dt = $prop->getDateTime();
+ $dt = libcalendaring_datetime::createFromImmutable($prop->getDateTime());
if (!$prop->hasTime()) {
$dt->_dateonly = true;
}
}
}
- else if ($prop instanceof VObject\Property\iCalendar\Period) {
- $dt = array();
+ 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[] = array($start, $end);
+
+ $dt[] = [libcalendaring_datetime::createFromImmutable($start), libcalendaring_datetime::createFromImmutable($end)];
}
catch (Exception $e) {
// ignore single date parse errors
}
}
}
- else if ($prop instanceof \DateTime) {
- $dt = $prop;
+ 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) ? array() : 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 DateTime) {
+ 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 DateTime) {
+ 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 DateTime) {
+ 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 DateTime) {
+ 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(
// vCard
'N',
'ADR',
'ORG',
'GENDER',
'LOCATION',
// iCalendar
'REQUEST-STATUS',
);
}
diff --git a/plugins/libcalendaring/tests/libcalendaring.php b/plugins/libcalendaring/tests/LibcalendaringTest.php
similarity index 91%
rename from plugins/libcalendaring/tests/libcalendaring.php
rename to plugins/libcalendaring/tests/LibcalendaringTest.php
index e93e0b32..12595300 100644
--- a/plugins/libcalendaring/tests/libcalendaring.php
+++ b/plugins/libcalendaring/tests/LibcalendaringTest.php
@@ -1,184 +1,184 @@
<?php
/**
* libcalendaring plugin's utility functions tests
*
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 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_test extends PHPUnit\Framework\TestCase
+class LibcalendaringTest extends PHPUnit\Framework\TestCase
{
- function setUp()
+ function setUp(): void
{
require_once __DIR__ . '/../libcalendaring.php';
}
/**
* libcalendaring::parse_alarm_value()
*/
function test_parse_alarm_value()
{
$alarm = libcalendaring::parse_alarm_value('-15M');
$this->assertEquals('15', $alarm[0]);
$this->assertEquals('-M', $alarm[1]);
$this->assertEquals('-PT15M', $alarm[3]);
$alarm = libcalendaring::parse_alarm_value('-PT5H');
$this->assertEquals('5', $alarm[0]);
$this->assertEquals('-H', $alarm[1]);
$alarm = libcalendaring::parse_alarm_value('P0DT1H0M0S');
$this->assertEquals('1', $alarm[0]);
$this->assertEquals('+H', $alarm[1]);
// FIXME: this should return something like (1140 + 120 + 30)M
$alarm = libcalendaring::parse_alarm_value('-P1DT2H30M');
// $this->assertEquals('1590', $alarm[0]);
// $this->assertEquals('-M', $alarm[1]);
$alarm = libcalendaring::parse_alarm_value('@1420722000');
$this->assertInstanceOf('DateTime', $alarm[0]);
}
/**
* libcalendaring::get_next_alarm()
*/
function test_get_next_alarm()
{
// alarm 10 minutes before event
$date = date('Ymd', strtotime('today + 2 days'));
$event = array(
'start' => new DateTime($date . 'T160000Z'),
'end' => new DateTime($date . 'T200000Z'),
'valarms' => array(
array(
'trigger' => '-PT10M',
'action' => 'DISPLAY',
),
),
);
$alarm = libcalendaring::get_next_alarm($event);
$this->assertEquals($event['valarms'][0]['action'], $alarm['action']);
$this->assertEquals(strtotime($date . 'T155000Z'), $alarm['time']);
// alarm 1 hour after event start
$event['valarms'] = array(
array(
'trigger' => '+PT1H',
),
);
$alarm = libcalendaring::get_next_alarm($event);
$this->assertEquals('DISPLAY', $alarm['action']);
$this->assertEquals(strtotime($date . 'T170000Z'), $alarm['time']);
// alarm 1 hour before event end
$event['valarms'] = array(
array(
'trigger' => '-PT1H',
'related' => 'END',
),
);
$alarm = libcalendaring::get_next_alarm($event);
$this->assertEquals('DISPLAY', $alarm['action']);
$this->assertEquals(strtotime($date . 'T190000Z'), $alarm['time']);
// alarm 1 hour after event end
$event['valarms'] = array(
array(
'trigger' => 'PT1H',
'related' => 'END',
),
);
$alarm = libcalendaring::get_next_alarm($event);
$this->assertEquals('DISPLAY', $alarm['action']);
$this->assertEquals(strtotime($date . 'T210000Z'), $alarm['time']);
// ignore past alarms
$event['start'] = new DateTime('today 22:00:00');
$event['end'] = new DateTime('today 23:00:00');
$event['valarms'] = array(
array(
'trigger' => '-P2D',
'action' => 'EMAIL',
),
array(
'trigger' => '-PT30M',
'action' => 'DISPLAY',
),
);
$alarm = libcalendaring::get_next_alarm($event);
$this->assertEquals('DISPLAY', $alarm['action']);
$this->assertEquals(strtotime('today 21:30:00'), $alarm['time']);
// absolute alarm date/time
$event['valarms'] = array(
array('trigger' => new DateTime('today 20:00:00'))
);
$alarm = libcalendaring::get_next_alarm($event);
$this->assertEquals($event['valarms'][0]['trigger']->format('U'), $alarm['time']);
// no alarms for cancelled events
$event['status'] = 'CANCELLED';
$alarm = libcalendaring::get_next_alarm($event);
$this->assertEquals(null, $alarm);
}
/**
* libcalendaring::part_is_vcalendar()
*/
function test_part_is_vcalendar()
{
$part = new StdClass;
$part->mimetype = 'text/plain';
$part->filename = 'event.ics';
$this->assertFalse(libcalendaring::part_is_vcalendar($part));
$part->mimetype = 'text/calendar';
$this->assertTrue(libcalendaring::part_is_vcalendar($part));
$part->mimetype = 'text/x-vcalendar';
$this->assertTrue(libcalendaring::part_is_vcalendar($part));
$part->mimetype = 'application/ics';
$this->assertTrue(libcalendaring::part_is_vcalendar($part));
$part->mimetype = 'application/x-any';
$this->assertTrue(libcalendaring::part_is_vcalendar($part));
}
/**
* libcalendaring::to_rrule()
*/
function test_to_rrule()
{
$rrule = array(
'FREQ' => 'MONTHLY',
'BYDAY' => '2WE',
'INTERVAL' => 2,
'UNTIL' => new DateTime('2025-05-01 18:00:00 CEST'),
);
$s = libcalendaring::to_rrule($rrule);
- $this->assertRegExp('/FREQ='.$rrule['FREQ'].'/', $s, "Recurrence Frequence");
- $this->assertRegExp('/INTERVAL='.$rrule['INTERVAL'].'/', $s, "Recurrence Interval");
- $this->assertRegExp('/BYDAY='.$rrule['BYDAY'].'/', $s, "Recurrence BYDAY");
- $this->assertRegExp('/UNTIL=20250501T160000Z/', $s, "Recurrence End date (in UTC)");
+ $this->assertMatchesRegularExpression('/FREQ='.$rrule['FREQ'].'/', $s, "Recurrence Frequence");
+ $this->assertMatchesRegularExpression('/INTERVAL='.$rrule['INTERVAL'].'/', $s, "Recurrence Interval");
+ $this->assertMatchesRegularExpression('/BYDAY='.$rrule['BYDAY'].'/', $s, "Recurrence BYDAY");
+ $this->assertMatchesRegularExpression('/UNTIL=20250501T160000Z/', $s, "Recurrence End date (in UTC)");
}
}
diff --git a/plugins/libcalendaring/tests/libvcalendar.php b/plugins/libcalendaring/tests/LibvcalendarTest.php
similarity index 71%
rename from plugins/libcalendaring/tests/libvcalendar.php
rename to plugins/libcalendaring/tests/LibvcalendarTest.php
index 8872fea7..9c055836 100644
--- a/plugins/libcalendaring/tests/libvcalendar.php
+++ b/plugins/libcalendaring/tests/LibvcalendarTest.php
@@ -1,608 +1,608 @@
<?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 libvcalendar_test extends PHPUnit\Framework\TestCase
+class LibvcalendarTest extends PHPUnit\Framework\TestCase
{
- function setUp()
+ private $attachment_data;
+
+ function setUp(): void
{
require_once __DIR__ . '/../libvcalendar.php';
require_once __DIR__ . '/../libcalendaring.php';
}
/**
* Simple iCal parsing test
*/
function test_import()
{
$ical = new libvcalendar();
$ics = file_get_contents(__DIR__ . '/resources/snd.ics');
$events = $ical->import($ics, 'UTF-8');
$this->assertEquals(1, count($events));
$event = $events[0];
- $this->assertInstanceOf('DateTime', $event['created'], "'created' property is DateTime object");
- $this->assertInstanceOf('DateTime', $event['changed'], "'changed' property is DateTime object");
+ $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('DateTime', $event['start'], "'start' property is DateTime object");
- $this->assertInstanceOf('DateTime', $event['end'], "'end' property is DateTime object");
+ $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();
$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->fopen(__DIR__ . '/resources/multiple-rdate.ics', 'UTF-8');
- $events = array();
+ $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();
$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('DateTime', $event['created'], "Created date field");
+ $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();
$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->assertContains('<title>Kalender</title>', $attachment['data'], "Attachment content (decoded)");
+ $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('DateTime', $rrule['UNTIL'], "Recurrence end date");
+ $this->assertInstanceOf('DateTimeInterface', $rrule['UNTIL'], "Recurrence end date");
$this->assertEquals(2, count($rrule['EXDATE']), "Recurrence EXDATEs");
- $this->assertInstanceOf('DateTime', $rrule['EXDATE'][0], "Recurrence EXDATE as DateTime");
+ $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('DateTime', $exception['start'], "Exception start");
+ $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('DateTime', $events[0]['recurrence_date'], "Recurrence-ID as date");
+ $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();
$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('DateTime', $event['valarms'][2]['trigger'], "Absolute trigger date/time");
+ $this->assertInstanceOf('DateTimeInterface', $event['valarms'][2]['trigger'], "Absolute trigger date/time");
// test alarms export
- $ics = $ical->export(array($event));
- $this->assertContains('ACTION:DISPLAY', $ics, "Display alarm block");
- $this->assertContains('ACTION:EMAIL', $ics, "Email alarm block");
- $this->assertContains('DESCRIPTION:This is the first event reminder', $ics, "Alarm description");
- $this->assertContains('SUMMARY:This is the reminder message', $ics, "Email alarm summary");
- $this->assertContains('ATTENDEE:mailto:reminder-recipient@example.org', $ics, "Email alarm recipient");
- $this->assertContains('TRIGGER;VALUE=DATE-TIME:20130812', $ics, "Date-Time trigger");
+ $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();
$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();
$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();
$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->assertContains('ATTENDEE;CN="Kolab, Thomas";PARTSTAT=', $ics, "Quoted attendee parameters");
+ $this->assertStringContainsString('ATTENDEE;CN="Kolab, Thomas";PARTSTAT=', $ics, "Quoted attendee parameters");
}
/**
* Parse RDATE properties (#2885)
*/
function test_rdate()
{
$ical = new libvcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/multiple-rdate.ics', 'UTF-8');
$event = $events[0];
$this->assertEquals(9, count($event['recurrence']['RDATE']));
- $this->assertInstanceOf('DateTime', $event['recurrence']['RDATE'][0]);
- $this->assertInstanceOf('DateTime', $event['recurrence']['RDATE'][1]);
+ $this->assertInstanceOf('DateTimeInterface', $event['recurrence']['RDATE'][0]);
+ $this->assertInstanceOf('DateTimeInterface', $event['recurrence']['RDATE'][1]);
}
/**
* @depends test_import
*/
function test_freebusy()
{
$ical = new libvcalendar();
$ical->import_from_file(__DIR__ . '/resources/freebusy.ifb', 'UTF-8');
$freebusy = $ical->freebusy;
- $this->assertInstanceOf('DateTime', $freebusy['start'], "'start' property is DateTime object");
- $this->assertInstanceOf('DateTime', $freebusy['end'], "'end' property is DateTime object");
+ $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->import_from_file(__DIR__ . '/resources/dummy.ifb', 'UTF-8');
$freebusy = $ical->freebusy;
$this->assertEquals(0, count($freebusy['periods']), "Ignore 0-length freebudy periods");
- $this->assertContains('dummy', $freebusy['comment'], "Parse comment");
+ $this->assertStringContainsString('dummy', $freebusy['comment'], "Parse comment");
}
function test_vtodo()
{
$ical = new libvcalendar();
$tasks = $ical->import_from_file(__DIR__ . '/resources/vtodo.ics', 'UTF-8', true);
$task = $tasks[0];
- $this->assertInstanceOf('DateTime', $task['start'], "'start' property is DateTime object");
- $this->assertInstanceOf('DateTime', $task['due'], "'due' property is DateTime object");
+ $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(array($completed));
- $this->assertRegExp('/COMPLETED(;VALUE=DATE-TIME)?:[0-9TZ]+/', $ics, "Export COMPLETED property");
+ $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();
$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['start']->setTimezone(new DateTimezone('America/Montreal'));
$event['end']->setTimezone(new DateTimezone('Europe/Berlin'));
- $ics = $ical->export(array($event), 'REQUEST', false, array($this, 'get_attachment_data'), true);
+ $ics = $ical->export([$event], 'REQUEST', false, [$this, 'get_attachment_data'], true);
- $this->assertContains('BEGIN:VCALENDAR', $ics, "VCALENDAR encapsulation BEGIN");
+ $this->assertStringContainsString('BEGIN:VCALENDAR', $ics, "VCALENDAR encapsulation BEGIN");
- $this->assertContains('BEGIN:VTIMEZONE', $ics, "VTIMEZONE encapsulation BEGIN");
- $this->assertContains('TZID:Europe/Berlin', $ics, "Timezone ID");
- $this->assertContains('TZOFFSETFROM:+0100', $ics, "Timzone transition FROM");
- $this->assertContains('TZOFFSETTO:+0200', $ics, "Timzone transition TO");
- $this->assertContains('TZOFFSETFROM:-0400', $ics, "TZOFFSETFROM with negative offset (Bug T428)");
- $this->assertContains('TZOFFSETTO:-0500', $ics, "TZOFFSETTO with negative offset (Bug T428)");
- $this->assertContains('END:VTIMEZONE', $ics, "VTIMEZONE encapsulation END");
+ $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->assertContains('BEGIN:VEVENT', $ics, "VEVENT encapsulation BEGIN");
+ $this->assertStringContainsString('BEGIN:VEVENT', $ics, "VEVENT encapsulation BEGIN");
$this->assertSame(2, substr_count($ics, 'DTSTAMP'), "Duplicate DTSTAMP (T1148)");
- $this->assertContains('UID:ac6b0aee-2519-4e5c-9a25-48c57064c9f0', $ics, "Event UID");
- $this->assertContains('SEQUENCE:' . $event['sequence'], $ics, "Export Sequence number");
- $this->assertContains('DESCRIPTION:*Exported by', $ics, "Export Description");
- $this->assertContains('ORGANIZER;CN=Rolf Test:mailto:rolf@', $ics, "Export organizer");
- $this->assertRegExp('/ATTENDEE.*;ROLE=REQ-PARTICIPANT/', $ics, "Export Attendee ROLE");
- $this->assertRegExp('/ATTENDEE.*;PARTSTAT=NEEDS-ACTION/', $ics, "Export Attendee Status");
- $this->assertRegExp('/ATTENDEE.*;RSVP=TRUE/', $ics, "Export Attendee RSVP");
- $this->assertRegExp('/:mailto:rolf2@/', $ics, "Export Attendee mailto:");
+ $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->assertRegExp('/RRULE:.*FREQ='.$rrule['FREQ'].'/', $ics, "Export Recurrence Frequence");
- $this->assertRegExp('/RRULE:.*INTERVAL='.$rrule['INTERVAL'].'/', $ics, "Export Recurrence Interval");
- $this->assertRegExp('/RRULE:.*UNTIL=20140718T215959Z/', $ics, "Export Recurrence End date");
- $this->assertRegExp('/RRULE:.*BYDAY='.$rrule['BYDAY'].'/', $ics, "Export Recurrence BYDAY");
- $this->assertRegExp('/EXDATE.*:20131218/', $ics, "Export Recurrence EXDATE");
-
- $this->assertContains('BEGIN:VALARM', $ics, "Export VALARM");
- $this->assertContains('TRIGGER;RELATED=END:-PT12H', $ics, "Export Alarm trigger");
-
- $this->assertRegExp('/ATTACH.*;VALUE=BINARY/', $ics, "Embed attachment");
- $this->assertRegExp('/ATTACH.*;ENCODING=BASE64/', $ics, "Attachment B64 encoding");
- $this->assertRegExp('!ATTACH.*;FMTTYPE=text/html!', $ics, "Attachment mimetype");
- $this->assertRegExp('!ATTACH.*;X-LABEL=calendar.html!', $ics, "Attachment filename with X-LABEL");
-
- $this->assertContains('END:VEVENT', $ics, "VEVENT encapsulation END");
- $this->assertContains('END:VCALENDAR', $ics, "VCALENDAR encapsulation END");
+ $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();
$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->assertContains('BEGIN:VCALENDAR', $ics, "VCALENDAR encapsulation BEGIN");
- $this->assertContains('END:VCALENDAR', $ics, "VCALENDAR encapsulation END");
+ $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();
$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'] = array($exception1, $exception2);
+ $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->assertContains('RECURRENCE-ID;TZID=Europe/Zurich:20130814', $ics, "Recurrence-ID (1) being the exception date");
- $this->assertContains('RECURRENCE-ID;TZID=Europe/Zurich:20131113', $ics, "Recurrence-ID (2) being the exception date");
- $this->assertContains('SUMMARY:'.$exception2['title'], $ics, "Exception title");
+ $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 = array(
+ $event = [
'uid' => '1234567890',
'start' => new DateTime('now'),
'end' => new DateTime('now + 30min'),
'title' => 'test_export_valid_rrules',
- 'recurrence' => array(
+ 'recurrence' => [
'FREQ' => 'DAILY',
'COUNT' => 5,
- 'EXDATE' => array(),
- 'RDATE' => array(),
- ),
- );
+ 'EXDATE' => [],
+ 'RDATE' => [],
+ ],
+ ];
$ical = new libvcalendar();
- $ics = $ical->export(array($event), null, false, null, false);
+ $ics = $ical->export([$event], null, false, null, false);
- $this->assertNotContains('EXDATE=', $ics);
- $this->assertNotContains('RDATE=', $ics);
+ $this->assertStringNotContainsString('EXDATE=', $ics);
+ $this->assertStringNotContainsString('RDATE=', $ics);
}
/**
*
*/
function test_export_rdate()
{
$ical = new libvcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/multiple-rdate.ics', 'UTF-8');
$ics = $ical->export($events, null, false);
- $this->assertContains('RDATE:20140520T020000Z', $ics, "VALUE=PERIOD is translated into single DATE-TIME values");
+ $this->assertStringContainsString('RDATE:20140520T020000Z', $ics, "VALUE=PERIOD is translated into single DATE-TIME values");
}
/**
* @depends test_export
*/
function test_export_direct()
{
$ical = new libvcalendar();
$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->assertContains('BEGIN:VCALENDAR', $output, "VCALENDAR encapsulation BEGIN");
- $this->assertContains('END:VCALENDAR', $output, "VCALENDAR encapsulation END");
+ $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();
$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->assertContains('TZID=Europe/Berlin', $localtime->serialize());
- $this->assertContains('VALUE=DATE', $localdate->serialize());
- $this->assertContains('20130901T120000Z', $utctime->serialize());
- $this->assertContains('20130901T100000Z', $asutctime->serialize());
+ $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'));
$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');
$this->assertEquals(false, $vtz);
// invalid input data
$vtz = libvcalendar::get_vtimezone(new DateTime());
$this->assertEquals(false, $vtz);
// DateTimezone as input data
$vtz = libvcalendar::get_vtimezone(new DateTimezone('Pacific/Chatham'));
$this->assertInstanceOf('\Sabre\VObject\Component', $vtz);
- $this->assertContains('TZOFFSETFROM:+1245', $vtz->serialize());
- $this->assertContains('TZOFFSETTO:+1345', $vtz->serialize());
+ $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'));
$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 a2cbe149..8a00d7a6 100644
--- a/plugins/libkolab/composer.json
+++ b/plugins/libkolab/composer.json
@@ -1,32 +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": ">=5.3.0",
+ "php": ">=7.4.0",
"roundcube/plugin-installer": ">=0.1.3",
+ "kolab/libcalendaring": ">=3.4.0",
"pear/http_request2": "~2.3.0",
"caxy/php-htmldiff": "~0.1.7"
}
}
diff --git a/plugins/libkolab/lib/kolab_date_recurrence.php b/plugins/libkolab/lib/kolab_date_recurrence.php
index 3197cde5..9b09074b 100644
--- a/plugins/libkolab/lib/kolab_date_recurrence.php
+++ b/plugins/libkolab/lib/kolab_date_recurrence.php
@@ -1,238 +1,239 @@
<?php
/**
* Recurrence computation class for xcal-based Kolab format objects
*
* Utility class to compute instances of recurring events.
- * It requires the libcalendaring PHP module to be installed and loaded.
+ * It requires the libcalendaring PHP extension to be installed and loaded.
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012-2016, 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_date_recurrence
{
private /* EventCal */ $engine;
private /* kolab_format_xcal */ $object;
private /* DateTime */ $start;
private /* DateTime */ $next;
private /* cDateTime */ $cnext;
private /* DateInterval */ $duration;
private /* bool */ $allday;
/**
* Default constructor
*
* @param kolab_format_xcal The Kolab object to operate on
*/
function __construct($object)
{
$data = $object->to_array();
$this->object = $object;
$this->engine = $object->to_libcal();
$this->start = $this->next = $data['start'];
$this->allday = !empty($data['allday']);
$this->cnext = kolab_format::get_datetime($this->next);
if (is_object($data['start']) && is_object($data['end'])) {
$this->duration = $data['start']->diff($data['end']);
}
else {
// Prevent from errors when end date is not set (#5307) RFC5545 3.6.1
$seconds = !empty($data['end']) ? ($data['end'] - $data['start']) : 0;
$this->duration = new DateInterval('PT' . $seconds . 'S');
}
}
/**
* Get date/time of the next occurence of this event
*
- * @param boolean Return a Unix timestamp instead of a DateTime object
+ * @param bool Return a Unix timestamp instead of a DateTime object
*
- * @return mixed DateTime object/unix timestamp or False if recurrence ended
+ * @return DateTime|int|false Object/unix timestamp or False if recurrence ended
*/
public function next_start($timestamp = false)
{
$time = false;
if ($this->engine && $this->next) {
if (($cnext = new cDateTime($this->engine->getNextOccurence($this->cnext))) && $cnext->isValid()) {
$next = kolab_format::php_datetime($cnext, $this->start->getTimezone());
$time = $timestamp ? $next->format('U') : $next;
if ($this->allday) {
// it looks that for allday events the occurrence time
// is reset to 00:00:00, this is causing various issues
$next->setTime($this->start->format('G'), $this->start->format('i'), $this->start->format('s'));
$next->_dateonly = true;
}
$this->cnext = $cnext;
$this->next = $next;
}
}
return $time;
}
/**
* Get the next recurring instance of this event
*
* @return mixed Array with event properties or False if recurrence ended
*/
public function next_instance()
{
if ($next_start = $this->next_start()) {
$next_end = clone $next_start;
$next_end->add($this->duration);
$next = $this->object->to_array();
$recurrence_id_format = libkolab::recurrence_id_format($next);
$next['start'] = $next_start;
$next['end'] = $next_end;
$next['recurrence_date'] = clone $next_start;
$next['_instance'] = $next_start->format($recurrence_id_format);
unset($next['_formatobj']);
return $next;
}
return false;
}
/**
* Get the end date of the occurence of this recurrence cycle
*
* @return DateTime|bool End datetime of the last event or False if recurrence exceeds limit
*/
public function end()
{
$event = $this->object->to_array();
// recurrence end date is given
- if ($event['recurrence']['UNTIL'] instanceof DateTime) {
+ if ($event['recurrence']['UNTIL'] instanceof DateTimeInterface) {
return $event['recurrence']['UNTIL'];
}
// let libkolab do the work
if ($this->engine && ($cend = $this->engine->getLastOccurrence())
&& ($end_dt = kolab_format::php_datetime(new cDateTime($cend)))
) {
return $end_dt;
}
// determine a reasonable end date if none given
- if (!$event['recurrence']['COUNT'] && $event['end'] instanceof DateTime) {
+ if (!$event['recurrence']['COUNT'] && $event['end'] instanceof DateTimeInterface) {
$end_dt = clone $event['end'];
$end_dt->add(new DateInterval('P100Y'));
return $end_dt;
}
return false;
}
/**
* Find date/time of the first occurrence
*/
public function first_occurrence()
{
$event = $this->object->to_array();
$start = clone $this->start;
$orig_start = clone $this->start;
$interval = intval($event['recurrence']['INTERVAL'] ?: 1);
switch ($event['recurrence']['FREQ']) {
case 'WEEKLY':
if (empty($event['recurrence']['BYDAY'])) {
return $orig_start;
}
$start->sub(new DateInterval("P{$interval}W"));
break;
case 'MONTHLY':
if (empty($event['recurrence']['BYDAY']) && empty($event['recurrence']['BYMONTHDAY'])) {
return $orig_start;
}
$start->sub(new DateInterval("P{$interval}M"));
break;
case 'YEARLY':
if (empty($event['recurrence']['BYDAY']) && empty($event['recurrence']['BYMONTH'])) {
return $orig_start;
}
$start->sub(new DateInterval("P{$interval}Y"));
break;
case 'DAILY':
if (!empty($event['recurrence']['BYMONTH'])) {
break;
}
default:
return $orig_start;
}
$event['start'] = $start;
$event['recurrence']['INTERVAL'] = $interval;
if ($event['recurrence']['COUNT']) {
// Increase count so we do not stop the loop to early
$event['recurrence']['COUNT'] += 100;
}
// Create recurrence that starts in the past
$object_type = $this->object instanceof kolab_format_task ? 'task' : 'event';
$object = kolab_format::factory($object_type, 3.0);
$object->set($event);
$recurrence = new self($object);
$orig_date = $orig_start->format('Y-m-d');
$found = false;
// find the first occurrence
while ($next = $recurrence->next_start()) {
$start = $next;
if ($next->format('Y-m-d') >= $orig_date) {
$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($event['recurrence'])),
), true);
return null;
}
if ($this->allday) {
$start->_dateonly = true;
}
return $start;
}
}
diff --git a/plugins/libkolab/lib/kolab_format.php b/plugins/libkolab/lib/kolab_format.php
index cde67fad..cf24c293 100644
--- a/plugins/libkolab/lib/kolab_format.php
+++ b/plugins/libkolab/lib/kolab_format.php
@@ -1,793 +1,799 @@
<?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 DateTime)
+ 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 DateTime('@'.$datetime, new DateTimeZone('UTC'));
+ $datetime = new libcalendaring_datetime('@'.$datetime, new DateTimeZone('UTC'));
if ($tz) $datetime->setTimezone($tz);
}
else if (is_string($datetime) && strlen($datetime)) {
- $datetime = $tz ? new DateTime($datetime, $tz) : new DateTime($datetime);
+ $datetime = $tz ? new libcalendaring_datetime($datetime, $tz) : new libcalendaring_datetime($datetime);
}
- else if ($datetime instanceof DateTime) {
+ else if ($datetime instanceof DateTimeInterface) {
$datetime = clone $datetime;
}
}
catch (Exception $e) {}
- if ($datetime instanceof DateTime) {
+ 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 DateTime PHP datetime instance
+ * @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 DateTime;
- $d->setTimezone($dest_tz ?: self::$timezone);
+ $d = new libcalendaring_datetime(null, self::$timezone);
- try {
- if ($tzs = $cdt->timezone()) {
- $tz = new DateTimeZone($tzs);
- $d->setTimezone($tz);
- }
- else if ($cdt->isUTC()) {
- $d->setTimezone(new DateTimeZone('UTC'));
+ 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) { }
}
- 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 e8393a42..860adb65 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')) {
$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 DateTime) {
+ 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 DateTime ? $recurrence_id->format($recurrence_id_format) : strval($recurrence_id);
+ $instance_id = $recurrence_id instanceof DateTimeInterface ? $recurrence_id->format($recurrence_id_format) : strval($recurrence_id);
- if ($object['recurrence_date'] instanceof DateTime) {
+ 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_format_task.php b/plugins/libkolab/lib/kolab_format_task.php
index bc57e6b9..23ba2cc2 100644
--- a/plugins/libkolab/lib/kolab_format_task.php
+++ b/plugins/libkolab/lib/kolab_format_task.php
@@ -1,154 +1,154 @@
<?php
/**
* Kolab Task (ToDo) 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_task extends kolab_format_xcal
{
public $CTYPEv2 = 'application/x-vnd.kolab.task';
public static $scheduling_properties = array('start', 'due', 'summary', 'status');
protected $objclass = 'Todo';
protected $read_func = 'readTodo';
protected $write_func = 'writeTodo';
/**
* Default constructor
*/
function __construct($data = null, $version = 3.0)
{
parent::__construct(is_string($data) ? $data : null, $version);
// copy static property overriden by this class
$this->_scheduling_properties = self::$scheduling_properties;
}
/**
* Set properties to the kolabformat object
*
* @param array Object data as hash array
*/
public function set(&$object)
{
// set common xcal properties
parent::set($object);
$this->obj->setPercentComplete(intval($object['complete']));
$status = kolabformat::StatusUndefined;
if ($object['complete'] == 100 && !array_key_exists('status', $object))
$status = kolabformat::StatusCompleted;
else if ($object['status'] && array_key_exists($object['status'], $this->status_map))
$status = $this->status_map[$object['status']];
$this->obj->setStatus($status);
$this->obj->setStart(self::get_datetime($object['start'], null, $object['start']->_dateonly));
$this->obj->setDue(self::get_datetime($object['due'], null, $object['due']->_dateonly));
$related = new vectors;
if (!empty($object['parent_id']))
$related->push($object['parent_id']);
$this->obj->setRelatedTo($related);
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
/**
*
*/
public function is_valid()
{
return !$this->formaterror && ($this->data || (is_object($this->obj) && $this->obj->isValid()));
}
/**
* Convert the Configuration object into a hash array data structure
*
* @param array Additional data for merge
*
* @return array Config object 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);
$object['complete'] = intval($this->obj->percentComplete());
// if due date is set
if ($due = $this->obj->due())
$object['due'] = self::php_datetime($due);
// related-to points to parent task; we only support one relation
$related = self::vector2array($this->obj->relatedTo());
if (count($related))
$object['parent_id'] = $related[0];
// TODO: map more properties
$this->data = $object;
return $this->data;
}
/**
* Return the reference date for recurrence and alarms
*
* @return mixed DateTime instance of null if no refdate is available
*/
public function get_reference_date()
{
- if ($this->data['due'] && $this->data['due'] instanceof DateTime) {
+ if ($this->data['due'] && $this->data['due'] instanceof DateTimeInterface) {
return $this->data['due'];
}
return self::php_datetime($this->obj->due()) ?: parent::get_reference_date();
}
/**
* 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;
if ($object['status'] == 'COMPLETED' || ($object['complete'] == 100 && empty($object['status'])))
$tags[] = 'x-complete';
if ($object['priority'] == 1)
$tags[] = 'x-flagged';
if ($object['parent_id'])
$tags[] = 'x-parent:' . $object['parent_id'];
return array_unique($tags);
}
}
diff --git a/plugins/libkolab/lib/kolab_format_xcal.php b/plugins/libkolab/lib/kolab_format_xcal.php
index 633d8125..72d8b5ed 100644
--- a/plugins/libkolab/lib/kolab_format_xcal.php
+++ b/plugins/libkolab/lib/kolab_format_xcal.php
@@ -1,770 +1,775 @@
<?php
/**
* Xcal based Kolab format class wrapping libkolabxml bindings
*
* Base class for xcal-based Kolab groupware objects such as event, todo, journal
*
* @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/>.
*/
abstract class kolab_format_xcal extends kolab_format
{
public $CTYPE = 'application/calendar+xml';
public static $fulltext_cols = array('title', 'description', 'location', 'attendees:name', 'attendees:email', 'categories');
public static $scheduling_properties = array('start', 'end', 'location');
protected $_scheduling_properties = null;
protected $role_map = array(
'REQ-PARTICIPANT' => kolabformat::Required,
'OPT-PARTICIPANT' => kolabformat::Optional,
'NON-PARTICIPANT' => kolabformat::NonParticipant,
'CHAIR' => kolabformat::Chair,
);
protected $cutype_map = array(
'INDIVIDUAL' => kolabformat::CutypeIndividual,
'GROUP' => kolabformat::CutypeGroup,
'ROOM' => kolabformat::CutypeRoom,
'RESOURCE' => kolabformat::CutypeResource,
'UNKNOWN' => kolabformat::CutypeUnknown,
);
protected $rrule_type_map = array(
'MINUTELY' => RecurrenceRule::Minutely,
'HOURLY' => RecurrenceRule::Hourly,
'DAILY' => RecurrenceRule::Daily,
'WEEKLY' => RecurrenceRule::Weekly,
'MONTHLY' => RecurrenceRule::Monthly,
'YEARLY' => RecurrenceRule::Yearly,
);
protected $weekday_map = array(
'MO' => kolabformat::Monday,
'TU' => kolabformat::Tuesday,
'WE' => kolabformat::Wednesday,
'TH' => kolabformat::Thursday,
'FR' => kolabformat::Friday,
'SA' => kolabformat::Saturday,
'SU' => kolabformat::Sunday,
);
protected $alarm_type_map = array(
'DISPLAY' => Alarm::DisplayAlarm,
'EMAIL' => Alarm::EMailAlarm,
'AUDIO' => Alarm::AudioAlarm,
);
protected $status_map = array(
'NEEDS-ACTION' => kolabformat::StatusNeedsAction,
'IN-PROCESS' => kolabformat::StatusInProcess,
'COMPLETED' => kolabformat::StatusCompleted,
'CANCELLED' => kolabformat::StatusCancelled,
'TENTATIVE' => kolabformat::StatusTentative,
'CONFIRMED' => kolabformat::StatusConfirmed,
'DRAFT' => kolabformat::StatusDraft,
'FINAL' => kolabformat::StatusFinal,
);
protected $part_status_map = array(
'UNKNOWN' => kolabformat::PartNeedsAction,
'NEEDS-ACTION' => kolabformat::PartNeedsAction,
'TENTATIVE' => kolabformat::PartTentative,
'ACCEPTED' => kolabformat::PartAccepted,
'DECLINED' => kolabformat::PartDeclined,
'DELEGATED' => kolabformat::PartDelegated,
'IN-PROCESS' => kolabformat::PartInProcess,
'COMPLETED' => kolabformat::PartCompleted,
);
/**
* Convert common xcard properties into a hash array data structure
*
* @param array Additional data for merge
*
* @return array Object data as hash array
*/
public function to_array($data = array())
{
// read common object props
$object = parent::to_array($data);
$status_map = array_flip($this->status_map);
$object += array(
'sequence' => intval($this->obj->sequence()),
'title' => $this->obj->summary(),
'location' => $this->obj->location(),
'description' => $this->obj->description(),
'url' => $this->obj->url(),
'status' => $status_map[$this->obj->status()],
'priority' => $this->obj->priority(),
'categories' => self::vector2array($this->obj->categories()),
'start' => self::php_datetime($this->obj->start()),
);
if (method_exists($this->obj, 'comment')) {
$object['comment'] = $this->obj->comment();
}
// read organizer and attendees
if (($organizer = $this->obj->organizer()) && ($organizer->email() || $organizer->name())) {
$object['organizer'] = array(
'email' => $organizer->email(),
'name' => $organizer->name(),
);
}
$role_map = array_flip($this->role_map);
$cutype_map = array_flip($this->cutype_map);
$part_status_map = array_flip($this->part_status_map);
$attvec = $this->obj->attendees();
for ($i=0; $i < $attvec->size(); $i++) {
$attendee = $attvec->get($i);
$cr = $attendee->contact();
if ($cr->email() != $object['organizer']['email']) {
$delegators = $delegatees = array();
$vdelegators = $attendee->delegatedFrom();
for ($j=0; $j < $vdelegators->size(); $j++) {
$delegators[] = $vdelegators->get($j)->email();
}
$vdelegatees = $attendee->delegatedTo();
for ($j=0; $j < $vdelegatees->size(); $j++) {
$delegatees[] = $vdelegatees->get($j)->email();
}
$object['attendees'][] = array(
'role' => $role_map[$attendee->role()],
'cutype' => $cutype_map[$attendee->cutype()],
'status' => $part_status_map[$attendee->partStat()],
'rsvp' => $attendee->rsvp(),
'email' => $cr->email(),
'name' => $cr->name(),
'delegated-from' => $delegators,
'delegated-to' => $delegatees,
);
}
}
- if ($object['start'] instanceof DateTime) {
+ if ($object['start'] instanceof DateTimeInterface) {
$start_tz = $object['start']->getTimezone();
}
// read recurrence rule
if (($rr = $this->obj->recurrenceRule()) && $rr->isValid()) {
$rrule_type_map = array_flip($this->rrule_type_map);
$object['recurrence'] = array('FREQ' => $rrule_type_map[$rr->frequency()]);
if ($intvl = $rr->interval())
$object['recurrence']['INTERVAL'] = $intvl;
if (($count = $rr->count()) && $count > 0) {
$object['recurrence']['COUNT'] = $count;
}
else if ($until = self::php_datetime($rr->end(), $start_tz)) {
$refdate = $this->get_reference_date();
- if ($refdate && $refdate instanceof DateTime && !$refdate->_dateonly) {
+ if ($refdate && $refdate instanceof DateTimeInterface && empty($refdate->_dateonly)) {
$until->setTime($refdate->format('G'), $refdate->format('i'), 0);
}
$object['recurrence']['UNTIL'] = $until;
}
if (($byday = $rr->byday()) && $byday->size()) {
$weekday_map = array_flip($this->weekday_map);
$weekdays = array();
for ($i=0; $i < $byday->size(); $i++) {
$daypos = $byday->get($i);
$prefix = $daypos->occurence();
$weekdays[] = ($prefix ?: '') . $weekday_map[$daypos->weekday()];
}
$object['recurrence']['BYDAY'] = join(',', $weekdays);
}
if (($bymday = $rr->bymonthday()) && $bymday->size()) {
$object['recurrence']['BYMONTHDAY'] = join(',', self::vector2array($bymday));
}
if (($bymonth = $rr->bymonth()) && $bymonth->size()) {
$object['recurrence']['BYMONTH'] = join(',', self::vector2array($bymonth));
}
if ($exdates = $this->obj->exceptionDates()) {
for ($i=0; $i < $exdates->size(); $i++) {
if ($exdate = self::php_datetime($exdates->get($i), $start_tz)) {
$object['recurrence']['EXDATE'][] = $exdate;
}
}
}
}
if ($rdates = $this->obj->recurrenceDates()) {
for ($i=0; $i < $rdates->size(); $i++) {
if ($rdate = self::php_datetime($rdates->get($i), $start_tz)) {
$object['recurrence']['RDATE'][] = $rdate;
}
}
}
// read alarm
$valarms = $this->obj->alarms();
$alarm_types = array_flip($this->alarm_type_map);
$object['valarms'] = array();
for ($i=0; $i < $valarms->size(); $i++) {
$alarm = $valarms->get($i);
$type = $alarm_types[$alarm->type()];
if ($type == 'DISPLAY' || $type == 'EMAIL' || $type == 'AUDIO') { // only some alarms are supported
$valarm = array(
'action' => $type,
'summary' => $alarm->summary(),
'description' => $alarm->description(),
);
if ($type == 'EMAIL') {
$valarm['attendees'] = array();
$attvec = $alarm->attendees();
for ($j=0; $j < $attvec->size(); $j++) {
$cr = $attvec->get($j);
$valarm['attendees'][] = $cr->email();
}
}
else if ($type == 'AUDIO') {
$attach = $alarm->audioFile();
$valarm['uri'] = $attach->uri();
}
if ($start = self::php_datetime($alarm->start())) {
$object['alarms'] = '@' . $start->format('U');
$valarm['trigger'] = $start;
}
else if ($offset = $alarm->relativeStart()) {
$prefix = $offset->isNegative() ? '-' : '+';
$value = '';
$time = '';
if ($w = $offset->weeks()) $value .= $w . 'W';
else if ($d = $offset->days()) $value .= $d . 'D';
else if ($h = $offset->hours()) $time .= $h . 'H';
else if ($m = $offset->minutes()) $time .= $m . 'M';
else if ($s = $offset->seconds()) $time .= $s . 'S';
// assume 'at event time'
if (empty($value) && empty($time)) {
$prefix = '';
$time = '0S';
}
$object['alarms'] = $prefix . $value . $time;
$valarm['trigger'] = $prefix . 'P' . $value . ($time ? 'T' . $time : '');
if ($alarm->relativeTo() == kolabformat::End) {
$valarm['related'] = 'END';
}
}
// read alarm duration and repeat properties
if (($duration = $alarm->duration()) && $duration->isValid()) {
$value = $time = '';
if ($w = $duration->weeks()) $value .= $w . 'W';
else if ($d = $duration->days()) $value .= $d . 'D';
else if ($h = $duration->hours()) $time .= $h . 'H';
else if ($m = $duration->minutes()) $time .= $m . 'M';
else if ($s = $duration->seconds()) $time .= $s . 'S';
$valarm['duration'] = 'P' . $value . ($time ? 'T' . $time : '');
$valarm['repeat'] = $alarm->numrepeat();
}
$object['alarms'] .= ':' . $type; // legacy property
$object['valarms'][] = array_filter($valarm);
}
}
$this->get_attachments($object);
return $object;
}
/**
* Set common xcal properties to the kolabformat object
*
* @param array Event data as hash array
*/
public function set(&$object)
{
$this->init();
$is_new = !$this->obj->uid();
$old_sequence = $this->obj->sequence();
$reschedule = $is_new;
// set common object properties
parent::set($object);
// set sequence value
if (!isset($object['sequence'])) {
if ($is_new) {
$object['sequence'] = 0;
}
else {
$object['sequence'] = $old_sequence;
// increment sequence when updating properties relevant for scheduling.
// RFC 5545: "It is incremented [...] each time the Organizer makes a significant revision to the calendar component."
if ($this->check_rescheduling($object)) {
$object['sequence']++;
}
}
}
$this->obj->setSequence(intval($object['sequence']));
if ($object['sequence'] > $old_sequence) {
$reschedule = true;
}
$this->obj->setSummary($object['title']);
$this->obj->setLocation($object['location']);
$this->obj->setDescription($object['description']);
$this->obj->setPriority($object['priority']);
$this->obj->setCategories(self::array2vector($object['categories']));
$this->obj->setUrl(strval($object['url']));
if (method_exists($this->obj, 'setComment')) {
$this->obj->setComment($object['comment']);
}
// process event attendees
$attendees = new vectorattendee;
foreach ((array)$object['attendees'] as $i => $attendee) {
if ($attendee['role'] == 'ORGANIZER') {
$object['organizer'] = $attendee;
}
else if ($attendee['email'] != $object['organizer']['email']) {
$cr = new ContactReference(ContactReference::EmailReference, $attendee['email']);
$cr->setName($attendee['name']);
// set attendee RSVP if missing
if (!isset($attendee['rsvp'])) {
$object['attendees'][$i]['rsvp'] = $attendee['rsvp'] = $reschedule;
}
$att = new Attendee;
$att->setContact($cr);
$att->setPartStat($this->part_status_map[$attendee['status']]);
$att->setRole($this->role_map[$attendee['role']] ?: kolabformat::Required);
$att->setCutype($this->cutype_map[$attendee['cutype']] ?: kolabformat::CutypeIndividual);
$att->setRSVP((bool)$attendee['rsvp']);
if (!empty($attendee['delegated-from'])) {
$vdelegators = new vectorcontactref;
foreach ((array)$attendee['delegated-from'] as $delegator) {
$vdelegators->push(new ContactReference(ContactReference::EmailReference, $delegator));
}
$att->setDelegatedFrom($vdelegators);
}
if (!empty($attendee['delegated-to'])) {
$vdelegatees = new vectorcontactref;
foreach ((array)$attendee['delegated-to'] as $delegatee) {
$vdelegatees->push(new ContactReference(ContactReference::EmailReference, $delegatee));
}
$att->setDelegatedTo($vdelegatees);
}
if ($att->isValid()) {
$attendees->push($att);
}
else {
rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Invalid event attendee: " . json_encode($attendee),
), true);
}
}
}
$this->obj->setAttendees($attendees);
if ($object['organizer']) {
$organizer = new ContactReference(ContactReference::EmailReference, $object['organizer']['email']);
$organizer->setName($object['organizer']['name']);
$this->obj->setOrganizer($organizer);
}
- if ($object['start'] instanceof DateTime) {
+ if ($object['start'] instanceof DateTimeInterface) {
$start_tz = $object['start']->getTimezone();
}
// save recurrence rule
$rr = new RecurrenceRule;
$rr->setFrequency(RecurrenceRule::FreqNone);
if ($object['recurrence'] && !empty($object['recurrence']['FREQ'])) {
$freq = $object['recurrence']['FREQ'];
$bysetpos = explode(',', $object['recurrence']['BYSETPOS']);
$rr->setFrequency($this->rrule_type_map[$freq]);
if ($object['recurrence']['INTERVAL'])
$rr->setInterval(intval($object['recurrence']['INTERVAL']));
if ($object['recurrence']['BYDAY']) {
$byday = new vectordaypos;
foreach (explode(',', $object['recurrence']['BYDAY']) as $day) {
$occurrence = 0;
if (preg_match('/^([\d-]+)([A-Z]+)$/', $day, $m)) {
$occurrence = intval($m[1]);
$day = $m[2];
}
if (isset($this->weekday_map[$day])) {
// @TODO: libkolabxml does not support BYSETPOS, neither we.
// However, we can convert most common cases to BYDAY
if (!$occurrence && $freq == 'MONTHLY' && !empty($bysetpos)) {
foreach ($bysetpos as $pos) {
$byday->push(new DayPos(intval($pos), $this->weekday_map[$day]));
}
}
else {
$byday->push(new DayPos($occurrence, $this->weekday_map[$day]));
}
}
}
$rr->setByday($byday);
}
if ($object['recurrence']['BYMONTHDAY']) {
$bymday = new vectori;
foreach (explode(',', $object['recurrence']['BYMONTHDAY']) as $day)
$bymday->push(intval($day));
$rr->setBymonthday($bymday);
}
if ($object['recurrence']['BYMONTH']) {
$bymonth = new vectori;
foreach (explode(',', $object['recurrence']['BYMONTH']) as $month)
$bymonth->push(intval($month));
$rr->setBymonth($bymonth);
}
if ($object['recurrence']['COUNT'])
$rr->setCount(intval($object['recurrence']['COUNT']));
else if ($object['recurrence']['UNTIL'])
$rr->setEnd(self::get_datetime($object['recurrence']['UNTIL'], null, true, $start_tz));
if ($rr->isValid()) {
// add exception dates (only if recurrence rule is valid)
$exdates = new vectordatetime;
foreach ((array)$object['recurrence']['EXDATE'] as $exdate)
$exdates->push(self::get_datetime($exdate, null, true, $start_tz));
$this->obj->setExceptionDates($exdates);
}
else {
rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Invalid event recurrence rule: " . json_encode($object['recurrence']),
), true);
}
}
$this->obj->setRecurrenceRule($rr);
// save recurrence dates (aka RDATE)
if (!empty($object['recurrence']['RDATE'])) {
$rdates = new vectordatetime;
foreach ((array)$object['recurrence']['RDATE'] as $rdate)
$rdates->push(self::get_datetime($rdate, null, true, $start_tz));
$this->obj->setRecurrenceDates($rdates);
}
// save alarm(s)
$valarms = new vectoralarm;
$valarm_hashes = array();
if ($object['valarms']) {
foreach ($object['valarms'] as $valarm) {
if (!array_key_exists($valarm['action'], $this->alarm_type_map)) {
continue; // skip unknown alarm types
}
// Get rid of duplicates, some CalDAV clients can set them
$hash = serialize($valarm);
if (in_array($hash, $valarm_hashes)) {
continue;
}
$valarm_hashes[] = $hash;
if ($valarm['action'] == 'EMAIL') {
$recipients = new vectorcontactref;
foreach (($valarm['attendees'] ?: array($object['_owner'])) as $email) {
$recipients->push(new ContactReference(ContactReference::EmailReference, $email));
}
$alarm = new Alarm(
strval($valarm['summary'] ?: $object['title']),
strval($valarm['description'] ?: $object['description']),
$recipients
);
}
else if ($valarm['action'] == 'AUDIO') {
$attach = new Attachment;
$attach->setUri($valarm['uri'] ?: 'null', 'unknown');
$alarm = new Alarm($attach);
}
else {
// action == DISPLAY
$alarm = new Alarm(strval($valarm['summary'] ?: $object['title']));
}
- if (is_object($valarm['trigger']) && $valarm['trigger'] instanceof DateTime) {
+ if (is_object($valarm['trigger']) && $valarm['trigger'] instanceof DateTimeInterface) {
$alarm->setStart(self::get_datetime($valarm['trigger'], new DateTimeZone('UTC')));
}
else if (preg_match('/^@([0-9]+)$/', $valarm['trigger'], $m)) {
$alarm->setStart(self::get_datetime($m[1], new DateTimeZone('UTC')));
}
else {
// Support also interval in format without PT, e.g. -10M
if (preg_match('/^([-+]*)([0-9]+[DHMS])$/', strtoupper($valarm['trigger']), $m)) {
$valarm['trigger'] = $m[1] . ($m[2][strlen($m[2])-1] == 'D' ? 'P' : 'PT') . $m[2];
}
try {
$period = new DateInterval(preg_replace('/[^0-9PTWDHMS]/', '', $valarm['trigger']));
$duration = new Duration($period->d, $period->h, $period->i, $period->s, $valarm['trigger'][0] == '-');
}
catch (Exception $e) {
// skip alarm with invalid trigger values
rcube::raise_error($e, true);
continue;
}
$related = strtoupper($valarm['related']) == 'END' ? kolabformat::End : kolabformat::Start;
$alarm->setRelativeStart($duration, $related);
}
if ($valarm['duration']) {
try {
$d = new DateInterval($valarm['duration']);
$duration = new Duration($d->d, $d->h, $d->i, $d->s);
$alarm->setDuration($duration, intval($valarm['repeat']));
}
catch (Exception $e) {
// ignore
}
}
$valarms->push($alarm);
}
}
// legacy support
else if ($object['alarms']) {
list($offset, $type) = explode(":", $object['alarms']);
if ($type == 'EMAIL' && !empty($object['_owner'])) { // email alarms implicitly go to event owner
$recipients = new vectorcontactref;
$recipients->push(new ContactReference(ContactReference::EmailReference, $object['_owner']));
$alarm = new Alarm($object['title'], strval($object['description']), $recipients);
}
else { // default: display alarm
$alarm = new Alarm($object['title']);
}
if (preg_match('/^@(\d+)/', $offset, $d)) {
$alarm->setStart(self::get_datetime($d[1], new DateTimeZone('UTC')));
}
else if (preg_match('/^([-+]?)P?T?(\d+)([SMHDW])/', $offset, $d)) {
$days = $hours = $minutes = $seconds = 0;
switch ($d[3]) {
case 'W': $days = 7*intval($d[2]); break;
case 'D': $days = intval($d[2]); break;
case 'H': $hours = intval($d[2]); break;
case 'M': $minutes = intval($d[2]); break;
case 'S': $seconds = intval($d[2]); break;
}
$alarm->setRelativeStart(new Duration($days, $hours, $minutes, $seconds, $d[1] == '-'), $d[1] == '-' ? kolabformat::Start : kolabformat::End);
}
$valarms->push($alarm);
}
$this->obj->setAlarms($valarms);
$this->set_attachments($object);
}
/**
* Return the reference date for recurrence and alarms
*
* @return mixed DateTime instance of null if no refdate is available
*/
public function get_reference_date()
{
- if ($this->data['start'] && $this->data['start'] instanceof DateTime) {
+ if ($this->data['start'] && $this->data['start'] instanceof DateTimeInterface) {
return $this->data['start'];
}
return self::php_datetime($this->obj->start());
}
/**
* 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($obj = null)
{
$data = '';
$object = $obj ?: $this->data;
foreach (self::$fulltext_cols as $colname) {
list($col, $field) = explode(':', $colname);
if ($field) {
$a = array();
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 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 = array();
$object = $obj ?: $this->data;
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);
}
/**
* Identify changes considered relevant for scheduling
*
* @param array Hash array with NEW object properties
* @param array Hash array with OLD object properties
*
* @return boolean True if changes affect scheduling, False otherwise
*/
public function check_rescheduling($object, $old = null)
{
$reschedule = false;
if (!is_array($old)) {
$old = $this->data['uid'] ? $this->data : $this->to_array();
}
foreach ($this->_scheduling_properties ?: self::$scheduling_properties as $prop) {
$a = $old[$prop];
$b = $object[$prop];
- if ($object['allday'] && ($prop == 'start' || $prop == 'end') && $a instanceof DateTime && $b instanceof DateTime) {
+
+ if ($object['allday']
+ && ($prop == 'start' || $prop == 'end')
+ && $a instanceof DateTimeInterface
+ && $b instanceof DateTimeInterface
+ ) {
$a = $a->format('Y-m-d');
$b = $b->format('Y-m-d');
}
if ($prop == 'recurrence' && is_array($a) && is_array($b)) {
unset($a['EXCEPTIONS'], $b['EXCEPTIONS']);
$a = array_filter($a);
$b = array_filter($b);
// advanced rrule comparison: no rescheduling if series was shortened
if ($a['COUNT'] && $b['COUNT'] && $b['COUNT'] < $a['COUNT']) {
unset($a['COUNT'], $b['COUNT']);
}
else if ($a['UNTIL'] && $b['UNTIL'] && $b['UNTIL'] < $a['UNTIL']) {
unset($a['UNTIL'], $b['UNTIL']);
}
}
if ($a != $b) {
$reschedule = true;
break;
}
}
return $reschedule;
}
/**
* Clones into an instance of libcalendaring's extended EventCal class
*
* @return mixed EventCal object or false on failure
*/
public function to_libcal()
{
static $error_logged = false;
if (class_exists('kolabcalendaring')) {
return new EventCal($this->obj);
}
else if (!$error_logged) {
$error_logged = true;
rcube::raise_error(array(
'code' => 900,
'message' => "Required kolabcalendaring module not found"
), true);
}
return false;
}
}
diff --git a/plugins/libkolab/lib/kolab_storage_cache.php b/plugins/libkolab/lib/kolab_storage_cache.php
index e9591484..ff5bd86e 100644
--- a/plugins/libkolab/lib/kolab_storage_cache.php
+++ b/plugins/libkolab/lib/kolab_storage_cache.php
@@ -1,1458 +1,1458 @@
<?php
/**
* Kolab storage cache class providing a local caching layer for Kolab groupware objects.
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@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_cache
{
const DB_DATE_FORMAT = 'Y-m-d H:i:s';
const MAX_RECORDS = 500;
protected $db;
protected $imap;
protected $folder;
protected $uid2msg;
protected $objects;
protected $metadata = array();
protected $folder_id;
protected $resource_uri;
protected $enabled = true;
protected $synched = false;
protected $synclock = false;
protected $ready = false;
protected $cache_table;
protected $folders_table;
protected $max_sql_packet;
protected $max_sync_lock_time = 600;
protected $extra_cols = array();
protected $data_props = array();
protected $order_by = null;
protected $limit = null;
protected $error = 0;
protected $server_timezone;
/**
* Factory constructor
*/
public static function factory(kolab_storage_folder $storage_folder)
{
$subclass = 'kolab_storage_cache_' . $storage_folder->type;
if (class_exists($subclass)) {
return new $subclass($storage_folder);
}
else {
rcube::raise_error(array(
'code' => 900,
'type' => 'php',
'message' => "No kolab_storage_cache class found for folder '$storage_folder->name' of type '$storage_folder->type'"
), true);
return new kolab_storage_cache($storage_folder);
}
}
/**
* Default constructor
*/
public function __construct(kolab_storage_folder $storage_folder = null)
{
$rcmail = rcube::get_instance();
$this->db = $rcmail->get_dbh();
$this->imap = $rcmail->get_storage();
$this->enabled = $rcmail->config->get('kolab_cache', false);
$this->folders_table = $this->db->table_name('kolab_folders');
$this->server_timezone = new DateTimeZone(date_default_timezone_get());
if ($this->enabled) {
// always read folder cache and lock state from DB master
$this->db->set_table_dsn('kolab_folders', 'w');
// remove sync-lock on script termination
$rcmail->add_shutdown_function(array($this, '_sync_unlock'));
}
if ($storage_folder)
$this->set_folder($storage_folder);
}
/**
* Direct access to cache by folder_id
* (only for internal use)
*/
public function select_by_id($folder_id)
{
$query = $this->db->query("SELECT * FROM `{$this->folders_table}` WHERE `folder_id` = ?", $folder_id);
if ($sql_arr = $this->db->fetch_assoc($query)) {
$this->metadata = $sql_arr;
$this->folder_id = $sql_arr['folder_id'];
$this->folder = new StdClass;
$this->folder->type = $sql_arr['type'];
$this->resource_uri = $sql_arr['resource'];
$this->cache_table = $this->db->table_name('kolab_cache_' . $sql_arr['type']);
$this->ready = true;
}
}
/**
* Connect cache with a storage folder
*
* @param kolab_storage_folder The storage folder instance to connect with
*/
public function set_folder(kolab_storage_folder $storage_folder)
{
$this->folder = $storage_folder;
if (empty($this->folder->name) || !$this->folder->valid) {
$this->ready = false;
return;
}
// compose fully qualified ressource uri for this instance
$this->resource_uri = $this->folder->get_resource_uri();
$this->cache_table = $this->db->table_name('kolab_cache_' . $this->folder->type);
$this->ready = $this->enabled && !empty($this->folder->type);
$this->folder_id = null;
}
/**
* Returns true if this cache supports query by type
*/
public function has_type_col()
{
return in_array('type', $this->extra_cols);
}
/**
* Getter for the numeric ID used in cache tables
*/
public function get_folder_id()
{
$this->_read_folder_data();
return $this->folder_id;
}
/**
* Returns code of last error
*
* @return int Error code
*/
public function get_error()
{
return $this->error;
}
/**
* Synchronize local cache data with remote
*/
public function synchronize()
{
// only sync once per request cycle
if ($this->synched)
return;
if (!$this->ready) {
// kolab cache is disabled, synchronize IMAP mailbox cache only
$this->imap_mode(true);
$this->imap->folder_sync($this->folder->name);
$this->imap_mode(false);
}
else {
$this->sync_start = time();
// read cached folder metadata
$this->_read_folder_data();
// Read folder data from IMAP
$ctag = $this->folder->get_ctag();
// Validate current ctag
list($uidvalidity, $highestmodseq, $uidnext) = explode('-', $ctag);
if (empty($uidvalidity) || empty($highestmodseq)) {
rcube::raise_error(array(
'code' => 900,
'message' => "Failed to sync the kolab cache (Invalid ctag)"
), true);
}
// check cache status ($this->metadata is set in _read_folder_data())
else if (
empty($this->metadata['ctag'])
|| empty($this->metadata['changed'])
|| $this->metadata['ctag'] !== $ctag
) {
// lock synchronization for this folder or wait if locked
$this->_sync_lock();
// Run a full-sync (initial sync or continue the aborted sync)
if (empty($this->metadata['changed']) || empty($this->metadata['ctag'])) {
$result = $this->synchronize_full();
}
// Synchronize only the changes since last sync
else {
$result = $this->synchronize_update($ctag);
}
// update ctag value (will be written to database in _sync_unlock())
if ($result) {
$this->metadata['ctag'] = $ctag;
$this->metadata['changed'] = date(self::DB_DATE_FORMAT, time());
}
// remove lock
$this->_sync_unlock();
}
}
$this->check_error();
$this->synched = time();
}
/**
* Perform full cache synchronization
*/
protected function synchronize_full()
{
// get effective time limit we have for synchronization (~70% of the execution time)
$time_limit = $this->_max_sync_lock_time() * 0.7;
if (time() - $this->sync_start > $time_limit) {
return false;
}
// disable messages cache if configured to do so
$this->imap_mode(true);
// synchronize IMAP mailbox cache, does nothing if messages cache is disabled
$this->imap->folder_sync($this->folder->name);
// compare IMAP index with object cache index
$imap_index = $this->imap->index($this->folder->name, null, null, true, true);
$this->imap_mode(false);
if ($imap_index->is_error()) {
rcube::raise_error(array(
'code' => 900,
'message' => "Failed to sync the kolab cache (SEARCH failed)"
), true);
return false;
}
// determine objects to fetch or to invalidate
$imap_index = $imap_index->get();
$del_index = array();
$old_index = $this->current_index($del_index);
// Fetch objects and store in DB
$result = $this->synchronize_fetch($imap_index, $old_index, $del_index);
if ($result) {
// Remove redundant entries from IMAP and cache
$rem_index = array_intersect($del_index, $imap_index);
$del_index = array_merge(array_unique($del_index), array_diff($old_index, $imap_index));
$this->synchronize_delete($rem_index, $del_index);
}
return $result;
}
/**
* Perform partial cache synchronization, based on QRESYNC
*/
protected function synchronize_update()
{
if (!$this->imap->get_capability('QRESYNC')) {
rcube::raise_error(array(
'code' => 900,
'message' => "Failed to sync the kolab cache (no QRESYNC capability)"
), true);
return $this->synchronize_full();
}
// Handle the previous ctag
list($uidvalidity, $highestmodseq, $uidnext) = explode('-', $this->metadata['ctag']);
if (empty($uidvalidity) || empty($highestmodseq)) {
rcube::raise_error(array(
'code' => 900,
'message' => "Failed to sync the kolab cache (Invalid old ctag)"
), true);
return false;
}
// Enable QRESYNC
$res = $this->imap->conn->enable('QRESYNC');
if ($res === false) {
rcube::raise_error(array(
'code' => 900,
'message' => "Failed to sync the kolab cache (failed to enable QRESYNC/CONDSTORE)"
), true);
return false;
}
$mbox_data = $this->imap->folder_data($this->folder->name);
if (empty($mbox_data)) {
rcube::raise_error(array(
'code' => 900,
'message' => "Failed to sync the kolab cache (failed to get folder state)"
), true);
return false;
}
// Check UIDVALIDITY
if ($uidvalidity != $mbox_data['UIDVALIDITY']) {
return $this->synchronize_full();
}
// QRESYNC not supported on specified mailbox
if (!empty($mbox_data['NOMODSEQ']) || empty($mbox_data['HIGHESTMODSEQ'])) {
rcube::raise_error(array(
'code' => 900,
'message' => "Failed to sync the kolab cache (QRESYNC not supported on the folder)"
), true);
return $this->synchronize_full();
}
// Get modified flags and vanished messages
// UID FETCH 1:* (FLAGS) (CHANGEDSINCE 0123456789 VANISHED)
$result = $this->imap->conn->fetch(
$this->folder->name, '1:*', true, array('FLAGS'), $highestmodseq, true
);
$removed = array();
$modified = array();
$existing = $this->current_index($removed);
if (!empty($result)) {
foreach ($result as $msg) {
$uid = $msg->uid;
// Message marked as deleted
if (!empty($msg->flags['DELETED'])) {
$removed[] = $uid;
continue;
}
// Flags changed or new
$modified[] = $uid;
}
}
$new = array_diff($modified, $existing, $removed);
$result = true;
if (!empty($new)) {
$result = $this->synchronize_fetch($new, $existing, $removed);
if (!$result) {
return false;
}
}
// VANISHED found?
$mbox_data = $this->imap->folder_data($this->folder->name);
// Removed vanished messages from the database
$vanished = (array) rcube_imap_generic::uncompressMessageSet($mbox_data['VANISHED']);
// Remove redundant entries from IMAP and DB
$vanished = array_merge($removed, array_intersect($vanished, $existing));
$this->synchronize_delete($removed, $vanished);
return $result;
}
/**
* Fetch objects from IMAP and save into the database
*/
protected function synchronize_fetch($new_index, &$old_index, &$del_index)
{
// get effective time limit we have for synchronization (~70% of the execution time)
$time_limit = $this->_max_sync_lock_time() * 0.7;
if (time() - $this->sync_start > $time_limit) {
return false;
}
$i = 0;
$aborted = false;
// fetch new objects from imap
foreach (array_diff($new_index, $old_index) as $msguid) {
// Note: We'll store only objects matching the folder type
// anything else will be silently ignored
if ($object = $this->folder->read_object($msguid)) {
// Deduplication: remove older objects with the same UID
// Here we do not resolve conflicts, we just make sure
// the most recent version of the object will be used
if ($old_msguid = $old_index[$object['uid']]) {
if ($old_msguid < $msguid) {
$del_index[] = $old_msguid;
}
else {
$del_index[] = $msguid;
continue;
}
}
$old_index[$object['uid']] = $msguid;
$this->_extended_insert($msguid, $object);
// check time limit and abort sync if running too long
if (++$i % 50 == 0 && time() - $this->sync_start > $time_limit) {
$aborted = true;
break;
}
}
}
$this->_extended_insert(0, null);
return $aborted === false;
}
/**
* Remove specified objects from the database and IMAP
*/
protected function synchronize_delete($imap_delete, $db_delete)
{
if (!empty($imap_delete)) {
$this->imap_mode(true);
$this->imap->delete_message($imap_delete, $this->folder->name);
$this->imap_mode(false);
}
if (!empty($db_delete)) {
$quoted_ids = join(',', array_map(array($this->db, 'quote'), $db_delete));
$this->db->query(
"DELETE FROM `{$this->cache_table}` WHERE `folder_id` = ? AND `msguid` IN ($quoted_ids)",
$this->folder_id
);
}
}
/**
* Return current use->msguid index
*/
protected function current_index(&$duplicates = array())
{
// read cache index
$sql_result = $this->db->query(
"SELECT `msguid`, `uid` FROM `{$this->cache_table}` WHERE `folder_id` = ?"
. " ORDER BY `msguid` DESC", $this->folder_id
);
$index = $del_index = array();
while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
// Mark all duplicates for removal (note sorting order above)
// Duplicates here should not happen, but they do sometimes
if (isset($index[$sql_arr['uid']])) {
$duplicates[] = $sql_arr['msguid'];
}
else {
$index[$sql_arr['uid']] = $sql_arr['msguid'];
}
}
return $index;
}
/**
* Read a single entry from cache or from IMAP directly
*
* @param string Related IMAP message UID
* @param string Object type to read
* @param string IMAP folder name the entry relates to
* @param array Hash array with object properties or null if not found
*/
public function get($msguid, $type = null, $foldername = null)
{
// delegate to another cache instance
if ($foldername && $foldername != $this->folder->name) {
$success = false;
if ($targetfolder = kolab_storage::get_folder($foldername)) {
$success = $targetfolder->cache->get($msguid, $type);
$this->error = $targetfolder->cache->get_error();
}
return $success;
}
// load object if not in memory
if (!isset($this->objects[$msguid])) {
if ($this->ready) {
$this->_read_folder_data();
$sql_result = $this->db->query(
"SELECT * FROM `{$this->cache_table}` ".
"WHERE `folder_id` = ? AND `msguid` = ?",
$this->folder_id,
$msguid
);
if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
$this->objects = array($msguid => $this->_unserialize($sql_arr)); // store only this object in memory (#2827)
}
}
// fetch from IMAP if not present in cache
if (empty($this->objects[$msguid])) {
if ($object = $this->folder->read_object($msguid, $type ?: '*', $foldername)) {
$this->objects = array($msguid => $object);
$this->set($msguid, $object);
}
}
}
$this->check_error();
return $this->objects[$msguid];
}
/**
* 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_by_uid($uid)
{
$old_order_by = $this->order_by;
$old_limit = $this->limit;
// set order to make sure we get most recent object version
// set limit to skip count query
$this->order_by = '`msguid` DESC';
$this->limit = array(1, 0);
$list = $this->select(array(array('uid', '=', $uid)));
// set the order/limit back to defined value
$this->order_by = $old_order_by;
$this->limit = $old_limit;
if (!empty($list) && !empty($list[0])) {
return $list[0];
}
}
/**
* Insert/Update a cache entry
*
* @param string Related IMAP message UID
* @param mixed Hash array with object properties to save or false to delete the cache entry
* @param string IMAP folder name the entry relates to
*/
public function set($msguid, $object, $foldername = null)
{
if (!$msguid) {
return;
}
// delegate to another cache instance
if ($foldername && $foldername != $this->folder->name) {
if ($targetfolder = kolab_storage::get_folder($foldername)) {
$targetfolder->cache->set($msguid, $object);
$this->error = $targetfolder->cache->get_error();
}
return;
}
// remove old entry
if ($this->ready) {
$this->_read_folder_data();
$this->db->query("DELETE FROM `{$this->cache_table}` WHERE `folder_id` = ? AND `msguid` = ?",
$this->folder_id, $msguid);
}
if ($object) {
// insert new object data...
$this->save($msguid, $object);
}
else {
// ...or set in-memory cache to false
$this->objects[$msguid] = $object;
}
$this->check_error();
}
/**
* Insert (or update) a cache entry
*
* @param int Related IMAP message UID
* @param mixed Hash array with object properties to save or false to delete the cache entry
* @param int Optional old message UID (for update)
*/
public function save($msguid, $object, $olduid = null)
{
// write to cache
if ($this->ready) {
$this->_read_folder_data();
$sql_data = $this->_serialize($object);
$sql_data['folder_id'] = $this->folder_id;
$sql_data['msguid'] = $msguid;
$sql_data['uid'] = $object['uid'];
$args = array();
$cols = array('folder_id', 'msguid', 'uid', 'changed', 'data', 'tags', 'words');
$cols = array_merge($cols, $this->extra_cols);
foreach ($cols as $idx => $col) {
$cols[$idx] = $this->db->quote_identifier($col);
$args[] = $sql_data[$col];
}
if ($olduid) {
foreach ($cols as $idx => $col) {
$cols[$idx] = "$col = ?";
}
$query = "UPDATE `{$this->cache_table}` SET " . implode(', ', $cols)
. " WHERE `folder_id` = ? AND `msguid` = ?";
$args[] = $this->folder_id;
$args[] = $olduid;
}
else {
$query = "INSERT INTO `{$this->cache_table}` (`created`, " . implode(', ', $cols)
. ") VALUES (" . $this->db->now() . str_repeat(', ?', count($cols)) . ")";
}
$result = $this->db->query($query, $args);
if (!$this->db->affected_rows($result)) {
rcube::raise_error(array(
'code' => 900, 'type' => 'php',
'message' => "Failed to write to kolab cache"
), true);
}
}
// keep a copy in memory for fast access
$this->objects = array($msguid => $object);
$this->uid2msg = array($object['uid'] => $msguid);
$this->check_error();
}
/**
* Move an existing cache entry to a new resource
*
* @param string Entry's IMAP message UID
* @param string Entry's Object UID
* @param kolab_storage_folder Target storage folder instance
* @param string Target entry's IMAP message UID
*/
public function move($msguid, $uid, $target, $new_msguid = null)
{
if ($this->ready && $target) {
// clear cached uid mapping and force new lookup
unset($target->cache->uid2msg[$uid]);
// resolve new message UID in target folder
if (!$new_msguid) {
$new_msguid = $target->cache->uid2msguid($uid);
}
if ($new_msguid) {
$this->_read_folder_data();
$this->db->query(
"UPDATE `{$this->cache_table}` SET `folder_id` = ?, `msguid` = ? ".
"WHERE `folder_id` = ? AND `msguid` = ?",
$target->cache->get_folder_id(),
$new_msguid,
$this->folder_id,
$msguid
);
$result = $this->db->affected_rows();
}
}
if (empty($result)) {
// just clear cache entry
$this->set($msguid, false);
}
unset($this->uid2msg[$uid]);
$this->check_error();
}
/**
* Remove all objects from local cache
*/
public function purge()
{
if (!$this->ready) {
return true;
}
$this->_read_folder_data();
$result = $this->db->query(
"DELETE FROM `{$this->cache_table}` WHERE `folder_id` = ?",
$this->folder_id
);
return $this->db->affected_rows($result);
}
/**
* Update resource URI for existing cache entries
*
* @param string Target IMAP folder to move it to
*/
public function rename($new_folder)
{
if (!$this->ready) {
return;
}
if ($target = kolab_storage::get_folder($new_folder)) {
// resolve new message UID in target folder
$this->db->query(
"UPDATE `{$this->folders_table}` SET `resource` = ? ".
"WHERE `resource` = ?",
$target->get_resource_uri(),
$this->resource_uri
);
$this->check_error();
}
else {
$this->error = kolab_storage::ERROR_IMAP_CONN;
}
}
/**
* Select Kolab objects filtered by the given query
*
* @param array Pseudo-SQL query as list of filter parameter triplets
* triplet: array('<colname>', '<comparator>', '<value>')
* @param boolean Set true to only return UIDs instead of complete objects
* @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) or UIDs
*/
public function select($query = array(), $uids = false, $fast = false)
{
$result = $uids ? array() : new kolab_storage_dataset($this);
// read from local cache DB (assume it to be synchronized)
if ($this->ready) {
$this->_read_folder_data();
// fetch full object data on one query if a small result set is expected
$fetchall = !$uids && ($this->limit ? $this->limit[0] : ($count = $this->count($query))) < self::MAX_RECORDS;
// skip SELECT if we know it will return nothing
if ($count === 0) {
return $result;
}
$sql_query = "SELECT " . ($fetchall ? '*' : "`msguid` AS `_msguid`, `uid`")
. " FROM `{$this->cache_table}` WHERE `folder_id` = ?"
. $this->_sql_where($query)
. (!empty($this->order_by) ? " ORDER BY " . $this->order_by : '');
$sql_result = $this->limit ?
$this->db->limitquery($sql_query, $this->limit[1], $this->limit[0], $this->folder_id) :
$this->db->query($sql_query, $this->folder_id);
if ($this->db->is_error($sql_result)) {
if ($uids) {
return null;
}
$result->set_error(true);
return $result;
}
while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
if ($fast) {
$sql_arr['fast-mode'] = true;
}
if ($uids) {
$this->uid2msg[$sql_arr['uid']] = $sql_arr['_msguid'];
$result[] = $sql_arr['uid'];
}
else if ($fetchall && ($object = $this->_unserialize($sql_arr))) {
$result[] = $object;
}
else if (!$fetchall) {
// only add msguid to dataset index
$result[] = $sql_arr;
}
}
}
// use IMAP
else {
$filter = $this->_query2assoc($query);
$this->imap_mode(true);
if ($filter['type']) {
$search = 'UNDELETED HEADER X-Kolab-Type ' . kolab_format::KTYPE_PREFIX . $filter['type'];
$index = $this->imap->search_once($this->folder->name, $search);
}
else {
$index = $this->imap->index($this->folder->name, null, null, true, true);
}
$this->imap_mode(false);
if ($index->is_error()) {
$this->check_error();
if ($uids) {
return null;
}
$result->set_error(true);
return $result;
}
$index = $index->get();
$result = $uids ? $index : $this->_fetch($index, $filter['type']);
// TODO: post-filter result according to query
}
// We don't want to cache big results in-memory, however
// if we select only one object here, there's a big chance we will need it later
if (!$uids && count($result) == 1) {
if ($msguid = $result[0]['_msguid']) {
$this->uid2msg[$result[0]['uid']] = $msguid;
$this->objects = array($msguid => $result[0]);
}
}
$this->check_error();
return $result;
}
/**
* Get number of objects mathing the given query
*
* @param array $query Pseudo-SQL query as list of filter parameter triplets
* @return integer The number of objects of the given type
*/
public function count($query = array())
{
// read from local cache DB (assume it to be synchronized)
if ($this->ready) {
$this->_read_folder_data();
$sql_result = $this->db->query(
"SELECT COUNT(*) AS `numrows` FROM `{$this->cache_table}` ".
"WHERE `folder_id` = ?" . $this->_sql_where($query),
$this->folder_id
);
if ($this->db->is_error($sql_result)) {
return null;
}
$sql_arr = $this->db->fetch_assoc($sql_result);
$count = intval($sql_arr['numrows']);
}
// use IMAP
else {
$filter = $this->_query2assoc($query);
$this->imap_mode(true);
if ($filter['type']) {
$search = 'UNDELETED HEADER X-Kolab-Type ' . kolab_format::KTYPE_PREFIX . $filter['type'];
$index = $this->imap->search_once($this->folder->name, $search);
}
else {
$index = $this->imap->index($this->folder->name, null, null, true, true);
}
$this->imap_mode(false);
if ($index->is_error()) {
$this->check_error();
return null;
}
// TODO: post-filter result according to query
$count = $index->count();
}
$this->check_error();
return $count;
}
/**
* Define ORDER BY clause for cache queries
*/
public function set_order_by($sortcols)
{
if (!empty($sortcols)) {
$sortcols = array_map(function($v) {
list($column, $order) = explode(' ', $v, 2);
return "`$column`" . ($order ? " $order" : '');
}, (array) $sortcols);
$this->order_by = join(', ', $sortcols);
}
else {
$this->order_by = null;
}
}
/**
* Define LIMIT clause for cache queries
*/
public function set_limit($length, $offset = 0)
{
$this->limit = array($length, $offset);
}
/**
* Helper method to compose a valid SQL query from pseudo filter triplets
*/
protected function _sql_where($query)
{
$sql_where = '';
foreach ((array) $query as $param) {
if (is_array($param[0])) {
$subq = array();
foreach ($param[0] as $q) {
$subq[] = preg_replace('/^\s*AND\s+/i', '', $this->_sql_where(array($q)));
}
if (!empty($subq)) {
$sql_where .= ' AND (' . implode($param[1] == 'OR' ? ' OR ' : ' AND ', $subq) . ')';
}
continue;
}
else if ($param[1] == '=' && is_array($param[2])) {
$qvalue = '(' . join(',', array_map(array($this->db, 'quote'), $param[2])) . ')';
$param[1] = 'IN';
}
else if ($param[1] == '~' || $param[1] == 'LIKE' || $param[1] == '!~' || $param[1] == '!LIKE') {
$not = ($param[1] == '!~' || $param[1] == '!LIKE') ? 'NOT ' : '';
$param[1] = $not . 'LIKE';
$qvalue = $this->db->quote('%'.preg_replace('/(^\^|\$$)/', ' ', $param[2]).'%');
}
else if ($param[1] == '~*' || $param[1] == '!~*') {
$not = $param[1][1] == '!' ? 'NOT ' : '';
$param[1] = $not . 'LIKE';
$qvalue = $this->db->quote(preg_replace('/(^\^|\$$)/', ' ', $param[2]).'%');
}
else if ($param[0] == 'tags') {
$param[1] = ($param[1] == '!=' ? 'NOT ' : '' ) . 'LIKE';
$qvalue = $this->db->quote('% '.$param[2].' %');
}
else {
$qvalue = $this->db->quote($param[2]);
}
$sql_where .= sprintf(' AND %s %s %s',
$this->db->quote_identifier($param[0]),
$param[1],
$qvalue
);
}
return $sql_where;
}
/**
* Helper method to convert the given pseudo-query triplets into
* an associative filter array with 'equals' values only
*/
protected function _query2assoc($query)
{
// extract object type from query parameter
$filter = array();
foreach ($query as $param) {
if ($param[1] == '=')
$filter[$param[0]] = $param[2];
}
return $filter;
}
/**
* Fetch messages from IMAP
*
* @param array List of message UIDs to fetch
* @param string Requested object type or * for all
* @param string IMAP folder to read from
* @return array List of parsed Kolab objects
*/
protected function _fetch($index, $type = null, $folder = null)
{
$results = new kolab_storage_dataset($this);
foreach ((array)$index as $msguid) {
if ($object = $this->folder->read_object($msguid, $type, $folder)) {
$results[] = $object;
$this->set($msguid, $object);
}
}
return $results;
}
/**
* Helper method to convert the given Kolab object into a dataset to be written to cache
*/
protected function _serialize($object)
{
$data = array();
$sql_data = array('changed' => null, 'tags' => '', 'words' => '');
if ($object['changed']) {
$sql_data['changed'] = date(self::DB_DATE_FORMAT, is_object($object['changed']) ? $object['changed']->format('U') : $object['changed']);
}
if ($object['_formatobj']) {
$xml = (string) $object['_formatobj']->write(3.0);
$data['_size'] = strlen($xml);
$sql_data['tags'] = ' ' . join(' ', $object['_formatobj']->get_tags()) . ' '; // pad with spaces for strict/prefix search
$sql_data['words'] = ' ' . join(' ', $object['_formatobj']->get_words()) . ' ';
}
// Store only minimal set of object properties
foreach ($this->data_props as $prop) {
if (isset($object[$prop])) {
$data[$prop] = $object[$prop];
- if ($data[$prop] instanceof DateTime) {
+ if ($data[$prop] instanceof DateTimeInterface) {
$data[$prop] = array(
'cl' => 'DateTime',
'dt' => $data[$prop]->format('Y-m-d H:i:s'),
'tz' => $data[$prop]->getTimezone()->getName(),
);
}
}
}
$sql_data['data'] = json_encode(rcube_charset::clean($data));
return $sql_data;
}
/**
* Helper method to turn stored cache data into a valid storage object
*/
protected function _unserialize($sql_arr)
{
if ($sql_arr['fast-mode'] && !empty($sql_arr['data']) && ($object = json_decode($sql_arr['data'], true))) {
$object['uid'] = $sql_arr['uid'];
foreach ($this->data_props as $prop) {
if (isset($object[$prop]) && is_array($object[$prop]) && $object[$prop]['cl'] == 'DateTime') {
$object[$prop] = new DateTime($object[$prop]['dt'], new DateTimeZone($object[$prop]['tz']));
}
else if (!isset($object[$prop]) && isset($sql_arr[$prop])) {
$object[$prop] = $sql_arr[$prop];
}
}
if ($sql_arr['created'] && empty($object['created'])) {
$object['created'] = new DateTime($sql_arr['created']);
}
if ($sql_arr['changed'] && empty($object['changed'])) {
$object['changed'] = new DateTime($sql_arr['changed']);
}
$object['_type'] = $sql_arr['type'] ?: $this->folder->type;
$object['_msguid'] = $sql_arr['msguid'];
$object['_mailbox'] = $this->folder->name;
}
// Fetch object xml
else {
// FIXME: Because old cache solution allowed storing objects that
// do not match folder type we may end up with invalid objects.
// 2nd argument of read_object() here makes sure they are still
// usable. However, not allowing them here might be also an intended
// solution in future.
$object = $this->folder->read_object($sql_arr['msguid'], '*');
}
return $object;
}
/**
* Write records into cache using extended inserts to reduce the number of queries to be executed
*
* @param int Message UID. Set 0 to commit buffered inserts
* @param array Kolab object to cache
*/
protected function _extended_insert($msguid, $object)
{
static $buffer = '';
$line = '';
$cols = array('folder_id', 'msguid', 'uid', 'created', 'changed', 'data', 'tags', 'words');
if ($this->extra_cols) {
$cols = array_merge($cols, $this->extra_cols);
}
if ($object) {
$sql_data = $this->_serialize($object);
// Skip multi-folder insert for all databases but MySQL
// In Oracle we can't put long data inline, others we don't support yet
if (strpos($this->db->db_provider, 'mysql') !== 0) {
$extra_args = array();
$params = array($this->folder_id, $msguid, $object['uid'], $sql_data['changed'],
$sql_data['data'], $sql_data['tags'], $sql_data['words']);
foreach ($this->extra_cols as $col) {
$params[] = $sql_data[$col];
$extra_args[] = '?';
}
$cols = implode(', ', array_map(function($n) { return "`{$n}`"; }, $cols));
$extra_args = count($extra_args) ? ', ' . implode(', ', $extra_args) : '';
$result = $this->db->query(
"INSERT INTO `{$this->cache_table}` ($cols)"
. " VALUES (?, ?, ?, " . $this->db->now() . ", ?, ?, ?, ?$extra_args)",
$params
);
if (!$this->db->affected_rows($result)) {
rcube::raise_error(array(
'code' => 900, 'message' => "Failed to write to kolab cache"
), true);
}
return;
}
$values = array(
$this->db->quote($this->folder_id),
$this->db->quote($msguid),
$this->db->quote($object['uid']),
$this->db->now(),
$this->db->quote($sql_data['changed']),
$this->db->quote($sql_data['data']),
$this->db->quote($sql_data['tags']),
$this->db->quote($sql_data['words']),
);
foreach ($this->extra_cols as $col) {
$values[] = $this->db->quote($sql_data[$col]);
}
$line = '(' . join(',', $values) . ')';
}
if ($buffer && (!$msguid || (strlen($buffer) + strlen($line) > $this->max_sql_packet()))) {
$columns = implode(', ', array_map(function($n) { return "`{$n}`"; }, $cols));
$update = implode(', ', array_map(function($i) { return "`{$i}` = VALUES(`{$i}`)"; }, array_slice($cols, 2)));
$result = $this->db->query(
"INSERT INTO `{$this->cache_table}` ($columns) VALUES $buffer"
. " ON DUPLICATE KEY UPDATE $update"
);
if (!$this->db->affected_rows($result)) {
rcube::raise_error(array(
'code' => 900, 'message' => "Failed to write to kolab cache"
), true);
}
$buffer = '';
}
$buffer .= ($buffer ? ',' : '') . $line;
}
/**
* Returns max_allowed_packet from mysql config
*/
protected function max_sql_packet()
{
if (!$this->max_sql_packet) {
// mysql limit or max 4 MB
$value = $this->db->get_variable('max_allowed_packet', 1048500);
$this->max_sql_packet = min($value, 4*1024*1024) - 2000;
}
return $this->max_sql_packet;
}
/**
* Read this folder's ID and cache metadata
*/
protected function _read_folder_data()
{
// already done
if (!empty($this->folder_id) || !$this->ready)
return;
$sql_arr = $this->db->fetch_assoc($this->db->query(
"SELECT `folder_id`, `synclock`, `ctag`, `changed`"
. " FROM `{$this->folders_table}` WHERE `resource` = ?",
$this->resource_uri
));
if ($sql_arr) {
$this->metadata = $sql_arr;
$this->folder_id = $sql_arr['folder_id'];
}
else {
$this->db->query("INSERT INTO `{$this->folders_table}` (`resource`, `type`)"
. " VALUES (?, ?)", $this->resource_uri, $this->folder->type);
$this->folder_id = $this->db->insert_id('kolab_folders');
$this->metadata = array();
}
}
/**
* Check lock record for this folder and wait if locked or set lock
*/
protected function _sync_lock()
{
if (!$this->ready)
return;
$this->_read_folder_data();
// abort if database is not set-up
if ($this->db->is_error()) {
$this->check_error();
$this->ready = false;
return;
}
$read_query = "SELECT `synclock`, `ctag` FROM `{$this->folders_table}` WHERE `folder_id` = ?";
$write_query = "UPDATE `{$this->folders_table}` SET `synclock` = ? WHERE `folder_id` = ? AND `synclock` = ?";
$max_lock_time = $this->_max_sync_lock_time();
// wait if locked (expire locks after 10 minutes) ...
// ... or if setting lock fails (another process meanwhile set it)
while (
(intval($this->metadata['synclock']) + $max_lock_time > time()) ||
(($res = $this->db->query($write_query, time(), $this->folder_id, intval($this->metadata['synclock']))) &&
!($affected = $this->db->affected_rows($res)))
) {
usleep(500000);
$this->metadata = $this->db->fetch_assoc($this->db->query($read_query, $this->folder_id));
}
$this->synclock = $affected > 0;
}
/**
* Remove lock for this folder
*/
public function _sync_unlock()
{
if (!$this->ready || !$this->synclock)
return;
$this->db->query(
"UPDATE `{$this->folders_table}` SET `synclock` = 0, `ctag` = ?, `changed` = ? WHERE `folder_id` = ?",
$this->metadata['ctag'],
$this->metadata['changed'],
$this->folder_id
);
$this->synclock = false;
}
protected function _max_sync_lock_time()
{
$limit = get_offset_sec(ini_get('max_execution_time'));
if ($limit <= 0 || $limit > $this->max_sync_lock_time) {
$limit = $this->max_sync_lock_time;
}
return $limit;
}
/**
* Check IMAP connection error state
*/
protected 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;
}
}
else if ($this->db->is_error()) {
$this->error = kolab_storage::ERROR_CACHE_DB;
}
}
/**
* Resolve an object UID into an IMAP message UID
*
* @param string Kolab object UID
* @param boolean Include deleted objects
* @return int The resolved IMAP message UID
*/
public function uid2msguid($uid, $deleted = false)
{
// query local database if available
if (!isset($this->uid2msg[$uid]) && $this->ready) {
$this->_read_folder_data();
$sql_result = $this->db->query(
"SELECT `msguid` FROM `{$this->cache_table}` ".
"WHERE `folder_id` = ? AND `uid` = ? ORDER BY `msguid` DESC",
$this->folder_id,
$uid
);
if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
$this->uid2msg[$uid] = $sql_arr['msguid'];
}
}
if (!isset($this->uid2msg[$uid])) {
// use IMAP SEARCH to get the right message
$index = $this->imap->search_once($this->folder->name, ($deleted ? '' : 'UNDELETED ') .
'HEADER SUBJECT ' . rcube_imap_generic::escape($uid));
$results = $index->get();
$this->uid2msg[$uid] = end($results);
}
return $this->uid2msg[$uid];
}
/**
* Getter for protected member variables
*/
public function __get($name)
{
if ($name == 'folder_id') {
$this->_read_folder_data();
}
return $this->$name;
}
/**
* Set Roundcube storage options and bypass messages/indexes cache.
*
* We use skip_deleted and threading settings specific to Kolab,
* we have to change these global settings only temporarily.
* Roundcube cache duplicates information already stored in kolab_cache,
* that's why we can disable it for better performance.
*
* @param bool $force True to start Kolab mode, False to stop it.
*/
public function imap_mode($force = false)
{
// remember current IMAP settings
if ($force) {
$this->imap_options = array(
'skip_deleted' => $this->imap->get_option('skip_deleted'),
'threading' => $this->imap->get_threading(),
);
}
// re-set IMAP settings
$this->imap->set_threading($force ? false : $this->imap_options['threading']);
$this->imap->set_options(array(
'skip_deleted' => $force ? true : $this->imap_options['skip_deleted'],
));
// if kolab cache is disabled do nothing
if (!$this->enabled) {
return;
}
static $messages_cache, $cache_bypass;
if ($messages_cache === null) {
$rcmail = rcube::get_instance();
$messages_cache = (bool) $rcmail->config->get('messages_cache');
$cache_bypass = (int) $rcmail->config->get('kolab_messages_cache_bypass');
}
if ($messages_cache) {
// handle recurrent (multilevel) bypass() calls
if ($force) {
$this->cache_bypassed += 1;
if ($this->cache_bypassed > 1) {
return;
}
}
else {
$this->cache_bypassed -= 1;
if ($this->cache_bypassed > 0) {
return;
}
}
switch ($cache_bypass) {
case 2:
// Disable messages and index cache completely
$this->imap->set_messages_caching(!$force);
break;
case 3:
case 1:
// We'll disable messages cache, but keep index cache (1) or vice-versa (3)
// Default mode is both (MODE_INDEX | MODE_MESSAGE)
$mode = $cache_bypass == 3 ? rcube_imap_cache::MODE_MESSAGE : rcube_imap_cache::MODE_INDEX;
if (!$force) {
$mode |= $cache_bypass == 3 ? rcube_imap_cache::MODE_INDEX : rcube_imap_cache::MODE_MESSAGE;
}
$this->imap->set_messages_caching(true, $mode);
}
}
}
/**
* Converts DateTime or unix timestamp into sql date format
* using server timezone.
*/
protected function _convert_datetime($datetime)
{
if (is_object($datetime)) {
$dt = clone $datetime;
$dt->setTimeZone($this->server_timezone);
return $dt->format(self::DB_DATE_FORMAT);
}
else if ($datetime) {
return date(self::DB_DATE_FORMAT, $datetime);
}
}
}
diff --git a/plugins/libkolab/lib/kolab_storage_dataset.php b/plugins/libkolab/lib/kolab_storage_dataset.php
index 97717e2a..5953805b 100644
--- a/plugins/libkolab/lib/kolab_storage_dataset.php
+++ b/plugins/libkolab/lib/kolab_storage_dataset.php
@@ -1,191 +1,192 @@
<?php
/**
* Dataset class providing the results of a select operation on a kolab_storage_folder.
*
* Can be used as a normal array as well as an iterator in foreach() loops.
*
* @version @package_version@
* @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 kolab_storage_dataset implements Iterator, ArrayAccess, Countable
{
const CHUNK_SIZE = 25;
private $cache; // kolab_storage_cache instance to use for fetching data
private $memlimit = 0;
private $buffer = false;
private $index = [];
private $data = [];
private $iteratorkey = 0;
private $error = null;
private $chunk = [];
/**
* Default constructor
*
* @param object kolab_storage_cache instance to be used for fetching objects upon access
*/
public function __construct($cache)
{
$this->cache = $cache;
// enable in-memory buffering up until 1/5 of the available memory
if (function_exists('memory_get_usage')) {
$this->memlimit = parse_bytes(ini_get('memory_limit')) / 5;
$this->buffer = true;
}
}
/**
* Return error state
*/
public function is_error()
{
return !empty($this->error);
}
/**
* Set error state
*/
public function set_error($err)
{
$this->error = $err;
}
/*** Implement PHP Countable interface ***/
- public function count()
+ public function count(): int
{
return count($this->index);
}
/*** Implement PHP ArrayAccess interface ***/
- public function offsetSet($offset, $value)
+ public function offsetSet($offset, $value): void
{
if (is_string($value)) {
$uid = $value;
}
else {
$uid = !empty($value['_msguid']) ? $value['_msguid'] : $value['uid'];
}
if (is_null($offset)) {
$offset = count($this->index);
}
$this->index[$offset] = $uid;
// keep full payload data in memory if possible
if ($this->memlimit && $this->buffer) {
$this->data[$offset] = $value;
// check memory usage and stop buffering
if ($offset % 10 == 0) {
$this->buffer = memory_get_usage() < $this->memlimit;
}
}
}
- public function offsetExists($offset)
+ public function offsetExists($offset): bool
{
return isset($this->index[$offset]);
}
- public function offsetUnset($offset)
+ public function offsetUnset($offset): void
{
unset($this->index[$offset]);
}
+ #[ReturnTypeWillChange]
public function offsetGet($offset)
{
if (isset($this->chunk[$offset])) {
return $this->chunk[$offset] ?: null;
}
// The item is a string (object's UID), use multiget method to pre-fetch
// multiple objects from the server in one request
if (isset($this->data[$offset]) && is_string($this->data[$offset]) && method_exists($this->cache, 'multiget')) {
$idx = $offset;
$uids = [];
while (isset($this->index[$idx]) && count($uids) < self::CHUNK_SIZE) {
if (isset($this->data[$idx]) && !is_string($this->data[$idx])) {
// skip objects that had the raw content in the cache (are not empty)
continue;
}
$uids[$idx] = $this->index[$idx];
$idx++;
}
if (!empty($uids)) {
$this->chunk = $this->cache->multiget($uids);
}
if (isset($this->chunk[$offset])) {
return $this->chunk[$offset] ?: null;
}
return null;
}
if (isset($this->data[$offset])) {
return $this->data[$offset];
}
if ($uid = $this->index[$offset]) {
return $this->cache->get($uid);
}
return null;
}
/*** Implement PHP Iterator interface ***/
+ #[ReturnTypeWillChange]
public function current()
{
return $this->offsetGet($this->iteratorkey);
}
- public function key()
+ public function key(): int
{
return $this->iteratorkey;
}
- public function next()
+ public function next(): void
{
$this->iteratorkey++;
- return $this->valid();
}
- public function rewind()
+ public function rewind(): void
{
$this->iteratorkey = 0;
}
- public function valid()
+ public function valid(): bool
{
return !empty($this->index[$this->iteratorkey]);
}
}
diff --git a/plugins/libkolab/lib/kolab_storage_dav_cache.php b/plugins/libkolab/lib/kolab_storage_dav_cache.php
index e22518f9..5dec0fa9 100644
--- a/plugins/libkolab/lib/kolab_storage_dav_cache.php
+++ b/plugins/libkolab/lib/kolab_storage_dav_cache.php
@@ -1,700 +1,700 @@
<?php
/**
* Kolab storage cache class providing a local caching layer for Kolab groupware objects.
*
* @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 kolab_storage_dav_cache extends kolab_storage_cache
{
/**
* Factory constructor
*/
public static function factory(kolab_storage_folder $storage_folder)
{
$subclass = 'kolab_storage_dav_cache_' . $storage_folder->type;
if (class_exists($subclass)) {
return new $subclass($storage_folder);
}
rcube::raise_error(
['code' => 900, 'message' => "No {$subclass} class found for folder '{$storage_folder->name}'"],
true
);
return new kolab_storage_dav_cache($storage_folder);
}
/**
* Connect cache with a storage folder
*
* @param kolab_storage_folder The storage folder instance to connect with
*/
public function set_folder(kolab_storage_folder $storage_folder)
{
$this->folder = $storage_folder;
if (!$this->folder->valid) {
$this->ready = false;
return;
}
// compose fully qualified ressource uri for this instance
$this->resource_uri = $this->folder->get_resource_uri();
$this->cache_table = $this->db->table_name('kolab_cache_dav_' . $this->folder->type);
$this->ready = true;
}
/**
* Synchronize local cache data with remote
*/
public function synchronize()
{
// only sync once per request cycle
if ($this->synched) {
return;
}
$this->sync_start = time();
// read cached folder metadata
$this->_read_folder_data();
$ctag = $this->folder->get_ctag();
// check cache status ($this->metadata is set in _read_folder_data())
if (
empty($this->metadata['ctag'])
|| empty($this->metadata['changed'])
|| $this->metadata['ctag'] !== $ctag
) {
// lock synchronization for this folder and wait if already locked
$this->_sync_lock();
$result = $this->synchronize_worker();
// update ctag value (will be written to database in _sync_unlock())
if ($result) {
$this->metadata['ctag'] = $ctag;
$this->metadata['changed'] = date(self::DB_DATE_FORMAT, time());
}
// remove lock
$this->_sync_unlock();
}
$this->synched = time();
}
/**
* Perform cache synchronization
*/
protected function synchronize_worker()
{
// get effective time limit we have for synchronization (~70% of the execution time)
$time_limit = $this->_max_sync_lock_time() * 0.7;
if (time() - $this->sync_start > $time_limit) {
return false;
}
// TODO: Implement synchronization with use of WebDAV-Sync (RFC 6578)
// Get the objects from the DAV server
$dav_index = $this->folder->dav->getIndex($this->folder->href, $this->folder->get_dav_type());
if (!is_array($dav_index)) {
rcube::raise_error([
'code' => 900,
'message' => "Failed to sync the kolab cache for {$this->folder->href}"
], true);
return false;
}
// WARNING: For now we assume object's href is <calendar-href>/<uid>.ics,
// which would mean there are no duplicates (objects with the same uid).
// With DAV protocol we can't get UID without fetching the whole object.
// Also the folder_id + uid is a unique index in the database.
// In the future we maybe should store the href in database.
// Determine objects to fetch or delete
$new_index = [];
$update_index = [];
$old_index = $this->folder_index(); // uid -> etag
$chunk_size = 20; // max numer of objects per DAV request
foreach ($dav_index as $object) {
$uid = $object['uid'];
if (isset($old_index[$uid])) {
$old_etag = $old_index[$uid];
$old_index[$uid] = null;
if ($old_etag === $object['etag']) {
// the object didn't change
continue;
}
$update_index[$uid] = $object['href'];
}
else {
$new_index[$uid] = $object['href'];
}
}
// Fetch new objects and store in DB
if (!empty($new_index)) {
foreach (array_chunk($new_index, $chunk_size, true) as $chunk) {
$objects = $this->folder->dav->getData($this->folder->href, $this->folder->get_dav_type(), $chunk);
if (!is_array($objects)) {
rcube::raise_error([
'code' => 900,
'message' => "Failed to sync the kolab cache for {$this->folder->href}"
], true);
return false;
}
foreach ($objects as $dav_object) {
if ($object = $this->folder->from_dav($dav_object)) {
$object['_raw'] = $dav_object['data'];
$this->_extended_insert(false, $object);
unset($object['_raw']);
}
}
$this->_extended_insert(true, null);
// check time limit and abort sync if running too long
if (++$i % 25 == 0 && time() - $this->sync_start > $time_limit) {
return false;
}
}
}
// Fetch updated objects and store in DB
if (!empty($update_index)) {
foreach (array_chunk($update_index, $chunk_size, true) as $chunk) {
$objects = $this->folder->dav->getData($this->folder->href, $this->folder->get_dav_type(), $chunk);
if (!is_array($objects)) {
rcube::raise_error([
'code' => 900,
'message' => "Failed to sync the kolab cache for {$this->folder->href}"
], true);
return false;
}
foreach ($objects as $dav_object) {
if ($object = $this->folder->from_dav($dav_object)) {
$object['_raw'] = $dav_object['data'];
$this->save($object, $object['uid']);
unset($object['_raw']);
}
}
// check time limit and abort sync if running too long
if (++$i % 25 == 0 && time() - $this->sync_start > $time_limit) {
return false;
}
}
}
// Remove deleted objects
$old_index = array_filter($old_index);
if (!empty($old_index)) {
$quoted_uids = join(',', array_map(array($this->db, 'quote'), $old_index));
$this->db->query(
"DELETE FROM `{$this->cache_table}` WHERE `folder_id` = ? AND `uid` IN ($quoted_uids)",
$this->folder_id
);
}
return true;
}
/**
* Return current folder index (uid -> etag)
*/
public function folder_index()
{
$this->_read_folder_data();
// read cache index
$sql_result = $this->db->query(
"SELECT `uid`, `etag` FROM `{$this->cache_table}` WHERE `folder_id` = ?",
$this->folder_id
);
$index = [];
while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
$index[$sql_arr['uid']] = $sql_arr['etag'];
}
return $index;
}
/**
* Read a single entry from cache or from server directly
*
* @param string Object UID
* @param string Object type to read
* @param string Unused (kept for compat. with the parent class)
*
* @return null|array An array of objects, NULL if not found
*/
public function get($uid, $type = null, $unused = null)
{
if ($this->ready) {
$this->_read_folder_data();
$sql_result = $this->db->query(
"SELECT * FROM `{$this->cache_table}` WHERE `folder_id` = ? AND `uid` = ?",
$this->folder_id,
$uid
);
if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
$object = $this->_unserialize($sql_arr);
}
}
// fetch from DAV if not present in cache
if (empty($object)) {
if ($object = $this->folder->read_object($uid, $type ?: '*')) {
$this->save($object);
}
}
return $object ?: null;
}
/**
* Read multiple entries from the server directly
*
* @param array Object UIDs
*
* @return false|array An array of objects, False on error
*/
public function multiget($uids)
{
return $this->folder->read_objects($uids);
}
/**
* Insert/Update a cache entry
*
* @param string Object UID
* @param array|false Hash array with object properties to save or false to delete the cache entry
* @param string Unused (kept for compat. with the parent class)
*/
public function set($uid, $object, $unused = null)
{
// remove old entry
if ($this->ready) {
$this->_read_folder_data();
$this->db->query(
"DELETE FROM `{$this->cache_table}` WHERE `folder_id` = ? AND `uid` = ?",
$this->folder_id,
$uid
);
}
if ($object) {
$this->save($object);
}
}
/**
* Insert (or update) a cache entry
*
* @param mixed Hash array with object properties to save or false to delete the cache entry
* @param string Optional old message UID (for update)
* @param string Unused (kept for compat. with the parent class)
*/
public function save($object, $olduid = null, $unused = null)
{
// write to cache
if ($this->ready) {
$this->_read_folder_data();
$sql_data = $this->_serialize($object);
$sql_data['folder_id'] = $this->folder_id;
$sql_data['uid'] = rcube_charset::clean($object['uid']);
$sql_data['etag'] = rcube_charset::clean($object['etag']);
$args = [];
$cols = ['folder_id', 'uid', 'etag', 'changed', 'data', 'tags', 'words'];
$cols = array_merge($cols, $this->extra_cols);
foreach ($cols as $idx => $col) {
$cols[$idx] = $this->db->quote_identifier($col);
$args[] = $sql_data[$col];
}
if ($olduid) {
foreach ($cols as $idx => $col) {
$cols[$idx] = "$col = ?";
}
$query = "UPDATE `{$this->cache_table}` SET " . implode(', ', $cols)
. " WHERE `folder_id` = ? AND `uid` = ?";
$args[] = $this->folder_id;
$args[] = $olduid;
}
else {
$query = "INSERT INTO `{$this->cache_table}` (`created`, " . implode(', ', $cols)
. ") VALUES (" . $this->db->now() . str_repeat(', ?', count($cols)) . ")";
}
$result = $this->db->query($query, $args);
if (!$this->db->affected_rows($result)) {
rcube::raise_error([
'code' => 900,
'message' => "Failed to write to kolab cache"
], true);
}
}
}
/**
* Move an existing cache entry to a new resource
*
* @param string Entry's UID
* @param kolab_storage_folder Target storage folder instance
* @param string Unused (kept for compat. with the parent class)
* @param string Unused (kept for compat. with the parent class)
*/
public function move($uid, $target, $unused1 = null, $unused2 = null)
{
// TODO
}
/**
* Update resource URI for existing folder
*
* @param string Target DAV folder to move it to
*/
public function rename($new_folder)
{
// TODO
}
/**
* Select Kolab objects filtered by the given query
*
* @param array Pseudo-SQL query as list of filter parameter triplets
* triplet: ['<colname>', '<comparator>', '<value>']
* @param bool Set true to only return UIDs instead of complete objects
* @param bool Use fast mode to fetch only minimal set of information
* (no xml fetching and parsing, etc.)
*
* @return array|null|kolab_storage_dataset List of Kolab data objects (each represented as hash array) or UIDs
*/
public function select($query = [], $uids = false, $fast = false)
{
$result = $uids ? [] : new kolab_storage_dataset($this);
$this->_read_folder_data();
// fetch full object data on one query if a small result set is expected
$fetchall = !$uids && ($this->limit ? $this->limit[0] : ($count = $this->count($query))) < self::MAX_RECORDS;
// skip SELECT if we know it will return nothing
if ($count === 0) {
return $result;
}
$sql_query = "SELECT " . ($fetchall ? '*' : "`uid`")
. " FROM `{$this->cache_table}` WHERE `folder_id` = ?"
. $this->_sql_where($query)
. (!empty($this->order_by) ? " ORDER BY " . $this->order_by : '');
$sql_result = $this->limit ?
$this->db->limitquery($sql_query, $this->limit[1], $this->limit[0], $this->folder_id) :
$this->db->query($sql_query, $this->folder_id);
if ($this->db->is_error($sql_result)) {
if ($uids) {
return null;
}
$result->set_error(true);
return $result;
}
while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
if ($uids) {
$result[] = $sql_arr['uid'];
}
else if (!$fetchall) {
$result[] = $sql_arr;
}
else if (($object = $this->_unserialize($sql_arr, true, $fast))) {
$result[] = $object;
}
else {
$result[] = $sql_arr['uid'];
}
}
return $result;
}
/**
* Get number of objects mathing the given query
*
* @param array $query Pseudo-SQL query as list of filter parameter triplets
*
* @return int The number of objects of the given type
*/
public function count($query = [])
{
// read from local cache DB (assume it to be synchronized)
$this->_read_folder_data();
$sql_result = $this->db->query(
"SELECT COUNT(*) AS `numrows` FROM `{$this->cache_table}` ".
"WHERE `folder_id` = ?" . $this->_sql_where($query),
$this->folder_id
);
if ($this->db->is_error($sql_result)) {
return null;
}
$sql_arr = $this->db->fetch_assoc($sql_result);
$count = intval($sql_arr['numrows']);
return $count;
}
/**
* Getter for a single Kolab object identified by its UID
*
* @param string $uid Object UID
*
* @return array|null The Kolab object represented as hash array
*/
public function get_by_uid($uid)
{
$old_limit = $this->limit;
// set limit to skip count query
$this->limit = [1, 0];
$list = $this->select([['uid', '=', $uid]]);
// set the limit back to defined value
$this->limit = $old_limit;
if (!empty($list) && !empty($list[0])) {
return $list[0];
}
}
/**
* Write records into cache using extended inserts to reduce the number of queries to be executed
*
* @param bool Set to false to commit buffered insert, true to force an insert
* @param array Kolab object to cache
*/
protected function _extended_insert($force, $object)
{
static $buffer = '';
$line = '';
$cols = ['folder_id', 'uid', 'etag', 'created', 'changed', 'data', 'tags', 'words'];
if ($this->extra_cols) {
$cols = array_merge($cols, $this->extra_cols);
}
if ($object) {
$sql_data = $this->_serialize($object);
// Skip multi-folder insert for all databases but MySQL
// In Oracle we can't put long data inline, others we don't support yet
if (strpos($this->db->db_provider, 'mysql') !== 0) {
$extra_args = [];
$params = [
$this->folder_id,
rcube_charset::clean($object['uid']),
rcube_charset::clean($object['etag']),
$sql_data['changed'],
$sql_data['data'],
$sql_data['tags'],
$sql_data['words']
];
foreach ($this->extra_cols as $col) {
$params[] = $sql_data[$col];
$extra_args[] = '?';
}
$cols = implode(', ', array_map(function($n) { return "`{$n}`"; }, $cols));
$extra_args = count($extra_args) ? ', ' . implode(', ', $extra_args) : '';
$result = $this->db->query(
"INSERT INTO `{$this->cache_table}` ($cols)"
. " VALUES (?, ?, " . $this->db->now() . ", ?, ?, ?, ?$extra_args)",
$params
);
if (!$this->db->affected_rows($result)) {
rcube::raise_error(array(
'code' => 900, 'message' => "Failed to write to kolab cache"
), true);
}
return;
}
$values = array(
$this->db->quote($this->folder_id),
$this->db->quote(rcube_charset::clean($object['uid'])),
$this->db->quote(rcube_charset::clean($object['etag'])),
$this->db->now(),
$this->db->quote($sql_data['changed']),
$this->db->quote($sql_data['data']),
$this->db->quote($sql_data['tags']),
$this->db->quote($sql_data['words']),
);
foreach ($this->extra_cols as $col) {
$values[] = $this->db->quote($sql_data[$col]);
}
$line = '(' . join(',', $values) . ')';
}
if ($buffer && ($force || (strlen($buffer) + strlen($line) > $this->max_sql_packet()))) {
$columns = implode(', ', array_map(function($n) { return "`{$n}`"; }, $cols));
$update = implode(', ', array_map(function($i) { return "`{$i}` = VALUES(`{$i}`)"; }, array_slice($cols, 2)));
$result = $this->db->query(
"INSERT INTO `{$this->cache_table}` ($columns) VALUES $buffer"
. " ON DUPLICATE KEY UPDATE $update"
);
if (!$this->db->affected_rows($result)) {
rcube::raise_error(array(
'code' => 900, 'message' => "Failed to write to kolab cache"
), true);
}
$buffer = '';
}
$buffer .= ($buffer ? ',' : '') . $line;
}
/**
* Helper method to convert the given Kolab object into a dataset to be written to cache
*/
protected function _serialize($object)
{
static $threshold;
if ($threshold === null) {
$rcube = rcube::get_instance();
$threshold = parse_bytes(rcube::get_instance()->config->get('dav_cache_threshold', 0));
}
$data = [];
$sql_data = ['changed' => null, 'tags' => '', 'words' => ''];
if (!empty($object['changed'])) {
$sql_data['changed'] = date(self::DB_DATE_FORMAT, is_object($object['changed']) ? $object['changed']->format('U') : $object['changed']);
}
// Store only minimal set of object properties
foreach ($this->data_props as $prop) {
if (isset($object[$prop])) {
$data[$prop] = $object[$prop];
- if ($data[$prop] instanceof DateTime) {
+ if ($data[$prop] instanceof DateTimeInterface) {
$data[$prop] = array(
'cl' => 'DateTime',
'dt' => $data[$prop]->format('Y-m-d H:i:s'),
'tz' => $data[$prop]->getTimezone()->getName(),
);
}
}
}
if (!empty($object['_raw']) && $threshold > 0 && strlen($object['_raw']) <= $threshold) {
$data['_raw'] = $object['_raw'];
}
$sql_data['data'] = json_encode(rcube_charset::clean($data));
return $sql_data;
}
/**
* Helper method to turn stored cache data into a valid storage object
*/
protected function _unserialize($sql_arr, $noread = false, $fast_mode = false)
{
- if (!empty($sql_arr['data'])) {
- if ($object = json_decode($sql_arr['data'], true)) {
- $object['_type'] = $sql_arr['type'] ?: $this->folder->type;
- $object['uid'] = $sql_arr['uid'];
- $object['etag'] = $sql_arr['etag'];
- }
- }
-
- if (!empty($fast_mode) && !empty($object)) {
+ if (!empty($sql_arr['data']) && ($object = json_decode($sql_arr['data'], true))) {
foreach ($this->data_props as $prop) {
- if (isset($object[$prop]) && is_array($object[$prop]) && $object[$prop]['cl'] == 'DateTime') {
+ if (isset($object[$prop]) && is_array($object[$prop])
+ && isset($object[$prop]['cl']) && $object[$prop]['cl'] == 'DateTime'
+ ) {
$object[$prop] = new DateTime($object[$prop]['dt'], new DateTimeZone($object[$prop]['tz']));
}
else if (!isset($object[$prop]) && isset($sql_arr[$prop])) {
$object[$prop] = $sql_arr[$prop];
}
}
if ($sql_arr['created'] && empty($object['created'])) {
$object['created'] = new DateTime($sql_arr['created']);
}
if ($sql_arr['changed'] && empty($object['changed'])) {
$object['changed'] = new DateTime($sql_arr['changed']);
}
+ $object['_type'] = !empty($sql_arr['type']) ? $sql_arr['type'] : $this->folder->type;
+ $object['uid'] = $sql_arr['uid'];
+ $object['etag'] = $sql_arr['etag'];
+ }
+
+ if (!empty($fast_mode) && !empty($object)) {
unset($object['_raw']);
}
else if ($noread) {
// We have the raw content already, parse it
if (!empty($object['_raw'])) {
$object['data'] = $object['_raw'];
if ($object = $this->folder->from_dav($object)) {
return $object;
}
}
return null;
}
else {
// Fetch a complete object from the server
$object = $this->folder->read_object($sql_arr['uid'], '*');
}
return $object;
}
}
diff --git a/plugins/libkolab/lib/kolab_storage_dav_folder.php b/plugins/libkolab/lib/kolab_storage_dav_folder.php
index e73a6882..8bf48c7f 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_annotation = '')
+ public function __construct($dav, $attributes, $type = '')
{
$this->attributes = $attributes;
$this->href = $this->attributes['href'];
- $this->id = md5($this->dav->url . '/' . $this->href);
+ $this->id = md5($dav->url . '/' . $this->href);
$this->dav = $dav;
$this->valid = true;
- list($this->type, $suffix) = explode('.', $type_annotation);
+ 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')) {
$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/libkolab.php b/plugins/libkolab/libkolab.php
index fad740f9..6c5e7a7a 100644
--- a/plugins/libkolab/libkolab.php
+++ b/plugins/libkolab/libkolab.php
@@ -1,388 +1,388 @@
<?php
/**
* Kolab core library
*
* Plugin to setup a basic environment for the interaction with a Kolab server.
* Other Kolab-related plugins will depend on it and can use the library classes
*
* @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 libkolab extends rcube_plugin
{
static $http_requests = array();
static $bonnie_api = false;
/**
* Required startup method of a Roundcube plugin
*/
public function init()
{
// load local config
$this->load_config();
// extend include path to load bundled lib classes
$include_path = $this->home . '/lib' . PATH_SEPARATOR . ini_get('include_path');
set_include_path($include_path);
$this->add_hook('storage_init', array($this, 'storage_init'));
$this->add_hook('storage_connect', array($this, 'storage_connect'));
$this->add_hook('user_delete', array('kolab_storage', 'delete_user_folders'));
// For Chwala
$this->add_hook('folder_mod', array('kolab_storage', 'folder_mod'));
$rcmail = rcube::get_instance();
try {
kolab_format::$timezone = new DateTimeZone($rcmail->config->get('timezone', 'GMT'));
}
catch (Exception $e) {
rcube::raise_error($e, true);
kolab_format::$timezone = new DateTimeZone('GMT');
}
$this->add_texts('localization/', false);
if (!empty($rcmail->output->type) && $rcmail->output->type == 'html') {
$rcmail->output->add_handler('libkolab.folder_search_form', array($this, 'folder_search_form'));
$this->include_stylesheet($this->local_skin_path() . '/libkolab.css');
}
// embed scripts and templates for email message audit trail
if ($rcmail->task == 'mail' && self::get_bonnie_api()) {
if ($rcmail->output->type == 'html') {
$this->add_hook('render_page', array($this, 'bonnie_render_page'));
$this->include_script('libkolab.js');
// add 'Show history' item to message menu
$this->api->add_content(html::tag('li', array('role' => 'menuitem'),
$this->api->output->button(array(
'command' => 'kolab-mail-history',
'label' => 'libkolab.showhistory',
'type' => 'link',
'classact' => 'icon history active',
'class' => 'icon history disabled',
'innerclass' => 'icon history',
))),
'messagemenu');
}
$this->register_action('plugin.message-changelog', array($this, 'message_changelog'));
}
}
/**
* Hook into IMAP FETCH HEADER.FIELDS command and request Kolab-specific headers
*/
function storage_init($p)
{
$kolab_headers = 'X-KOLAB-TYPE X-KOLAB-MIME-VERSION MESSAGE-ID';
if (!empty($p['fetch_headers'])) {
$p['fetch_headers'] .= ' ' . $kolab_headers;
}
else {
$p['fetch_headers'] = $kolab_headers;
}
return $p;
}
/**
* Hook into IMAP connection to replace client identity
*/
function storage_connect($p)
{
$client_name = 'Roundcube/Kolab';
if (empty($p['ident'])) {
$p['ident'] = array(
'name' => $client_name,
'version' => RCUBE_VERSION,
/*
'php' => PHP_VERSION,
'os' => PHP_OS,
'command' => $_SERVER['REQUEST_URI'],
*/
);
}
else {
$p['ident']['name'] = $client_name;
}
return $p;
}
/**
* Getter for a singleton instance of the Bonnie API
*
* @return mixed kolab_bonnie_api instance if configured, false otherwise
*/
public static function get_bonnie_api()
{
// get configuration for the Bonnie API
if (!self::$bonnie_api && ($bonnie_config = rcube::get_instance()->config->get('kolab_bonnie_api', false))) {
self::$bonnie_api = new kolab_bonnie_api($bonnie_config);
}
return self::$bonnie_api;
}
/**
* Hook to append the message history dialog template to the mail view
*/
function bonnie_render_page($p)
{
if (($p['template'] === 'mail' || $p['template'] === 'message') && !$p['kolab-audittrail']) {
// append a template for the audit trail dialog
$this->api->output->add_footer(
html::div(array('id' => 'mailmessagehistory', 'class' => 'uidialog', 'aria-hidden' => 'true', 'style' => 'display:none'),
self::object_changelog_table(array('class' => 'records-table changelog-table'))
)
);
$this->api->output->set_env('kolab_audit_trail', true);
$p['kolab-audittrail'] = true;
}
return $p;
}
/**
* Handler for message audit trail changelog requests
*/
public function message_changelog()
{
if (!self::$bonnie_api) {
return false;
}
$rcmail = rcube::get_instance();
$msguid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST, true);
$mailbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
$result = $msguid && $mailbox ? self::$bonnie_api->changelog('mail', null, $mailbox, $msguid) : null;
if (is_array($result)) {
if (is_array($result['changes'])) {
$dtformat = $rcmail->config->get('date_format') . ' ' . $rcmail->config->get('time_format');
array_walk($result['changes'], function(&$change) use ($dtformat, $rcmail) {
if ($change['date']) {
$dt = rcube_utils::anytodatetime($change['date']);
- if ($dt instanceof DateTime) {
+ if ($dt instanceof DateTimeInterface) {
$change['date'] = $rcmail->format_date($dt, $dtformat);
}
}
});
}
$this->api->output->command('plugin.message_render_changelog', $result['changes']);
}
else {
$this->api->output->command('plugin.message_render_changelog', false);
}
$this->api->output->send();
}
/**
* Wrapper function to load and initalize the HTTP_Request2 Object
*
* @param string|Net_Url2 Request URL
* @param string Request method ('OPTIONS','GET','HEAD','POST','PUT','DELETE','TRACE','CONNECT')
* @param array Configuration for this Request instance, that will be merged
* with default configuration
*
* @return HTTP_Request2 Request object
*/
public static function http_request($url = '', $method = 'GET', $config = array())
{
$rcube = rcube::get_instance();
$http_config = (array) $rcube->config->get('kolab_http_request');
// deprecated configuration options
if (empty($http_config)) {
foreach (array('ssl_verify_peer', 'ssl_verify_host') as $option) {
$value = $rcube->config->get('kolab_' . $option, true);
if (is_bool($value)) {
$http_config[$option] = $value;
}
}
}
if (!empty($config)) {
$http_config = array_merge($http_config, $config);
}
// force CURL adapter, this allows to handle correctly
// compressed responses with SplObserver registered (kolab_files) (#4507)
$http_config['adapter'] = 'HTTP_Request2_Adapter_Curl';
$key = md5(serialize($http_config));
if (!($request = self::$http_requests[$key])) {
// load HTTP_Request2 (support both composer-installed and system-installed package)
if (!class_exists('HTTP_Request2')) {
require_once 'HTTP/Request2.php';
}
try {
$request = new HTTP_Request2();
$request->setConfig($http_config);
}
catch (Exception $e) {
rcube::raise_error($e, true, true);
}
// proxy User-Agent string
$request->setHeader('user-agent', $_SERVER['HTTP_USER_AGENT']);
self::$http_requests[$key] = $request;
}
// cleanup
try {
$request->setBody('');
$request->setUrl($url);
$request->setMethod($method);
}
catch (Exception $e) {
rcube::raise_error($e, true, true);
}
return $request;
}
/**
* Table oultine for object changelog display
*/
public static function object_changelog_table($attrib = array())
{
$rcube = rcube::get_instance();
$attrib += array('domain' => 'libkolab');
$table = new html_table(array('cols' => 5, 'border' => 0, 'cellspacing' => 0));
$table->add_header('diff', '');
$table->add_header('revision', $rcube->gettext('revision', $attrib['domain']));
$table->add_header('date', $rcube->gettext('date', $attrib['domain']));
$table->add_header('user', $rcube->gettext('user', $attrib['domain']));
$table->add_header('operation', $rcube->gettext('operation', $attrib['domain']));
$table->add_header('actions', '&nbsp;');
$rcube->output->add_label(
'libkolab.showrevision',
'libkolab.actionreceive',
'libkolab.actionappend',
'libkolab.actionmove',
'libkolab.actiondelete',
'libkolab.actionread',
'libkolab.actionflagset',
'libkolab.actionflagclear',
'libkolab.objectchangelog',
'libkolab.objectchangelognotavailable',
'close'
);
return $table->show($attrib);
}
/**
* Wrapper function for generating a html diff using the FineDiff class by Raymond Hill
*/
public static function html_diff($from, $to, $is_html = null)
{
// auto-detect text/html format
if ($is_html === null) {
$from_html = (preg_match('/<(html|body)(\s+[a-z]|>)/', $from, $m) && strpos($from, '</'.$m[1].'>') > 0);
$to_html = (preg_match('/<(html|body)(\s+[a-z]|>)/', $to, $m) && strpos($to, '</'.$m[1].'>') > 0);
$is_html = $from_html || $to_html;
// ensure both parts are of the same format
if ($is_html && !$from_html) {
$converter = new rcube_text2html($from, false, array('wrap' => true));
$from = $converter->get_html();
}
if ($is_html && !$to_html) {
$converter = new rcube_text2html($to, false, array('wrap' => true));
$to = $converter->get_html();
}
}
// compute diff from HTML
if ($is_html) {
include_once __dir__ . '/vendor/Caxy/HtmlDiff/Match.php';
include_once __dir__ . '/vendor/Caxy/HtmlDiff/Operation.php';
include_once __dir__ . '/vendor/Caxy/HtmlDiff/HtmlDiff.php';
// replace data: urls with a transparent image to avoid memory problems
$from = preg_replace('/src="data:image[^"]+/', 'src="data:image/gif;base64,R0lGODlhAQABAPAAAOjq6gAAACH/C1hNUCBEYXRhWE1QAT8AIfkEBQAAAAAsAAAAAAEAAQAAAgJEAQA7', $from);
$to = preg_replace('/src="data:image[^"]+/', 'src="data:image/gif;base64,R0lGODlhAQABAPAAAOjq6gAAACH/C1hNUCBEYXRhWE1QAT8AIfkEBQAAAAAsAAAAAAEAAQAAAgJEAQA7', $to);
$diff = new Caxy\HtmlDiff\HtmlDiff($from, $to);
$diffhtml = $diff->build();
// remove empty inserts (from tables)
return preg_replace('!<ins class="diff\w+">\s*</ins>!Uims', '', $diffhtml);
}
else {
include_once __dir__ . '/vendor/finediff.php';
$diff = new FineDiff($from, $to, FineDiff::$wordGranularity);
return $diff->renderDiffToHTML();
}
}
/**
* 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 $event['allday'] ? 'Ymd' : 'Ymd\THis';
}
/**
* Returns HTML code for folder search widget
*
* @param array $attrib Named parameters
*
* @return string HTML code for the gui object
*/
public function folder_search_form($attrib)
{
$rcmail = rcube::get_instance();
$attrib += array(
'gui-object' => false,
'wrapper' => true,
'form-name' => 'foldersearchform',
'command' => 'non-extsing-command',
'reset-command' => 'non-existing-command',
);
if ($attrib['label-domain'] && !strpos($attrib['buttontitle'], '.')) {
$attrib['buttontitle'] = $attrib['label-domain'] . '.' . $attrib['buttontitle'];
}
if ($attrib['buttontitle']) {
$attrib['placeholder'] = $rcmail->gettext($attrib['buttontitle']);
}
return $rcmail->output->search_form($attrib);
}
}
diff --git a/plugins/libkolab/tests/kolab_date_recurrence.php b/plugins/libkolab/tests/KolabDateRecurrenceTest.php
similarity index 97%
rename from plugins/libkolab/tests/kolab_date_recurrence.php
rename to plugins/libkolab/tests/KolabDateRecurrenceTest.php
index ed3e3bd3..3c51aa19 100644
--- a/plugins/libkolab/tests/kolab_date_recurrence.php
+++ b/plugins/libkolab/tests/KolabDateRecurrenceTest.php
@@ -1,270 +1,270 @@
<?php
/**
* kolab_date_recurrence tests
*
* @author Aleksander Machniak <machniak@kolabsys.com>
*
* Copyright (C) 2017, 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_date_recurrence_test extends PHPUnit\Framework\TestCase
+class KolabDateRecurrenceTest extends PHPUnit\Framework\TestCase
{
- function setUp()
+ function setUp(): void
{
$rcube = rcmail::get_instance();
$rcube->plugins->load_plugin('libkolab', true, true);
}
/**
* kolab_date_recurrence::first_occurrence()
*
* @dataProvider data_first_occurrence
*/
function test_first_occurrence($recurrence_data, $start, $expected)
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$start = new DateTime($start);
if (!empty($recurrence_data['UNTIL'])) {
$recurrence_data['UNTIL'] = new DateTime($recurrence_data['UNTIL']);
}
$event = array('start' => $start, 'recurrence' => $recurrence_data);
$object = kolab_format::factory('event', 3.0);
$object->set($event);
$recurrence = new kolab_date_recurrence($object);
$first = $recurrence->first_occurrence();
$this->assertEquals($expected, $first ? $first->format('Y-m-d H:i:s') : '');
}
/**
* Data for test_first_occurrence()
*/
function data_first_occurrence()
{
// TODO: BYYEARDAY, BYWEEKNO, BYSETPOS, WKST
return array(
// non-recurring
array(
array(), // recurrence data
'2017-08-31 11:00:00', // start date
'2017-08-31 11:00:00', // expected result
),
// daily
array(
array('FREQ' => 'DAILY', 'INTERVAL' => '1'), // recurrence data
'2017-08-31 11:00:00', // start date
'2017-08-31 11:00:00', // expected result
),
// TODO: this one is not supported by the Calendar UI
array(
array('FREQ' => 'DAILY', 'INTERVAL' => '1', 'BYMONTH' => 1),
'2017-08-31 11:00:00',
'2018-01-01 11:00:00',
),
// weekly
array(
array('FREQ' => 'WEEKLY', 'INTERVAL' => '1'),
'2017-08-31 11:00:00', // Thursday
'2017-08-31 11:00:00',
),
array(
array('FREQ' => 'WEEKLY', 'INTERVAL' => '1', 'BYDAY' => 'WE'),
'2017-08-31 11:00:00', // Thursday
'2017-09-06 11:00:00',
),
array(
array('FREQ' => 'WEEKLY', 'INTERVAL' => '1', 'BYDAY' => 'TH'),
'2017-08-31 11:00:00', // Thursday
'2017-08-31 11:00:00',
),
array(
array('FREQ' => 'WEEKLY', 'INTERVAL' => '1', 'BYDAY' => 'FR'),
'2017-08-31 11:00:00', // Thursday
'2017-09-01 11:00:00',
),
array(
array('FREQ' => 'WEEKLY', 'INTERVAL' => '2'),
'2017-08-31 11:00:00', // Thursday
'2017-08-31 11:00:00',
),
array(
array('FREQ' => 'WEEKLY', 'INTERVAL' => '3', 'BYDAY' => 'WE'),
'2017-08-31 11:00:00', // Thursday
'2017-09-20 11:00:00',
),
array(
array('FREQ' => 'WEEKLY', 'INTERVAL' => '1', 'BYDAY' => 'WE', 'COUNT' => 1),
'2017-08-31 11:00:00', // Thursday
'2017-09-06 11:00:00',
),
array(
array('FREQ' => 'WEEKLY', 'INTERVAL' => '1', 'BYDAY' => 'WE', 'UNTIL' => '2017-09-01'),
'2017-08-31 11:00:00', // Thursday
'',
),
// monthly
array(
array('FREQ' => 'MONTHLY', 'INTERVAL' => '1'),
'2017-09-08 11:00:00',
'2017-09-08 11:00:00',
),
array(
array('FREQ' => 'MONTHLY', 'INTERVAL' => '1', 'BYMONTHDAY' => '8,9'),
'2017-08-31 11:00:00',
'2017-09-08 11:00:00',
),
array(
array('FREQ' => 'MONTHLY', 'INTERVAL' => '1', 'BYMONTHDAY' => '8,9'),
'2017-09-08 11:00:00',
'2017-09-08 11:00:00',
),
array(
array('FREQ' => 'MONTHLY', 'INTERVAL' => '1', 'BYDAY' => '1WE'),
'2017-08-16 11:00:00',
'2017-09-06 11:00:00',
),
array(
array('FREQ' => 'MONTHLY', 'INTERVAL' => '1', 'BYDAY' => '-1WE'),
'2017-08-16 11:00:00',
'2017-08-30 11:00:00',
),
array(
array('FREQ' => 'MONTHLY', 'INTERVAL' => '2'),
'2017-09-08 11:00:00',
'2017-09-08 11:00:00',
),
array(
array('FREQ' => 'MONTHLY', 'INTERVAL' => '2', 'BYMONTHDAY' => '8'),
'2017-08-31 11:00:00',
'2017-09-08 11:00:00', // ??????
),
// yearly
array(
array('FREQ' => 'YEARLY', 'INTERVAL' => '1'),
'2017-08-16 12:00:00',
'2017-08-16 12:00:00',
),
array(
array('FREQ' => 'YEARLY', 'INTERVAL' => '1', 'BYMONTH' => '8'),
'2017-08-16 12:00:00',
'2017-08-16 12:00:00',
),
array(
array('FREQ' => 'YEARLY', 'INTERVAL' => '1', 'BYDAY' => '-1MO'),
'2017-08-16 11:00:00',
'2017-12-25 11:00:00',
),
array(
array('FREQ' => 'YEARLY', 'INTERVAL' => '1', 'BYMONTH' => '8', 'BYDAY' => '-1MO'),
'2017-08-16 11:00:00',
'2017-08-28 11:00:00',
),
array(
array('FREQ' => 'YEARLY', 'INTERVAL' => '1', 'BYMONTH' => '1', 'BYDAY' => '1MO'),
'2017-08-16 11:00:00',
'2018-01-01 11:00:00',
),
array(
array('FREQ' => 'YEARLY', 'INTERVAL' => '1', 'BYMONTH' => '1,9', 'BYDAY' => '1MO'),
'2017-08-16 11:00:00',
'2017-09-04 11:00:00',
),
array(
array('FREQ' => 'YEARLY', 'INTERVAL' => '2'),
'2017-08-16 11:00:00',
'2017-08-16 11:00:00',
),
array(
array('FREQ' => 'YEARLY', 'INTERVAL' => '2', 'BYMONTH' => '8'),
'2017-08-16 11:00:00',
'2017-08-16 11:00:00',
),
array(
array('FREQ' => 'YEARLY', 'INTERVAL' => '2', 'BYDAY' => '-1MO'),
'2017-08-16 11:00:00',
'2017-12-25 11:00:00',
),
// on dates (FIXME: do we really expect the first occurrence to be on the start date?)
array(
array('RDATE' => array (new DateTime('2017-08-10 11:00:00 Europe/Warsaw'))),
'2017-08-01 11:00:00',
'2017-08-01 11:00:00',
),
);
}
/**
* kolab_date_recurrence::first_occurrence() for all-day events
*
* @dataProvider data_first_occurrence
*/
function test_first_occurrence_allday($recurrence_data, $start, $expected)
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$start = new DateTime($start);
if (!empty($recurrence_data['UNTIL'])) {
$recurrence_data['UNTIL'] = new DateTime($recurrence_data['UNTIL']);
}
$event = array('start' => $start, 'recurrence' => $recurrence_data, 'allday' => true);
$object = kolab_format::factory('event', 3.0);
$object->set($event);
$recurrence = new kolab_date_recurrence($object);
$first = $recurrence->first_occurrence();
$this->assertEquals($expected, $first ? $first->format('Y-m-d H:i:s') : '');
}
/**
* kolab_date_recurrence::next_instance()
*/
function test_next_instance()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
date_default_timezone_set('America/New_York');
$start = new DateTime('2017-08-31 11:00:00', new DateTimeZone('Europe/Berlin'));
- $event = array(
+ $event = [
'start' => $start,
- 'recurrence' => array('FREQ' => 'WEEKLY', 'INTERVAL' => '1'),
+ 'recurrence' => ['FREQ' => 'WEEKLY', 'INTERVAL' => '1'],
'allday' => true,
- );
+ ];
$object = kolab_format::factory('event', 3.0);
$object->set($event);
$recurrence = new kolab_date_recurrence($object);
$next = $recurrence->next_instance();
$this->assertEquals($start->format('2017-09-07 H:i:s'), $next['start']->format('Y-m-d H:i:s'), 'Same time');
$this->assertEquals($start->getTimezone()->getName(), $next['start']->getTimezone()->getName(), 'Same timezone');
- $this->assertSame($next['start']->_dateonly, true, '_dateonly flag');
+ $this->assertSame(true, $next['start']->_dateonly, '_dateonly flag');
}
}
diff --git a/plugins/libkolab/tests/kolab_storage_config.php b/plugins/libkolab/tests/KolabStorageConfigTest.php
similarity index 96%
rename from plugins/libkolab/tests/kolab_storage_config.php
rename to plugins/libkolab/tests/KolabStorageConfigTest.php
index d0c0ba3f..9305cefb 100644
--- a/plugins/libkolab/tests/kolab_storage_config.php
+++ b/plugins/libkolab/tests/KolabStorageConfigTest.php
@@ -1,238 +1,241 @@
<?php
-class kolab_storage_config_test extends PHPUnit\Framework\TestCase
+class KolabStorageConfigTest extends PHPUnit\Framework\TestCase
{
private $params_personal = array(
'folder' => 'Archive',
'uid' => '9',
'message-id' => '<1225270@example.org>',
'date' => 'Mon, 20 Apr 2015 15:30:30 UTC',
'subject' => 'Archived',
);
private $url_personal = 'imap:///user/$user/Archive/9?message-id=%3C1225270%40example.org%3E&date=Mon%2C+20+Apr+2015+15%3A30%3A30+UTC&subject=Archived';
private $params_shared = array(
'folder' => 'Shared Folders/shared/Collected',
'uid' => '4',
'message-id' => '<5270122@example.org>',
'date' => 'Mon, 20 Apr 2015 16:33:03 +0200',
'subject' => 'Shared',
);
private $url_shared = 'imap:///shared/Collected/4?message-id=%3C5270122%40example.org%3E&date=Mon%2C+20+Apr+2015+16%3A33%3A03+%2B0200&subject=Shared';
private $params_other = array(
'folder' => 'Other Users/lucy.white/Mailings',
'uid' => '378',
'message-id' => '<22448899@example.org>',
'date' => 'Tue, 14 Apr 2015 14:14:30 +0200',
'subject' => 'Happy Holidays',
);
private $url_other = 'imap:///user/lucy.white%40example.org/Mailings/378?message-id=%3C22448899%40example.org%3E&date=Tue%2C+14+Apr+2015+14%3A14%3A30+%2B0200&subject=Happy+Holidays';
- public static function setUpBeforeClass()
+ public static function setUpBeforeClass(): void
{
$rcube = rcmail::get_instance();
$rcube->plugins->load_plugin('libkolab', true, true);
if (!kolab_format::supports(3)) {
return;
}
+ // Unset mock'ed storage from the Roundcube core tests
+ $rcmail->storage = null;
+
if ($rcube->config->get('tests_username')) {
$authenticated = $rcube->login(
$rcube->config->get('tests_username'),
$rcube->config->get('tests_password'),
- $rcube->config->get('default_host'),
+ $rcube->config->get('imap_host', $rcube->config->get('default_host')),
false
);
if (!$authenticated) {
throw new Exception('IMAP login failed for user ' . $rcube->config->get('tests_username'));
}
// check for defult groupware folders and clear them
$imap = $rcube->get_storage();
$folders = $imap->list_folders('', '*');
foreach (array('Configuration') as $folder) {
if (in_array($folder, $folders)) {
if (!$imap->clear_folder($folder)) {
throw new Exception("Failed to clear folder '$folder'");
}
}
else {
throw new Exception("Default folder '$folder' doesn't exits in test user account");
}
}
}
else {
throw new Exception('Missing test account username/password in config-test.inc.php');
}
kolab_storage::setup();
}
function test_001_build_member_url()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$rcube = rcube::get_instance();
$email = $rcube->get_user_email();
$personal = str_replace('$user', urlencode($email), $this->url_personal);
// personal namespace
$url = kolab_storage_config::build_member_url($this->params_personal);
$this->assertEquals($personal, $url);
// shared namespace
$url = kolab_storage_config::build_member_url($this->params_shared);
$this->assertEquals($this->url_shared, $url);
// other users namespace
$url = kolab_storage_config::build_member_url($this->params_other);
$this->assertEquals($this->url_other, $url);
}
function test_002_parse_member_url()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$rcube = rcube::get_instance();
$email = $rcube->get_user_email();
$personal = str_replace('$user', urlencode($email), $this->url_personal);
// personal namespace
$params = kolab_storage_config::parse_member_url($personal);
$this->assertEquals($this->params_personal['uid'], $params['uid']);
$this->assertEquals($this->params_personal['folder'], $params['folder']);
$this->assertEquals($this->params_personal['subject'], $params['params']['subject']);
$this->assertEquals($this->params_personal['message-id'], $params['params']['message-id']);
// shared namespace
$params = kolab_storage_config::parse_member_url($this->url_shared);
$this->assertEquals($this->params_shared['uid'], $params['uid']);
$this->assertEquals($this->params_shared['folder'], $params['folder']);
// other users namespace
$params = kolab_storage_config::parse_member_url($this->url_other);
$this->assertEquals($this->params_other['uid'], $params['uid']);
$this->assertEquals($this->params_other['folder'], $params['folder']);
}
function test_003_build_parse_member_url()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
// personal namespace
$params = $this->params_personal;
$params_ = kolab_storage_config::parse_member_url(kolab_storage_config::build_member_url($params));
$this->assertEquals($params['uid'], $params_['uid']);
$this->assertEquals($params['folder'], $params_['folder']);
// shared namespace
$params = $this->params_shared;
$params_ = kolab_storage_config::parse_member_url(kolab_storage_config::build_member_url($params));
$this->assertEquals($params['uid'], $params_['uid']);
$this->assertEquals($params['folder'], $params_['folder']);
// other users namespace
$params = $this->params_other;
$params_ = kolab_storage_config::parse_member_url(kolab_storage_config::build_member_url($params));
$this->assertEquals($params['uid'], $params_['uid']);
$this->assertEquals($params['folder'], $params_['folder']);
}
/**
* Test relation/tag objects creation
* These objects will be used by following tests
*/
function test_save()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$config = kolab_storage_config::get_instance();
$tags = array(
array(
'category' => 'tag',
'name' => 'test1',
),
array(
'category' => 'tag',
'name' => 'test2',
),
array(
'category' => 'tag',
'name' => 'test3',
),
array(
'category' => 'tag',
'name' => 'test4',
),
);
foreach ($tags as $tag) {
$result = $config->save($tag, 'relation');
$this->assertTrue(!empty($result));
$this->assertTrue(!empty($tag['uid']));
}
}
/**
* Tests "race condition" in tags handling (T133)
*/
function test_T133()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$config = kolab_storage_config::get_instance();
// get tags
$tags = $config->get_tags();
$this->assertCount(4, $tags);
// create a tag
$tag = array(
'category' => 'tag',
'name' => 'new',
);
$result = $config->save($tag, 'relation');
$this->assertTrue(!empty($result));
// get tags again, make sure it contains the new tag
$tags = $config->get_tags();
$this->assertCount(5, $tags);
// update a tag
$tag['name'] = 'new-tag';
$result = $config->save($tag, 'relation');
$this->assertTrue(!empty($result));
// get tags again, make sure it contains the new tag
$tags = $config->get_tags();
$this->assertCount(5, $tags);
$this->assertSame('new-tag', $tags[4]['name']);
// remove a tag
$result = $config->delete($tag['uid']);
$this->assertTrue(!empty($result));
// get tags again, make sure it contains the new tag
$tags = $config->get_tags();
$this->assertCount(4, $tags);
foreach ($tags as $_tag) {
$this->assertTrue($_tag['uid'] != $tag['uid']);
}
}
}
diff --git a/plugins/libkolab/tests/kolab_storage_folder.php b/plugins/libkolab/tests/KolabStorageFolderTest.php
similarity index 96%
rename from plugins/libkolab/tests/kolab_storage_folder.php
rename to plugins/libkolab/tests/KolabStorageFolderTest.php
index c242b979..5b73968f 100644
--- a/plugins/libkolab/tests/kolab_storage_folder.php
+++ b/plugins/libkolab/tests/KolabStorageFolderTest.php
@@ -1,255 +1,258 @@
<?php
/**
* libkolab/kolab_storage_folder class tests
*
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 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_storage_folder_test extends PHPUnit\Framework\TestCase
+class KolabStorageFolderTest extends PHPUnit\Framework\TestCase
{
- public static function setUpBeforeClass()
+ public static function setUpBeforeClass(): void
{
// load libkolab plugin
$rcmail = rcmail::get_instance();
$rcmail->plugins->load_plugin('libkolab', true, true);
if (!kolab_format::supports(3)) {
return;
}
+ // Unset mock'ed storage from the Roundcube core tests
+ $rcmail->storage = null;
+
if ($rcmail->config->get('tests_username')) {
$authenticated = $rcmail->login(
$rcmail->config->get('tests_username'),
$rcmail->config->get('tests_password'),
- $rcmail->config->get('default_host'),
+ $rcmail->config->get('imap_host', $rcmail->config->get('default_host')),
false
);
if (!$authenticated) {
throw new Exception('IMAP login failed for user ' . $rcmail->config->get('tests_username'));
}
// check for defult groupware folders and clear them
$imap = $rcmail->get_storage();
$folders = $imap->list_folders('', '*');
foreach (array('Calendar','Contacts','Files','Tasks','Notes') as $folder) {
if (in_array($folder, $folders)) {
if (!$imap->clear_folder($folder)) {
throw new Exception("Failed to clear folder '$folder'");
}
}
else {
throw new Exception("Default folder '$folder' doesn't exits in test user account");
}
}
}
else {
throw new Exception('Missing test account username/password in config-test.inc.php');
}
kolab_storage::setup();
}
function test_001_folder_type_check()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$folder = new kolab_storage_folder('Calendar', 'event', 'event.default');
$this->assertTrue($folder->valid);
$this->assertEquals($folder->get_error(), 0);
$folder = new kolab_storage_folder('Calendar', 'event', 'mail');
$this->assertFalse($folder->valid);
$this->assertEquals($folder->get_error(), kolab_storage::ERROR_INVALID_FOLDER);
$folder = new kolab_storage_folder('INBOX');
$this->assertFalse($folder->valid);
$this->assertEquals($folder->get_error(), kolab_storage::ERROR_INVALID_FOLDER);
}
function test_002_get_owner()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$rcmail = rcmail::get_instance();
$folder = new kolab_storage_folder('Calendar', 'event', 'event');
$this->assertEquals($folder->get_owner(), $rcmail->config->get('tests_username'));
$domain = preg_replace('/^.+@/', '@', $rcmail->config->get('tests_username'));
$shared_ns = kolab_storage::namespace_root('shared');
$folder = new kolab_storage_folder($shared_ns . 'A-shared-folder', 'event', 'event');
$this->assertEquals($folder->get_owner(true), 'anonymous' . $domain);
$other_ns = kolab_storage::namespace_root('other');
$folder = new kolab_storage_folder($other_ns . 'major.tom/Calendar', 'event', 'event');
$this->assertEquals($folder->get_owner(true), 'major.tom' . $domain);
}
function test_003_get_resource_uri()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$rcmail = rcmail::get_instance();
$foldername = 'Calendar';
$uri = parse_url($rcmail->config->get('default_host'));
$hostname = $uri['host'];
$folder = new kolab_storage_folder($foldername, 'event', 'event.default');
$this->assertEquals($folder->get_resource_uri(), sprintf('imap://%s@%s/%s',
urlencode($rcmail->config->get('tests_username')),
$hostname,
$foldername
));
}
function test_004_get_uid()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$rcmail = rcmail::get_instance();
$folder = new kolab_storage_folder('Doesnt-Exist', 'event', 'event');
// generate UID from folder name if IMAP operations fail
$uid1 = $folder->get_uid();
$this->assertEquals($folder->get_uid(), $uid1);
$this->assertEquals($folder->get_error(), kolab_storage::ERROR_IMAP_CONN);
}
function test_005_subscribe()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$folder = new kolab_storage_folder('Contacts', 'contact');
$this->assertTrue($folder->subscribe(true));
$this->assertTrue($folder->is_subscribed());
$this->assertTrue($folder->subscribe(false));
$this->assertFalse($folder->is_subscribed());
$folder->subscribe(true);
}
function test_006_activate()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$folder = new kolab_storage_folder('Calendar', 'event');
$this->assertTrue($folder->activate(true));
$this->assertTrue($folder->is_active());
$this->assertTrue($folder->activate(false));
$this->assertFalse($folder->is_active());
}
function test_010_write_contacts()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$folder = new kolab_storage_folder('Contacts', 'contact');
$saved = $folder->save(null, 'contact');
$this->assertFalse($saved);
$contact = array(
'name' => 'FN',
'surname' => 'Last',
'firstname' => 'First',
'email' => array(
array('type' => 'home', 'address' => 'first.last@example.org'),
),
'organization' => 'Company A.G.'
);
$saved = $folder->save($contact, 'contact');
$this->assertTrue((bool)$saved);
}
/**
* @depends test_010_write_contacts
*/
function test_011_list_contacts()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$folder = new kolab_storage_folder('Contacts', 'contact');
$this->assertEquals($folder->count(), 1);
}
function test_T491_get_uid()
{
if (!kolab_format::supports(3)) {
$this->markTestSkipped('No Kolab support');
}
$rcmail = rcmail::get_instance();
$imap = $rcmail->get_storage();
$db = $rcmail->get_dbh();
// clear cache
//$imap->clear_cache('mailboxes.metadata', true);
// get folder UID
$folder = new kolab_storage_folder('Calendar', 'event', 'event');
$uid = $folder->get_uid();
// now get folder uniqueid annotations
$annotations = array(
'cyrus' => kolab_storage::UID_KEY_CYRUS,
'shared' => kolab_storage::UID_KEY_SHARED,
'private' => '/private/vendor/kolab/uniqueid',
);
foreach ($annotations as $key => $annotation) {
$meta = $imap->get_metadata('Calendar', $annotation);
$annotations[$key] = $meta['Calendar'][$annotation];
}
// compare results
if ($annotations['shared']) {
$this->assertSame($annotations['shared'], $uid);
}
else if ($annotations['cyrus']) {
$this->assertSame($annotations['cyrus'], $uid);
}
else {
// never use private namespace
$this->assertTrue($annotations['private'] != $uid);
}
// @TODO: check if the cache contains valid entries, not so simple with memcache
// as the cache key name is quite internal to the rcube_imap class.
}
}
diff --git a/plugins/libkolab/tests/README.md b/plugins/libkolab/tests/README.md
index 942822bf..d38d573d 100644
--- a/plugins/libkolab/tests/README.md
+++ b/plugins/libkolab/tests/README.md
@@ -1,43 +1,43 @@
libkolab plugin tests
=====================
In order to run the functional tests for libkolab classes, some configuration
for the Roundcube test instance need to be created. Along with the default
config for a given Roundcube instance, you should provide a config specifically
for running tests. To do so, create a config file named `config-test.inc.php`
in the regular Roundcube config dir. That should provide specific `db_dsnw` and
`default_host` values for testing purposes as well as the credentials of a
valid IMAP user account used for running the tests with.
Add these config options used by the libkolab tests:
```
// Unit tests settings
$config['tests_username'] = 'roundcube.test@example.org';
$config['tests_password'] = '<test-account-password>';
$config['default_host'] = '<kolab-server>';
// disable all plugins
- $config['plugins'] = array();
+ $config['plugins'] = [];
```
WARNING
-------
Please note that the configured IMAP account as well as the Roundcube database
configred in `db_dsnw` will be wiped and filled with test data in every test
run. Under no circumstances you should use credentials of a production database
or email account!
Run the tests
-------------
The tests are based on PHPUnit and need to be exected from the Roundcube
test directory in order to load and initialize the Roundcube framework context.
To execute individual tests, call `phpunit` from the tests directory:
```
cd <roundcube-dir>/tests/
phpunit ../plugins/libkolab/tests/<filename>
```
\ No newline at end of file

File Metadata

Mime Type
text/x-diff
Expires
Sat, Jan 18, 5:42 PM (6 h, 44 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
119982
Default Alt Text
(867 KB)

Event Timeline