diff --git a/plugins/calendar/calendar.php b/plugins/calendar/calendar.php index 5d2965ca..2c198f14 100644 --- a/plugins/calendar/calendar.php +++ b/plugins/calendar/calendar.php @@ -1,4047 +1,4045 @@ * @author Thomas Bruederli * * Copyright (C) 2010, Lazlo Westerhof * Copyright (C) 2014-2015, Kolab Systems AG * * 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 . */ 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',' — ')) . $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 = $("").attr({type: "text", name: "_categories[]", size: 30, "class": "form-control"}).val(name); var color = $("").attr({type: "text", name: "_colors[]", size: 6, "class": "colors form-control"}).val("000000"); var button = $("").attr({"class": "button icon delete input-group-text", title: button_label, href: "#rcmfd_new_category"}) .click(function() { $(this).parent().parent().remove(); }) .append($("").addClass("inner").text(rcmail.gettext("delete"))); $("
").addClass("input-group").append(input).append(color).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 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:///?_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 or tags return preg_match('/<(html|body)(\s+[a-z]|>)/', $event['description'], $m) && strpos($event['description'], '') > 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') . ' ' . $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); + // fallback to libcalendaring recurrence implementation + $recurrence = new libcalendaring_recurrence($this->lib, $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/drivers/calendar_driver.php b/plugins/calendar/drivers/calendar_driver.php index 082ed210..8bcd6903 100644 --- a/plugins/calendar/drivers/calendar_driver.php +++ b/plugins/calendar/drivers/calendar_driver.php @@ -1,863 +1,860 @@ * @author Thomas Bruederli * * Copyright (C) 2010, Lazlo Westerhof * Copyright (C) 2012-2015, Kolab Systems AG * * 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 . */ /** * 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(), 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']) || !($event['start'] instanceof DateTimeInterface)) { $valid = false; } if (empty($event['end']) || !is_object($event['end']) || !($event['end'] instanceof DateTimeInterface)) { $valid = false; } return $valid; } /** * Get list of event's attachments. * Drivers can return list of attachments as event property. * If they will do not do this list_attachments() method will be used. * * @param array $event Hash array with event properties: * id: Event identifier * calendar: Calendar identifier * * @return array List of attachments, each as hash array: * id: Attachment identifier * name: Attachment name * mimetype: MIME content type of the attachment * size: Attachment size */ public function list_attachments($event) { } /** * Get attachment properties * * @param string $id Attachment identifier * @param array $event Hash array with event properties: * id: Event identifier * calendar: Calendar identifier * * @return array Hash array with attachment properties: * id: Attachment identifier * name: Attachment name * mimetype: MIME content type of the attachment * size: Attachment size */ public function get_attachment($id, $event) { } /** * Get attachment body * * @param string $id Attachment identifier * @param array $event Hash array with event properties: * id: Event identifier * calendar: Calendar identifier * * @return string Attachment body */ public function get_attachment_body($id, $event) { } /** * Build a struct representing the given message reference * * @param object|string $uri_or_headers rcube_message_header instance holding the message headers * or an URI from a stored link referencing a mail message. * @param string $folder IMAP folder the message resides in * * @return array An struct referencing the given IMAP message */ public function get_message_reference($uri_or_headers, $folder = null) { // to be implemented by the derived classes return false; } /** * List availabale categories * The default implementation reads them from config/user prefs */ public function list_categories() { $rcmail = rcube::get_instance(); return $rcmail->config->get('calendar_categories', $this->default_categories); } /** * Create a new category */ public function add_category($name, $color) { } /** * Remove the given category */ public function remove_category($name) { } /** * Update/replace a category */ public function replace_category($oldname, $name, $color) { } /** * Fetch free/busy information from a person within the given range * * @param string $email E-mail address of attendee * @param int $start Requested period start date/time as unix timestamp * @param int $end Requested period end date/time as unix timestamp * * @return array List of busy timeslots within the requested range */ public function get_freebusy_list($email, $start, $end) { return false; } /** * Create instances of a recurring event * * @param array $event Hash array with event properties * @param DateTime $start Start date of the recurrence window * @param DateTime $end End date of the recurrence window * * @return array List of recurring event instances */ public function get_recurring_events($event, $start, $end = null) { $events = []; if (!empty($event['recurrence'])) { - // include library class - require_once(dirname(__FILE__) . '/../lib/calendar_recurrence.php'); - - $rcmail = rcmail::get_instance(); - $recurrence = new calendar_recurrence($rcmail->plugins->get_plugin('calendar'), $event); + $rcmail = rcmail::get_instance(); + $recurrence = new libcalendaring_recurrence($rcmail->plugins->get_plugin('calendar')->lib, $event); $recurrence_id_format = libcalendaring::recurrence_id_format($event); // determine a reasonable end date if none given if (!$end) { switch ($event['recurrence']['FREQ']) { case 'YEARLY': $intvl = 'P100Y'; break; case 'MONTHLY': $intvl = 'P20Y'; break; default: $intvl = 'P10Y'; break; } $end = clone $event['start']; $end->add(new DateInterval($intvl)); } $i = 0; while ($next_event = $recurrence->next_instance()) { // add to output if in range if (($next_event['start'] <= $end && $next_event['end'] >= $start)) { $next_event['_instance'] = $next_event['start']->format($recurrence_id_format); $next_event['id'] = $next_event['uid'] . '-' . $exception['_instance']; $next_event['recurrence_id'] = $event['uid']; $events[] = $next_event; } else if ($next_event['start'] > $end) { // stop loop if out of range break; } // avoid endless recursion loops if (++$i > 1000) { break; } } } return $events; } /** * Provide a list of revisions for the given event * * @param array $event Hash array with event properties: * id: Event identifier * calendar: Calendar identifier * * @return array List of changes, each as a hash array: * rev: Revision number * type: Type of the change (create, update, move, delete) * date: Change date * user: The user who executed the change * ip: Client IP * destination: Destination calendar for 'move' type */ public function get_event_changelog($event) { return false; } /** * Get a list of property changes beteen two revisions of an event * * @param array $event Hash array with event properties: * id: Event identifier * calendar: Calendar identifier * @param mixed $rev1 Old Revision * @param mixed $rev2 New Revision * * @return array List of property changes, each as a hash array: * property: Revision number * old: Old property value * new: Updated property value */ public function get_event_diff($event, $rev1, $rev2) { return false; } /** * Return full data of a specific revision of an event * * @param mixed $event UID string or hash array with event properties: * id: Event identifier * calendar: Calendar identifier * @param mixed $rev Revision number * * @return array Event object as hash array * @see self::get_event() */ public function get_event_revison($event, $rev) { return false; } /** * Command the backend to restore a certain revision of an event. * This shall replace the current event with an older version. * * @param mixed $event UID string or hash array with event properties: * id: Event identifier * calendar: Calendar identifier * @param mixed $rev Revision number * * @return boolean True on success, False on failure */ public function restore_event_revision($event, $rev) { return false; } /** * Callback function to produce driver-specific calendar create/edit form * * @param string $action Request action 'form-edit|form-new' * @param array $calendar Calendar properties (e.g. id, color) * @param array $formfields Edit form fields * * @return string HTML content of the form */ public function calendar_form($action, $calendar, $formfields) { $table = new html_table(['cols' => 2, 'class' => 'propform']); foreach ($formfields as $col => $colprop) { $label = !empty($colprop['label']) ? $colprop['label'] : $rcmail->gettext("$domain.$col"); $table->add('title', html::label($colprop['id'], rcube::Q($label))); $table->add(null, $colprop['value']); } return $table->show(); } /** * Compose a list of birthday events from the contact records in the user's address books. * * This is a default implementation using Roundcube's address book API. * It can be overriden with a more optimized version by the individual drivers. * * @param int $start Event's new start (unix timestamp) * @param int $end Event's new end (unix timestamp) * @param string $search Search query (optional) * @param int $modifiedsince Only list events modified since this time (unix timestamp) * * @return array A list of event records */ public function load_birthday_events($start, $end, $search = null, $modifiedsince = null) { // ignore update requests for simplicity reasons if (!empty($modifiedsince)) { return []; } // convert to DateTime for comparisons $start = new DateTime('@'.$start); $end = new DateTime('@'.$end); // extract the current year $year = $start->format('Y'); $year2 = $end->format('Y'); $events = []; $search = mb_strtolower($search); $rcmail = rcmail::get_instance(); $cache = $rcmail->get_cache('calendar.birthdays', 'db', 3600); $cache->expunge(); $alarm_type = $rcmail->config->get('calendar_birthdays_alarm_type', ''); $alarm_offset = $rcmail->config->get('calendar_birthdays_alarm_offset', '-1D'); $alarms = $alarm_type ? $alarm_offset . ':' . $alarm_type : null; // let the user select the address books to consider in prefs $selected_sources = $rcmail->config->get('calendar_birthday_adressbooks'); $sources = $selected_sources ?: array_keys($rcmail->get_address_sources(false, true)); foreach ($sources as $source) { $abook = $rcmail->get_address_book($source); // skip LDAP address books unless selected by the user if (!$abook || ($abook instanceof rcube_ldap && empty($selected_sources))) { continue; } // skip collected recipients/senders addressbooks if (is_a($abook, 'rcube_addresses')) { continue; } $abook->set_pagesize(10000); // check for cached results $cache_records = []; $cached = $cache->get($source); // iterate over (cached) contacts foreach (($cached ?: $abook->search('*', '', 2, true, true, ['birthday'])) as $contact) { $event = self::parse_contact($contact, $source); if (empty($event)) { continue; } // add stripped record to cache if (empty($cached)) { $cache_records[] = [ 'ID' => $contact['ID'], 'name' => $event['_displayname'], 'birthday' => $event['start']->format('Y-m-d'), ]; } // filter by search term (only name is involved here) if (!empty($search) && strpos(mb_strtolower($event['title']), $search) === false) { continue; } $bday = clone $event['start']; $byear = $bday->format('Y'); // quick-and-dirty recurrence computation: just replace the year $bday->setDate($year, $bday->format('n'), $bday->format('j')); $bday->setTime(12, 0, 0); $this_year = $year; // date range reaches over multiple years: use end year if not in range if (($bday > $end || $bday < $start) && $year2 != $year) { $bday->setDate($year2, $bday->format('n'), $bday->format('j')); $this_year = $year2; } // birthday is within requested range if ($bday <= $end && $bday >= $start) { unset($event['_displayname']); $event['alarms'] = $alarms; // if this is not the first occurence modify event details // but not when this is "all birthdays feed" request if ($year2 - $year < 10 && ($age = ($this_year - $byear))) { $label = ['name' => 'birthdayage', 'vars' => ['age' => $age]]; $event['description'] = $rcmail->gettext($label, 'calendar'); $event['start'] = $bday; $event['end'] = clone $bday; unset($event['recurrence']); } // add the main instance $events[] = $event; } } // store collected contacts in cache if (empty($cached)) { $cache->write($source, $cache_records); } } return $events; } /** * Get a single birthday calendar event */ public function get_birthday_event($id) { // decode $id list(, $source, $contact_id, $year) = explode(':', rcube_ldap::dn_decode($id)); $rcmail = rcmail::get_instance(); if (strlen($source) && $contact_id && ($abook = $rcmail->get_address_book($source))) { if ($contact = $abook->get_record($contact_id, true)) { return self::parse_contact($contact, $source); } } } /** * Parse contact and create an event for its birthday * * @param array $contact Contact data * @param string $source Addressbook source ID * * @return array|null Birthday event data */ public static function parse_contact($contact, $source) { if (!is_array($contact)) { return; } if (!empty($contact['birthday']) && is_array($contact['birthday'])) { $contact['birthday'] = reset($contact['birthday']); } if (empty($contact['birthday'])) { return; } try { $bday = $contact['birthday']; if (!$bday instanceof DateTimeInterface) { $bday = new DateTime($bday, new DateTimeZone('UTC')); } $bday->_dateonly = true; } catch (Exception $e) { rcube::raise_error([ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => 'BIRTHDAY PARSE ERROR: ' . $e->getMessage() ], true, false ); return; } $rcmail = rcmail::get_instance(); $birthyear = $bday->format('Y'); $display_name = rcube_addressbook::compose_display_name($contact); $label = ['name' => 'birthdayeventtitle', 'vars' => ['name' => $display_name]]; $event_title = $rcmail->gettext($label, 'calendar'); $uid = rcube_ldap::dn_encode('bday:' . $source . ':' . $contact['ID'] . ':' . $birthyear); return [ 'id' => $uid, 'uid' => $uid, 'calendar' => self::BIRTHDAY_CALENDAR_ID, 'title' => $event_title, 'description' => '', 'allday' => true, 'start' => $bday, 'end' => clone $bday, 'recurrence' => ['FREQ' => 'YEARLY', 'INTERVAL' => 1], 'free_busy' => 'free', '_displayname' => $display_name, ]; } /** * Store alarm dismissal for birtual birthay events * * @param string $event_id Event identifier * @param int $snooze Suspend the alarm for this number of seconds */ public function dismiss_birthday_alarm($event_id, $snooze = 0) { $rcmail = rcmail::get_instance(); $cache = $rcmail->get_cache('calendar.birthdayalarms', 'db', 86400 * 30); $cache->remove($event_id); // compute new notification time or disable if not snoozed $notifyat = $snooze > 0 ? time() + $snooze : null; $cache->set($event_id, ['snooze' => $snooze, 'notifyat' => $notifyat]); return true; } /** * Handler for user_delete plugin hook * * @param array $args Hash array with hook arguments * * @return array Return arguments for plugin hooks */ public function user_delete($args) { // TO BE OVERRIDDEN return $args; } } diff --git a/plugins/calendar/drivers/database/database_driver.php b/plugins/calendar/drivers/database/database_driver.php index e1ee1490..85b260ca 100644 --- a/plugins/calendar/drivers/database/database_driver.php +++ b/plugins/calendar/drivers/database/database_driver.php @@ -1,1531 +1,1528 @@ * @author Thomas Bruederli * * Copyright (C) 2010, Lazlo Westerhof * Copyright (C) 2012-2015, Kolab Systems AG * * 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 . */ 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 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); + $recurrence = new libcalendaring_recurrence($this->cal->lib, $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 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/lib/calendar_recurrence.php b/plugins/calendar/lib/calendar_recurrence.php deleted file mode 100644 index 4888fe18..00000000 --- a/plugins/calendar/lib/calendar_recurrence.php +++ /dev/null @@ -1,89 +0,0 @@ - - * - * Copyright (C) 2012-2014, Kolab Systems AG - * - * 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 . - */ -class calendar_recurrence extends libcalendaring_recurrence -{ - private $event; - private $duration; - - /** - * Default constructor - * - * @param calendar $cal The calendar plugin instance - * @param array $event The event object to operate on - */ - function __construct($cal, $event) - { - parent::__construct($cal->lib); - - $this->event = $event; - - if (is_object($event['start']) && is_object($event['end'])) { - $this->duration = $event['start']->diff($event['end']); - } - - $event['start']->_dateonly = !empty($event['allday']); - - $this->init($event['recurrence'], $event['start']); - } - - /** - * Alias of libcalendaring_recurrence::next() - * - * @return mixed DateTime object or False if recurrence ended - */ - public function next_start() - { - return $this->next(); - } - - /** - * 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()) { - $next = $this->event; - $next['start'] = $next_start; - - if ($this->duration) { - $next['end'] = clone $next_start; - $next['end']->add($this->duration); - } - - $next['recurrence_date'] = clone $next_start; - $next['_instance'] = libcalendaring::recurrence_instance_identifier($next, $this->event['allday']); - - unset($next['_formatobj']); - - return $next; - } - - return false; - } -} diff --git a/plugins/libcalendaring/lib/Horde_Date.php b/plugins/libcalendaring/lib/Horde_Date.php deleted file mode 100644 index faa71ffa..00000000 --- a/plugins/libcalendaring/lib/Horde_Date.php +++ /dev/null @@ -1,1304 +0,0 @@ - self::MASK_YEAR, - 'month' => self::MASK_MONTH, - 'mday' => self::MASK_DAY, - 'hour' => self::MASK_HOUR, - 'min' => self::MASK_MINUTE, - 'sec' => self::MASK_SECOND, - ); - - protected $_formatCache = array(); - - /** - * Builds a new date object. If $date contains date parts, use them to - * initialize the object. - * - * Recognized formats: - * - arrays with keys 'year', 'month', 'mday', 'day' - * 'hour', 'min', 'minute', 'sec' - * - objects with properties 'year', 'month', 'mday', 'hour', 'min', 'sec' - * - yyyy-mm-dd hh:mm:ss - * - yyyymmddhhmmss - * - yyyymmddThhmmssZ - * - yyyymmdd (might conflict with unix timestamps between 31 Oct 1966 and - * 03 Mar 1973) - * - unix timestamps - * - anything parsed by strtotime()/DateTime. - * - * @throws Horde_Date_Exception - */ - public function __construct($date = null, $timezone = null) - { - if (!self::$_supportedSpecs) { - self::$_supportedSpecs = self::$_defaultSpecs; - if (function_exists('nl_langinfo')) { - self::$_supportedSpecs .= 'bBpxX'; - } - } - - if (func_num_args() > 2) { - // Handle args in order: year month day hour min sec tz - $this->_initializeFromArgs(func_get_args()); - return; - } - - $this->_initializeTimezone($timezone); - - if (is_null($date)) { - return; - } - - if (is_string($date)) { - $date = trim($date, '"'); - } - - if (is_object($date)) { - $this->_initializeFromObject($date); - } elseif (is_array($date)) { - $this->_initializeFromArray($date); - } elseif (preg_match('/^(\d{4})-?(\d{2})-?(\d{2})T? ?(\d{2}):?(\d{2}):?(\d{2})(?:\.\d+)?(Z?)$/', $date, $parts)) { - $this->_year = (int)$parts[1]; - $this->_month = (int)$parts[2]; - $this->_mday = (int)$parts[3]; - $this->_hour = (int)$parts[4]; - $this->_min = (int)$parts[5]; - $this->_sec = (int)$parts[6]; - if ($parts[7]) { - $this->_initializeTimezone('UTC'); - } - } elseif (preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $date, $parts) && - $parts[2] > 0 && $parts[2] <= 12 && - $parts[3] > 0 && $parts[3] <= 31) { - $this->_year = (int)$parts[1]; - $this->_month = (int)$parts[2]; - $this->_mday = (int)$parts[3]; - $this->_hour = $this->_min = $this->_sec = 0; - } elseif ((string)(int)$date == $date) { - // Try as a timestamp. - $parts = @getdate($date); - if ($parts) { - $this->_year = $parts['year']; - $this->_month = $parts['mon']; - $this->_mday = $parts['mday']; - $this->_hour = $parts['hours']; - $this->_min = $parts['minutes']; - $this->_sec = $parts['seconds']; - } - } else { - // Use date_create() so we can catch errors with PHP 5.2. Use - // "new DateTime() once we require 5.3. - $parsed = date_create($date); - if (!$parsed) { - throw new Horde_Date_Exception(sprintf(Horde_Date_Translation::t("Failed to parse time string (%s)"), $date)); - } - $parsed->setTimezone(new DateTimeZone(date_default_timezone_get())); - $this->_year = (int)$parsed->format('Y'); - $this->_month = (int)$parsed->format('m'); - $this->_mday = (int)$parsed->format('d'); - $this->_hour = (int)$parsed->format('H'); - $this->_min = (int)$parsed->format('i'); - $this->_sec = (int)$parsed->format('s'); - $this->_initializeTimezone(date_default_timezone_get()); - } - } - - /** - * Returns a simple string representation of the date object - * - * @return string This object converted to a string. - */ - public function __toString() - { - try { - return $this->format($this->_defaultFormat); - } catch (Exception $e) { - return ''; - } - } - - /** - * Returns a DateTime object representing this object. - * - * @return DateTime - */ - public function toDateTime() - { - $date = new DateTime('now', new DateTimeZone($this->_timezone)); - $date->setDate($this->_year, $this->_month, $this->_mday); - $date->setTime($this->_hour, $this->_min, $this->_sec); - return $date; - } - - /** - * Converts a date in the proleptic Gregorian calendar to the no of days - * since 24th November, 4714 B.C. - * - * Returns the no of days since Monday, 24th November, 4714 B.C. in the - * proleptic Gregorian calendar (which is 24th November, -4713 using - * 'Astronomical' year numbering, and 1st January, 4713 B.C. in the - * proleptic Julian calendar). This is also the first day of the 'Julian - * Period' proposed by Joseph Scaliger in 1583, and the number of days - * since this date is known as the 'Julian Day'. (It is not directly - * to do with the Julian calendar, although this is where the name - * is derived from.) - * - * The algorithm is valid for all years (positive and negative), and - * also for years preceding 4714 B.C. - * - * Algorithm is from PEAR::Date_Calc - * - * @author Monte Ohrt - * @author Pierre-Alain Joye - * @author Daniel Convissor - * @author C.A. Woodcock - * - * @return integer The number of days since 24th November, 4714 B.C. - */ - public function toDays() - { - if (function_exists('GregorianToJD')) { - return gregoriantojd($this->_month, $this->_mday, $this->_year); - } - - $day = $this->_mday; - $month = $this->_month; - $year = $this->_year; - - if ($month > 2) { - // March = 0, April = 1, ..., December = 9, - // January = 10, February = 11 - $month -= 3; - } else { - $month += 9; - --$year; - } - - $hb_negativeyear = $year < 0; - $century = intval($year / 100); - $year = $year % 100; - - if ($hb_negativeyear) { - // Subtract 1 because year 0 is a leap year; - // And N.B. that we must treat the leap years as occurring - // one year earlier than they do, because for the purposes - // of calculation, the year starts on 1st March: - // - return intval((14609700 * $century + ($year == 0 ? 1 : 0)) / 400) + - intval((1461 * $year + 1) / 4) + - intval((153 * $month + 2) / 5) + - $day + 1721118; - } else { - return intval(146097 * $century / 4) + - intval(1461 * $year / 4) + - intval((153 * $month + 2) / 5) + - $day + 1721119; - } - } - - /** - * Converts number of days since 24th November, 4714 B.C. (in the proleptic - * Gregorian calendar, which is year -4713 using 'Astronomical' year - * numbering) to Gregorian calendar date. - * - * Returned date belongs to the proleptic Gregorian calendar, using - * 'Astronomical' year numbering. - * - * The algorithm is valid for all years (positive and negative), and - * also for years preceding 4714 B.C. (i.e. for negative 'Julian Days'), - * and so the only limitation is platform-dependent (for 32-bit systems - * the maximum year would be something like about 1,465,190 A.D.). - * - * N.B. Monday, 24th November, 4714 B.C. is Julian Day '0'. - * - * Algorithm is from PEAR::Date_Calc - * - * @author Monte Ohrt - * @author Pierre-Alain Joye - * @author Daniel Convissor - * @author C.A. Woodcock - * - * @param int $days the number of days since 24th November, 4714 B.C. - * @param string $format the string indicating how to format the output - * - * @return Horde_Date A Horde_Date object representing the date. - */ - public static function fromDays($days) - { - if (function_exists('jdtogregorian')) { - list($month, $day, $year) = explode('/', jdtogregorian($days)); - } else { - $days = intval($days); - - $days -= 1721119; - $century = floor((4 * $days - 1) / 146097); - $days = floor(4 * $days - 1 - 146097 * $century); - $day = floor($days / 4); - - $year = floor((4 * $day + 3) / 1461); - $day = floor(4 * $day + 3 - 1461 * $year); - $day = floor(($day + 4) / 4); - - $month = floor((5 * $day - 3) / 153); - $day = floor(5 * $day - 3 - 153 * $month); - $day = floor(($day + 5) / 5); - - $year = $century * 100 + $year; - if ($month < 10) { - $month +=3; - } else { - $month -=9; - ++$year; - } - } - - return new Horde_Date($year, $month, $day); - } - - /** - * Getter for the date and time properties. - * - * @param string $name One of 'year', 'month', 'mday', 'hour', 'min' or - * 'sec'. - * - * @return integer The property value, or null if not set. - */ - public function __get($name) - { - if ($name == 'day') { - $name = 'mday'; - } - - return $this->{'_' . $name}; - } - - /** - * Setter for the date and time properties. - * - * @param string $name One of 'year', 'month', 'mday', 'hour', 'min' or - * 'sec'. - * @param integer $value The property value. - */ - public function __set($name, $value) - { - if ($name == 'timezone') { - $this->_initializeTimezone($value); - return; - } - if ($name == 'day') { - $name = 'mday'; - } - - if ($name != 'year' && $name != 'month' && $name != 'mday' && - $name != 'hour' && $name != 'min' && $name != 'sec') { - throw new InvalidArgumentException('Undefined property ' . $name); - } - - $down = $value < $this->{'_' . $name}; - $this->{'_' . $name} = $value; - $this->_correct(self::$_corrections[$name], $down); - $this->_formatCache = array(); - } - - /** - * Returns whether a date or time property exists. - * - * @param string $name One of 'year', 'month', 'mday', 'hour', 'min' or - * 'sec'. - * - * @return boolen True if the property exists and is set. - */ - public function __isset($name) - { - if ($name == 'day') { - $name = 'mday'; - } - return ($name == 'year' || $name == 'month' || $name == 'mday' || - $name == 'hour' || $name == 'min' || $name == 'sec') && - isset($this->{'_' . $name}); - } - - /** - * Adds a number of seconds or units to this date, returning a new Date - * object. - */ - public function add($factor) - { - $d = clone($this); - if (is_array($factor) || is_object($factor)) { - foreach ($factor as $property => $value) { - $d->$property += $value; - } - } else { - $d->sec += $factor; - } - - return $d; - } - - /** - * Subtracts a number of seconds or units from this date, returning a new - * Horde_Date object. - */ - public function sub($factor) - { - if (is_array($factor)) { - foreach ($factor as &$value) { - $value *= -1; - } - } else { - $factor *= -1; - } - - return $this->add($factor); - } - - /** - * Converts this object to a different timezone. - * - * @param string $timezone The new timezone. - * - * @return Horde_Date This object. - */ - public function setTimezone($timezone) - { - $date = $this->toDateTime(); - $date->setTimezone(new DateTimeZone($timezone)); - $this->_timezone = $timezone; - $this->_year = (int)$date->format('Y'); - $this->_month = (int)$date->format('m'); - $this->_mday = (int)$date->format('d'); - $this->_hour = (int)$date->format('H'); - $this->_min = (int)$date->format('i'); - $this->_sec = (int)$date->format('s'); - $this->_formatCache = array(); - return $this; - } - - /** - * Sets the default date format used in __toString() - * - * @param string $format - */ - public function setDefaultFormat($format) - { - $this->_defaultFormat = $format; - } - - /** - * Returns the day of the week (0 = Sunday, 6 = Saturday) of this date. - * - * @return integer The day of the week. - */ - public function dayOfWeek() - { - if ($this->_month > 2) { - $month = $this->_month - 2; - $year = $this->_year; - } else { - $month = $this->_month + 10; - $year = $this->_year - 1; - } - - $day = (floor((13 * $month - 1) / 5) + - $this->_mday + ($year % 100) + - floor(($year % 100) / 4) + - floor(($year / 100) / 4) - 2 * - floor($year / 100) + 77); - - return (int)($day - 7 * floor($day / 7)); - } - - /** - * Returns the day number of the year (1 to 365/366). - * - * @return integer The day of the year. - */ - public function dayOfYear() - { - return $this->format('z') + 1; - } - - /** - * Returns the week of the month. - * - * @return integer The week number. - */ - public function weekOfMonth() - { - return ceil($this->_mday / 7); - } - - /** - * Returns the week of the year, first Monday is first day of first week. - * - * @return integer The week number. - */ - public function weekOfYear() - { - return $this->format('W'); - } - - /** - * Returns the number of weeks in the given year (52 or 53). - * - * @param integer $year The year to count the number of weeks in. - * - * @return integer $numWeeks The number of weeks in $year. - */ - public static function weeksInYear($year) - { - // Find the last Thursday of the year. - $date = new Horde_Date($year . '-12-31'); - while ($date->dayOfWeek() != self::DATE_THURSDAY) { - --$date->mday; - } - return $date->weekOfYear(); - } - - /** - * Sets the date of this object to the $nth weekday of $weekday. - * - * @param integer $weekday The day of the week (0 = Sunday, etc). - * @param integer $nth The $nth $weekday to set to (defaults to 1). - */ - public function setNthWeekday($weekday, $nth = 1) - { - if ($weekday < self::DATE_SUNDAY || $weekday > self::DATE_SATURDAY) { - return; - } - - if ($nth < 0) { // last $weekday of month - $this->_mday = $lastday = Horde_Date_Utils::daysInMonth($this->_month, $this->_year); - $last = $this->dayOfWeek(); - $this->_mday += ($weekday - $last); - if ($this->_mday > $lastday) - $this->_mday -= 7; - } - else { - $this->_mday = 1; - $first = $this->dayOfWeek(); - if ($weekday < $first) { - $this->_mday = 8 + $weekday - $first; - } else { - $this->_mday = $weekday - $first + 1; - } - $diff = 7 * $nth - 7; - $this->_mday += $diff; - $this->_correct(self::MASK_DAY, $diff < 0); - } - } - - /** - * Is the date currently represented by this object a valid date? - * - * @return boolean Validity, counting leap years, etc. - */ - public function isValid() - { - return ($this->_year >= 0 && $this->_year <= 9999); - } - - /** - * Compares this date to another date object to see which one is - * greater (later). Assumes that the dates are in the same - * timezone. - * - * @param mixed $other The date to compare to. - * - * @return integer == 0 if they are on the same date - * >= 1 if $this is greater (later) - * <= -1 if $other is greater (later) - */ - public function compareDate($other) - { - if (!($other instanceof Horde_Date)) { - $other = new Horde_Date($other); - } - - if ($this->_year != $other->year) { - return $this->_year - $other->year; - } - if ($this->_month != $other->month) { - return $this->_month - $other->month; - } - - return $this->_mday - $other->mday; - } - - /** - * Returns whether this date is after the other. - * - * @param mixed $other The date to compare to. - * - * @return boolean True if this date is after the other. - */ - public function after($other) - { - return $this->compareDate($other) > 0; - } - - /** - * Returns whether this date is before the other. - * - * @param mixed $other The date to compare to. - * - * @return boolean True if this date is before the other. - */ - public function before($other) - { - return $this->compareDate($other) < 0; - } - - /** - * Returns whether this date is the same like the other. - * - * @param mixed $other The date to compare to. - * - * @return boolean True if this date is the same like the other. - */ - public function equals($other) - { - return $this->compareDate($other) == 0; - } - - /** - * Compares this to another date object by time, to see which one - * is greater (later). Assumes that the dates are in the same - * timezone. - * - * @param mixed $other The date to compare to. - * - * @return integer == 0 if they are at the same time - * >= 1 if $this is greater (later) - * <= -1 if $other is greater (later) - */ - public function compareTime($other) - { - if (!($other instanceof Horde_Date)) { - $other = new Horde_Date($other); - } - - if ($this->_hour != $other->hour) { - return $this->_hour - $other->hour; - } - if ($this->_min != $other->min) { - return $this->_min - $other->min; - } - - return $this->_sec - $other->sec; - } - - /** - * Compares this to another date object, including times, to see - * which one is greater (later). Assumes that the dates are in the - * same timezone. - * - * @param mixed $other The date to compare to. - * - * @return integer == 0 if they are equal - * >= 1 if $this is greater (later) - * <= -1 if $other is greater (later) - */ - public function compareDateTime($other) - { - if (!($other instanceof Horde_Date)) { - $other = new Horde_Date($other); - } - - if ($diff = $this->compareDate($other)) { - return $diff; - } - - return $this->compareTime($other); - } - - /** - * Returns number of days between this date and another. - * - * @param Horde_Date $other The other day to diff with. - * - * @return integer The absolute number of days between the two dates. - */ - public function diff($other) - { - return abs($this->toDays() - $other->toDays()); - } - - /** - * Returns the time offset for local time zone. - * - * @param boolean $colon Place a colon between hours and minutes? - * - * @return string Timezone offset as a string in the format +HH:MM. - */ - public function tzOffset($colon = true) - { - return $colon ? $this->format('P') : $this->format('O'); - } - - /** - * Returns the unix timestamp representation of this date. - * - * @return integer A unix timestamp. - */ - public function timestamp() - { - if ($this->_year >= 1970 && $this->_year < 2038) { - return mktime($this->_hour, $this->_min, $this->_sec, - $this->_month, $this->_mday, $this->_year); - } - return $this->format('U'); - } - - /** - * Returns the unix timestamp representation of this date, 12:00am. - * - * @return integer A unix timestamp. - */ - public function datestamp() - { - if ($this->_year >= 1970 && $this->_year < 2038) { - return mktime(0, 0, 0, $this->_month, $this->_mday, $this->_year); - } - $date = new DateTime($this->format('Y-m-d')); - return $date->format('U'); - } - - /** - * Formats date and time to be passed around as a short url parameter. - * - * @return string Date and time. - */ - public function dateString() - { - return sprintf('%04d%02d%02d', $this->_year, $this->_month, $this->_mday); - } - - /** - * Formats date and time to the ISO format used by JSON. - * - * @return string Date and time. - */ - public function toJson() - { - return $this->format(self::DATE_JSON); - } - - /** - * Formats date and time to the RFC 2445 iCalendar DATE-TIME format. - * - * @param boolean $floating Whether to return a floating date-time - * (without time zone information). - * - * @return string Date and time. - */ - public function toiCalendar($floating = false) - { - if ($floating) { - return $this->format('Ymd\THis'); - } - $dateTime = $this->toDateTime(); - $dateTime->setTimezone(new DateTimeZone('UTC')); - return $dateTime->format('Ymd\THis\Z'); - } - - /** - * Formats time using the specifiers available in date() or in the DateTime - * class' format() method. - * - * To format in languages other than English, use strftime() instead. - * - * @param string $format - * - * @return string Formatted time. - */ - public function format($format) - { - if (!isset($this->_formatCache[$format])) { - $this->_formatCache[$format] = $this->toDateTime()->format($format); - } - return $this->_formatCache[$format]; - } - - /** - * Formats date and time using strftime() format. - * - * @return string strftime() formatted date and time. - */ - public function strftime($format) - { - if (preg_match('/%[^' . self::$_supportedSpecs . ']/', $format)) { - return strftime($format, $this->timestamp()); - } else { - return $this->_strftime($format); - } - } - - /** - * Formats date and time using a limited set of the strftime() format. - * - * @return string strftime() formatted date and time. - */ - protected function _strftime($format) - { - return preg_replace( - array('/%b/e', - '/%B/e', - '/%C/e', - '/%d/e', - '/%D/e', - '/%e/e', - '/%H/e', - '/%I/e', - '/%m/e', - '/%M/e', - '/%n/', - '/%p/e', - '/%R/e', - '/%S/e', - '/%t/', - '/%T/e', - '/%x/e', - '/%X/e', - '/%y/e', - '/%Y/', - '/%%/'), - array('$this->_strftime(Horde_Nls::getLangInfo(constant(\'ABMON_\' . (int)$this->_month)))', - '$this->_strftime(Horde_Nls::getLangInfo(constant(\'MON_\' . (int)$this->_month)))', - '(int)($this->_year / 100)', - 'sprintf(\'%02d\', $this->_mday)', - '$this->_strftime(\'%m/%d/%y\')', - 'sprintf(\'%2d\', $this->_mday)', - 'sprintf(\'%02d\', $this->_hour)', - 'sprintf(\'%02d\', $this->_hour == 0 ? 12 : ($this->_hour > 12 ? $this->_hour - 12 : $this->_hour))', - 'sprintf(\'%02d\', $this->_month)', - 'sprintf(\'%02d\', $this->_min)', - "\n", - '$this->_strftime(Horde_Nls::getLangInfo($this->_hour < 12 ? AM_STR : PM_STR))', - '$this->_strftime(\'%H:%M\')', - 'sprintf(\'%02d\', $this->_sec)', - "\t", - '$this->_strftime(\'%H:%M:%S\')', - '$this->_strftime(Horde_Nls::getLangInfo(D_FMT))', - '$this->_strftime(Horde_Nls::getLangInfo(T_FMT))', - 'substr(sprintf(\'%04d\', $this->_year), -2)', - (int)$this->_year, - '%'), - $format); - } - - /** - * Corrects any over- or underflows in any of the date's members. - * - * @param integer $mask We may not want to correct some overflows. - * @param integer $down Whether to correct the date up or down. - */ - protected function _correct($mask = self::MASK_ALLPARTS, $down = false) - { - if ($mask & self::MASK_SECOND) { - if ($this->_sec < 0 || $this->_sec > 59) { - $mask |= self::MASK_MINUTE; - - $this->_min += (int)($this->_sec / 60); - $this->_sec %= 60; - if ($this->_sec < 0) { - $this->_min--; - $this->_sec += 60; - } - } - } - - if ($mask & self::MASK_MINUTE) { - if ($this->_min < 0 || $this->_min > 59) { - $mask |= self::MASK_HOUR; - - $this->_hour += (int)($this->_min / 60); - $this->_min %= 60; - if ($this->_min < 0) { - $this->_hour--; - $this->_min += 60; - } - } - } - - if ($mask & self::MASK_HOUR) { - if ($this->_hour < 0 || $this->_hour > 23) { - $mask |= self::MASK_DAY; - - $this->_mday += (int)($this->_hour / 24); - $this->_hour %= 24; - if ($this->_hour < 0) { - $this->_mday--; - $this->_hour += 24; - } - } - } - - if ($mask & self::MASK_MONTH) { - $this->_correctMonth($down); - /* When correcting the month, always correct the day too. Months - * have different numbers of days. */ - $mask |= self::MASK_DAY; - } - - if ($mask & self::MASK_DAY) { - while ($this->_mday > 28 && - $this->_mday > Horde_Date_Utils::daysInMonth($this->_month, $this->_year)) { - if ($down) { - $this->_mday -= Horde_Date_Utils::daysInMonth($this->_month + 1, $this->_year) - Horde_Date_Utils::daysInMonth($this->_month, $this->_year); - } else { - $this->_mday -= Horde_Date_Utils::daysInMonth($this->_month, $this->_year); - $this->_month++; - } - $this->_correctMonth($down); - } - while ($this->_mday < 1) { - --$this->_month; - $this->_correctMonth($down); - $this->_mday += Horde_Date_Utils::daysInMonth($this->_month, $this->_year); - } - } - } - - /** - * Corrects the current month. - * - * This cannot be done in _correct() because that would also trigger a - * correction of the day, which would result in an infinite loop. - * - * @param integer $down Whether to correct the date up or down. - */ - protected function _correctMonth($down = false) - { - $this->_year += (int)($this->_month / 12); - $this->_month %= 12; - if ($this->_month < 1) { - $this->_year--; - $this->_month += 12; - } - } - - /** - * Handles args in order: year month day hour min sec tz - */ - protected function _initializeFromArgs($args) - { - $tz = (isset($args[6])) ? array_pop($args) : null; - $this->_initializeTimezone($tz); - - $args = array_slice($args, 0, 6); - $keys = array('year' => 1, 'month' => 1, 'mday' => 1, 'hour' => 0, 'min' => 0, 'sec' => 0); - $date = array_combine(array_slice(array_keys($keys), 0, count($args)), $args); - $date = array_merge($keys, $date); - - $this->_initializeFromArray($date); - } - - protected function _initializeFromArray($date) - { - if (isset($date['year']) && is_string($date['year']) && strlen($date['year']) == 2) { - if ($date['year'] > 70) { - $date['year'] += 1900; - } else { - $date['year'] += 2000; - } - } - - foreach ($date as $key => $val) { - if (in_array($key, array('year', 'month', 'mday', 'hour', 'min', 'sec'))) { - $this->{'_'. $key} = (int)$val; - } - } - - // If $date['day'] is present and numeric we may have been passed - // a Horde_Form_datetime array. - if (isset($date['day']) && - (string)(int)$date['day'] == $date['day']) { - $this->_mday = (int)$date['day']; - } - // 'minute' key also from Horde_Form_datetime - if (isset($date['minute']) && - (string)(int)$date['minute'] == $date['minute']) { - $this->_min = (int)$date['minute']; - } - - $this->_correct(); - } - - protected function _initializeFromObject($date) - { - if ($date instanceof DateTime) { - $this->_year = (int)$date->format('Y'); - $this->_month = (int)$date->format('m'); - $this->_mday = (int)$date->format('d'); - $this->_hour = (int)$date->format('H'); - $this->_min = (int)$date->format('i'); - $this->_sec = (int)$date->format('s'); - $this->_initializeTimezone($date->getTimezone()->getName()); - } else { - $is_horde_date = $date instanceof Horde_Date; - foreach (array('year', 'month', 'mday', 'hour', 'min', 'sec') as $key) { - if ($is_horde_date || isset($date->$key)) { - $this->{'_' . $key} = (int)$date->$key; - } - } - if (!$is_horde_date) { - $this->_correct(); - } else { - $this->_initializeTimezone($date->timezone); - } - } - } - - protected function _initializeTimezone($timezone) - { - if (empty($timezone)) { - $timezone = date_default_timezone_get(); - } - $this->_timezone = $timezone; - } - -} - -/** - * @category Horde - * @package Date - */ - -/** - * Horde Date wrapper/logic class, including some calculation - * functions. - * - * @category Horde - * @package Date - */ -class Horde_Date_Utils -{ - /** - * Returns whether a year is a leap year. - * - * @param integer $year The year. - * - * @return boolean True if the year is a leap year. - */ - public static function isLeapYear($year) - { - if (strlen($year) != 4 || preg_match('/\D/', $year)) { - return false; - } - - return (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0); - } - - /** - * Returns the date of the year that corresponds to the first day of the - * given week. - * - * @param integer $week The week of the year to find the first day of. - * @param integer $year The year to calculate for. - * - * @return Horde_Date The date of the first day of the given week. - */ - public static function firstDayOfWeek($week, $year) - { - return new Horde_Date(sprintf('%04dW%02d', $year, $week)); - } - - /** - * Returns the number of days in the specified month. - * - * @param integer $month The month - * @param integer $year The year. - * - * @return integer The number of days in the month. - */ - public static function daysInMonth($month, $year) - { - static $cache = array(); - if (!isset($cache[$year][$month])) { - $date = new DateTime(sprintf('%04d-%02d-01', $year, $month)); - $cache[$year][$month] = $date->format('t'); - } - return $cache[$year][$month]; - } - - /** - * Returns a relative, natural language representation of a timestamp - * - * @todo Wider range of values ... maybe future time as well? - * @todo Support minimum resolution parameter. - * - * @param mixed $time The time. Any format accepted by Horde_Date. - * @param string $date_format Format to display date if timestamp is - * more then 1 day old. - * @param string $time_format Format to display time if timestamp is 1 - * day old. - * - * @return string The relative time (i.e. 2 minutes ago) - */ - public static function relativeDateTime($time, $date_format = '%x', - $time_format = '%X') - { - $date = new Horde_Date($time); - - $delta = time() - $date->timestamp(); - if ($delta < 60) { - return sprintf(Horde_Date_Translation::ngettext("%d second ago", "%d seconds ago", $delta), $delta); - } - - $delta = round($delta / 60); - if ($delta < 60) { - return sprintf(Horde_Date_Translation::ngettext("%d minute ago", "%d minutes ago", $delta), $delta); - } - - $delta = round($delta / 60); - if ($delta < 24) { - return sprintf(Horde_Date_Translation::ngettext("%d hour ago", "%d hours ago", $delta), $delta); - } - - if ($delta > 24 && $delta < 48) { - $date = new Horde_Date($time); - return sprintf(Horde_Date_Translation::t("yesterday at %s"), $date->strftime($time_format)); - } - - $delta = round($delta / 24); - if ($delta < 7) { - return sprintf(Horde_Date_Translation::t("%d days ago"), $delta); - } - - if (round($delta / 7) < 5) { - $delta = round($delta / 7); - return sprintf(Horde_Date_Translation::ngettext("%d week ago", "%d weeks ago", $delta), $delta); - } - - // Default to the user specified date format. - return $date->strftime($date_format); - } - - /** - * Tries to convert strftime() formatters to date() formatters. - * - * Unsupported formatters will be removed. - * - * @param string $format A strftime() formatting string. - * - * @return string A date() formatting string. - */ - public static function strftime2date($format) - { - $replace = array( - '/%a/' => 'D', - '/%A/' => 'l', - '/%d/' => 'd', - '/%e/' => 'j', - '/%j/' => 'z', - '/%u/' => 'N', - '/%w/' => 'w', - '/%U/' => '', - '/%V/' => 'W', - '/%W/' => '', - '/%b/' => 'M', - '/%B/' => 'F', - '/%h/' => 'M', - '/%m/' => 'm', - '/%C/' => '', - '/%g/' => '', - '/%G/' => 'o', - '/%y/' => 'y', - '/%Y/' => 'Y', - '/%H/' => 'H', - '/%I/' => 'h', - '/%i/' => 'g', - '/%M/' => 'i', - '/%p/' => 'A', - '/%P/' => 'a', - '/%r/' => 'h:i:s A', - '/%R/' => 'H:i', - '/%S/' => 's', - '/%T/' => 'H:i:s', - '/%X/e' => 'Horde_Date_Utils::strftime2date(Horde_Nls::getLangInfo(T_FMT))', - '/%z/' => 'O', - '/%Z/' => '', - '/%c/' => '', - '/%D/' => 'm/d/y', - '/%F/' => 'Y-m-d', - '/%s/' => 'U', - '/%x/e' => 'Horde_Date_Utils::strftime2date(Horde_Nls::getLangInfo(D_FMT))', - '/%n/' => "\n", - '/%t/' => "\t", - '/%%/' => '%' - ); - - return preg_replace(array_keys($replace), array_values($replace), $format); - } - -} diff --git a/plugins/libcalendaring/lib/Horde_Date_Recurrence.php b/plugins/libcalendaring/lib/Horde_Date_Recurrence.php deleted file mode 100644 index 4dfdfaf6..00000000 --- a/plugins/libcalendaring/lib/Horde_Date_Recurrence.php +++ /dev/null @@ -1,1747 +0,0 @@ - 1 ? $plur : $sing); } -} - - -/** - * This file contains the Horde_Date_Recurrence class and according constants. - * - * Copyright 2007-2015 Horde LLC (http://www.horde.org/) - * - * See the enclosed file COPYING for license information (LGPL). If you - * did not receive this file, see http://www.horde.org/licenses/lgpl21. - * - * @category Horde - * @package Date - */ - -/** - * The Horde_Date_Recurrence class implements algorithms for calculating - * recurrences of events, including several recurrence types, intervals, - * exceptions, and conversion from and to vCalendar and iCalendar recurrence - * rules. - * - * All methods expecting dates as parameters accept all values that the - * Horde_Date constructor accepts, i.e. a timestamp, another Horde_Date - * object, an ISO time string or a hash. - * - * @author Jan Schneider - * @category Horde - * @package Date - */ -class Horde_Date_Recurrence -{ - /** No Recurrence **/ - const RECUR_NONE = 0; - - /** Recurs daily. */ - const RECUR_DAILY = 1; - - /** Recurs weekly. */ - const RECUR_WEEKLY = 2; - - /** Recurs monthly on the same date. */ - const RECUR_MONTHLY_DATE = 3; - - /** Recurs monthly on the same week day. */ - const RECUR_MONTHLY_WEEKDAY = 4; - - /** Recurs yearly on the same date. */ - const RECUR_YEARLY_DATE = 5; - - /** Recurs yearly on the same day of the year. */ - const RECUR_YEARLY_DAY = 6; - - /** Recurs yearly on the same week day. */ - const RECUR_YEARLY_WEEKDAY = 7; - - /** - * The start time of the event. - * - * @var Horde_Date - */ - public $start; - - /** - * The end date of the recurrence interval. - * - * @var Horde_Date - */ - public $recurEnd = null; - - /** - * The number of recurrences. - * - * @var integer - */ - public $recurCount = null; - - /** - * The type of recurrence this event follows. RECUR_* constant. - * - * @var integer - */ - public $recurType = self::RECUR_NONE; - - /** - * The length of time between recurrences. The time unit depends on the - * recurrence type. - * - * @var integer - */ - public $recurInterval = 1; - - /** - * Any additional recurrence data. - * - * @var integer - */ - public $recurData = null; - - /** - * BYDAY recurrence number - * - * @var integer - */ - public $recurNthDay = null; - - /** - * BYMONTH recurrence data - * - * @var array - */ - public $recurMonths = array(); - - /** - * RDATE recurrence values - * - * @var array - */ - public $rdates = array(); - - /** - * All the exceptions from recurrence for this event. - * - * @var array - */ - public $exceptions = array(); - - /** - * All the dates this recurrence has been marked as completed. - * - * @var array - */ - public $completions = array(); - - /** - * Constructor. - * - * @param Horde_Date $start Start of the recurring event. - */ - public function __construct($start) - { - $this->start = new Horde_Date($start); - } - - /** - * Resets the class properties. - */ - public function reset() - { - $this->recurEnd = null; - $this->recurCount = null; - $this->recurType = self::RECUR_NONE; - $this->recurInterval = 1; - $this->recurData = null; - $this->exceptions = array(); - $this->completions = array(); - } - - /** - * Checks if this event recurs on a given day of the week. - * - * @param integer $dayMask A mask consisting of Horde_Date::MASK_* - * constants specifying the day(s) to check. - * - * @return boolean True if this event recurs on the given day(s). - */ - public function recurOnDay($dayMask) - { - return ($this->recurData & $dayMask); - } - - /** - * Specifies the days this event recurs on. - * - * @param integer $dayMask A mask consisting of Horde_Date::MASK_* - * constants specifying the day(s) to recur on. - */ - public function setRecurOnDay($dayMask) - { - $this->recurData = $dayMask; - } - - /** - * - * @param integer $nthDay The nth weekday of month to repeat events on - */ - public function setRecurNthWeekday($nth) - { - $this->recurNthDay = (int)$nth; - } - - /** - * - * @return integer The nth weekday of month to repeat events. - */ - public function getRecurNthWeekday() - { - return isset($this->recurNthDay) ? $this->recurNthDay : ceil($this->start->mday / 7); - } - - /** - * Specifies the months for yearly (weekday) recurrence - * - * @param array $months List of months (integers) this event recurs on. - */ - function setRecurByMonth($months) - { - $this->recurMonths = (array)$months; - } - - /** - * Returns a list of months this yearly event recurs on - * - * @return array List of months (integers) this event recurs on. - */ - function getRecurByMonth() - { - return $this->recurMonths; - } - - /** - * Returns the days this event recurs on. - * - * @return integer A mask consisting of Horde_Date::MASK_* constants - * specifying the day(s) this event recurs on. - */ - public function getRecurOnDays() - { - return $this->recurData; - } - - /** - * Returns whether this event has a specific recurrence type. - * - * @param integer $recurrence RECUR_* constant of the - * recurrence type to check for. - * - * @return boolean True if the event has the specified recurrence type. - */ - public function hasRecurType($recurrence) - { - return ($recurrence == $this->recurType); - } - - /** - * Sets a recurrence type for this event. - * - * @param integer $recurrence A RECUR_* constant. - */ - public function setRecurType($recurrence) - { - $this->recurType = $recurrence; - } - - /** - * Returns recurrence type of this event. - * - * @return integer A RECUR_* constant. - */ - public function getRecurType() - { - return $this->recurType; - } - - /** - * Returns a description of this event's recurring type. - * - * @return string Human readable recurring type. - */ - public function getRecurName() - { - switch ($this->getRecurType()) { - case self::RECUR_NONE: - return Horde_Date_Translation::t("No recurrence"); - case self::RECUR_DAILY: - return Horde_Date_Translation::t("Daily"); - case self::RECUR_WEEKLY: - return Horde_Date_Translation::t("Weekly"); - case self::RECUR_MONTHLY_DATE: - case self::RECUR_MONTHLY_WEEKDAY: - return Horde_Date_Translation::t("Monthly"); - case self::RECUR_YEARLY_DATE: - case self::RECUR_YEARLY_DAY: - case self::RECUR_YEARLY_WEEKDAY: - return Horde_Date_Translation::t("Yearly"); - } - } - - /** - * Sets the length of time between recurrences of this event. - * - * @param integer $interval The time between recurrences. - */ - public function setRecurInterval($interval) - { - if ($interval > 0) { - $this->recurInterval = $interval; - } - } - - /** - * Retrieves the length of time between recurrences of this event. - * - * @return integer The number of seconds between recurrences. - */ - public function getRecurInterval() - { - return $this->recurInterval; - } - - /** - * Sets the number of recurrences of this event. - * - * @param integer $count The number of recurrences. - */ - public function setRecurCount($count) - { - if ($count > 0) { - $this->recurCount = (int)$count; - // Recurrence counts and end dates are mutually exclusive. - $this->recurEnd = null; - } else { - $this->recurCount = null; - } - } - - /** - * Retrieves the number of recurrences of this event. - * - * @return integer The number recurrences. - */ - public function getRecurCount() - { - return $this->recurCount; - } - - /** - * Returns whether this event has a recurrence with a fixed count. - * - * @return boolean True if this recurrence has a fixed count. - */ - public function hasRecurCount() - { - return isset($this->recurCount); - } - - /** - * Sets the start date of the recurrence interval. - * - * @param Horde_Date $start The recurrence start. - */ - public function setRecurStart($start) - { - $this->start = clone $start; - } - - /** - * Retrieves the start date of the recurrence interval. - * - * @return Horde_Date The recurrence start. - */ - public function getRecurStart() - { - return $this->start; - } - - /** - * Sets the end date of the recurrence interval. - * - * @param Horde_Date $end The recurrence end. - */ - public function setRecurEnd($end) - { - if (!empty($end)) { - // Recurrence counts and end dates are mutually exclusive. - $this->recurCount = null; - $this->recurEnd = clone $end; - } else { - $this->recurEnd = $end; - } - } - - /** - * Retrieves the end date of the recurrence interval. - * - * @return Horde_Date The recurrence end. - */ - public function getRecurEnd() - { - return $this->recurEnd; - } - - /** - * Returns whether this event has a recurrence end. - * - * @return boolean True if this recurrence ends. - */ - public function hasRecurEnd() - { - return isset($this->recurEnd) && isset($this->recurEnd->year) && - $this->recurEnd->year != 9999; - } - - /** - * Finds the next recurrence of this event that's after $afterDate. - * - * @param Horde_Date|string $after Return events after this date. - * - * @return Horde_Date|boolean The date of the next recurrence or false - * if the event does not recur after - * $afterDate. - */ - public function nextRecurrence($after) - { - if (!($after instanceof Horde_Date)) { - $after = new Horde_Date($after); - } else { - $after = clone($after); - } - - // Make sure $after and $this->start are in the same TZ - $after->setTimezone($this->start->timezone); - if ($this->start->compareDateTime($after) >= 0) { - return clone $this->start; - } - - if ($this->recurInterval == 0 && empty($this->rdates)) { - return false; - } - - switch ($this->getRecurType()) { - case self::RECUR_DAILY: - $diff = $this->start->diff($after); - $recur = ceil($diff / $this->recurInterval); - if ($this->recurCount && $recur >= $this->recurCount) { - return false; - } - - $recur *= $this->recurInterval; - $next = $this->start->add(array('day' => $recur)); - if ((!$this->hasRecurEnd() || - $next->compareDateTime($this->recurEnd) <= 0) && - $next->compareDateTime($after) >= 0) { - return $next; - } - - break; - - case self::RECUR_WEEKLY: - if (empty($this->recurData)) { - return false; - } - - $start_week = Horde_Date_Utils::firstDayOfWeek($this->start->format('W'), - $this->start->year); - $start_week->timezone = $this->start->timezone; - $start_week->hour = $this->start->hour; - $start_week->min = $this->start->min; - $start_week->sec = $this->start->sec; - - // Make sure we are not at the ISO-8601 first week of year while - // still in month 12...OR in the ISO-8601 last week of year while - // in month 1 and adjust the year accordingly. - $week = $after->format('W'); - if ($week == 1 && $after->month == 12) { - $theYear = $after->year + 1; - } elseif ($week >= 52 && $after->month == 1) { - $theYear = $after->year - 1; - } else { - $theYear = $after->year; - } - - $after_week = Horde_Date_Utils::firstDayOfWeek($week, $theYear); - $after_week->timezone = $this->start->timezone; - $after_week_end = clone $after_week; - $after_week_end->mday += 7; - - $diff = $start_week->diff($after_week); - $interval = $this->recurInterval * 7; - $repeats = floor($diff / $interval); - if ($diff % $interval < 7) { - $recur = $diff; - } else { - /** - * If the after_week is not in the first week interval the - * search needs to skip ahead a complete interval. The way it is - * calculated here means that an event that occurs every second - * week on Monday and Wednesday with the event actually starting - * on Tuesday or Wednesday will only have one incidence in the - * first week. - */ - $recur = $interval * ($repeats + 1); - } - - if ($this->hasRecurCount()) { - $recurrences = 0; - /** - * Correct the number of recurrences by the number of events - * that lay between the start of the start week and the - * recurrence start. - */ - $next = clone $start_week; - while ($next->compareDateTime($this->start) < 0) { - if ($this->recurOnDay((int)pow(2, $next->dayOfWeek()))) { - $recurrences--; - } - ++$next->mday; - } - if ($repeats > 0) { - $weekdays = $this->recurData; - $total_recurrences_per_week = 0; - while ($weekdays > 0) { - if ($weekdays % 2) { - $total_recurrences_per_week++; - } - $weekdays = ($weekdays - ($weekdays % 2)) / 2; - } - $recurrences += $total_recurrences_per_week * $repeats; - } - } - - $next = clone $start_week; - $next->mday += $recur; - while ($next->compareDateTime($after) < 0 && - $next->compareDateTime($after_week_end) < 0) { - if ($this->hasRecurCount() - && $next->compareDateTime($after) < 0 - && $this->recurOnDay((int)pow(2, $next->dayOfWeek()))) { - $recurrences++; - } - ++$next->mday; - } - if ($this->hasRecurCount() && - $recurrences >= $this->recurCount) { - return false; - } - if (!$this->hasRecurEnd() || - $next->compareDateTime($this->recurEnd) <= 0) { - if ($next->compareDateTime($after_week_end) >= 0) { - return $this->nextRecurrence($after_week_end); - } - while (!$this->recurOnDay((int)pow(2, $next->dayOfWeek())) && - $next->compareDateTime($after_week_end) < 0) { - ++$next->mday; - } - if (!$this->hasRecurEnd() || - $next->compareDateTime($this->recurEnd) <= 0) { - if ($next->compareDateTime($after_week_end) >= 0) { - return $this->nextRecurrence($after_week_end); - } else { - return $next; - } - } - } - break; - - case self::RECUR_MONTHLY_DATE: - $start = clone $this->start; - if ($after->compareDateTime($start) < 0) { - $after = clone $start; - } else { - $after = clone $after; - } - - // If we're starting past this month's recurrence of the event, - // look in the next month on the day the event recurs. - if ($after->mday > $start->mday) { - ++$after->month; - $after->mday = $start->mday; - } - - // Adjust $start to be the first match. - $offset = ($after->month - $start->month) + ($after->year - $start->year) * 12; - $offset = floor(($offset + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval; - - if ($this->recurCount && - ($offset / $this->recurInterval) >= $this->recurCount) { - return false; - } - $start->month += $offset; - $count = $offset / $this->recurInterval; - - do { - if ($this->recurCount && - $count++ >= $this->recurCount) { - return false; - } - - // Bail if we've gone past the end of recurrence. - if ($this->hasRecurEnd() && - $this->recurEnd->compareDateTime($start) < 0) { - return false; - } - if ($start->isValid()) { - return $start; - } - - // If the interval is 12, and the date isn't valid, then we - // need to see if February 29th is an option. If not, then the - // event will _never_ recur, and we need to stop checking to - // avoid an infinite loop. - if ($this->recurInterval == 12 && ($start->month != 2 || $start->mday > 29)) { - return false; - } - - // Add the recurrence interval. - $start->month += $this->recurInterval; - } while (true); - - break; - - case self::RECUR_MONTHLY_WEEKDAY: - // Start with the start date of the event. - $estart = clone $this->start; - - // What day of the week, and week of the month, do we recur on? - if (isset($this->recurNthDay)) { - $nth = $this->recurNthDay; - $weekday = log($this->recurData, 2); - } else { - $nth = ceil($this->start->mday / 7); - $weekday = $estart->dayOfWeek(); - } - - // Adjust $estart to be the first candidate. - $offset = ($after->month - $estart->month) + ($after->year - $estart->year) * 12; - $offset = floor(($offset + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval; - - // Adjust our working date until it's after $after. - $estart->month += $offset - $this->recurInterval; - - $count = $offset / $this->recurInterval; - do { - if ($this->recurCount && - $count++ >= $this->recurCount) { - return false; - } - - $estart->month += $this->recurInterval; - - $next = clone $estart; - $next->setNthWeekday($weekday, $nth); - - if ($next->month != $estart->month) { - // We're already in the next month. - continue; - } - if ($next->compareDateTime($after) < 0) { - // We haven't made it past $after yet, try again. - continue; - } - if ($this->hasRecurEnd() && - $next->compareDateTime($this->recurEnd) > 0) { - // We've gone past the end of recurrence; we can give up - // now. - return false; - } - - // We have a candidate to return. - break; - } while (true); - - return $next; - - case self::RECUR_YEARLY_DATE: - // Start with the start date of the event. - $estart = clone $this->start; - $after = clone $after; - - if ($after->month > $estart->month || - ($after->month == $estart->month && $after->mday > $estart->mday)) { - ++$after->year; - $after->month = $estart->month; - $after->mday = $estart->mday; - } - - // Seperate case here for February 29th - if ($estart->month == 2 && $estart->mday == 29) { - while (!Horde_Date_Utils::isLeapYear($after->year)) { - ++$after->year; - } - } - - // Adjust $estart to be the first candidate. - $offset = $after->year - $estart->year; - if ($offset > 0) { - $offset = floor(($offset + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval; - $estart->year += $offset; - } - - // We've gone past the end of recurrence; give up. - if ($this->recurCount && - $offset >= $this->recurCount) { - return false; - } - if ($this->hasRecurEnd() && - $this->recurEnd->compareDateTime($estart) < 0) { - return false; - } - - return $estart; - - case self::RECUR_YEARLY_DAY: - // Check count first. - $dayofyear = $this->start->dayOfYear(); - $count = ($after->year - $this->start->year) / $this->recurInterval + 1; - if ($this->recurCount && - ($count > $this->recurCount || - ($count == $this->recurCount && - $after->dayOfYear() > $dayofyear))) { - return false; - } - - // Start with a rough interval. - $estart = clone $this->start; - $estart->year += floor($count - 1) * $this->recurInterval; - - // Now add the difference to the required day of year. - $estart->mday += $dayofyear - $estart->dayOfYear(); - - // Add an interval if the estimation was wrong. - if ($estart->compareDate($after) < 0) { - $estart->year += $this->recurInterval; - $estart->mday += $dayofyear - $estart->dayOfYear(); - } - - // We've gone past the end of recurrence; give up. - if ($this->hasRecurEnd() && - $this->recurEnd->compareDateTime($estart) < 0) { - return false; - } - - return $estart; - - case self::RECUR_YEARLY_WEEKDAY: - // Start with the start date of the event. - $estart = clone $this->start; - - // What day of the week, and week of the month, do we recur on? - if (isset($this->recurNthDay)) { - $nth = $this->recurNthDay; - $weekday = log($this->recurData, 2); - } else { - $nth = ceil($this->start->mday / 7); - $weekday = $estart->dayOfWeek(); - } - - // Adjust $estart to be the first candidate. - $offset = floor(($after->year - $estart->year + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval; - - // Adjust our working date until it's after $after. - $estart->year += $offset - $this->recurInterval; - - $count = $offset / $this->recurInterval; - do { - if ($this->recurCount && - $count++ >= $this->recurCount) { - return false; - } - - $estart->year += $this->recurInterval; - - $next = clone $estart; - $next->setNthWeekday($weekday, $nth); - - if ($next->compareDateTime($after) < 0) { - // We haven't made it past $after yet, try again. - continue; - } - if ($this->hasRecurEnd() && - $next->compareDateTime($this->recurEnd) > 0) { - // We've gone past the end of recurrence; we can give up - // now. - return false; - } - - // We have a candidate to return. - break; - } while (true); - - return $next; - } - - // fall-back to RDATE properties - if (!empty($this->rdates)) { - $next = clone $this->start; - foreach ($this->rdates as $rdate) { - $next->year = $rdate->year; - $next->month = $rdate->month; - $next->mday = $rdate->mday; - if ($next->compareDateTime($after) >= 0) { - return $next; - } - } - } - - // We didn't find anything, the recurType was bad, or something else - // went wrong - return false. - return false; - } - - /** - * Returns whether this event has any date that matches the recurrence - * rules and is not an exception. - * - * @return boolean True if an active recurrence exists. - */ - public function hasActiveRecurrence() - { - if (!$this->hasRecurEnd()) { - return true; - } - - $next = $this->nextRecurrence(new Horde_Date($this->start)); - while (is_object($next)) { - if (!$this->hasException($next->year, $next->month, $next->mday) && - !$this->hasCompletion($next->year, $next->month, $next->mday)) { - return true; - } - - $next = $this->nextRecurrence($next->add(array('day' => 1))); - } - - return false; - } - - /** - * Returns the next active recurrence. - * - * @param Horde_Date $afterDate Return events after this date. - * - * @return Horde_Date|boolean The date of the next active - * recurrence or false if the event - * has no active recurrence after - * $afterDate. - */ - public function nextActiveRecurrence($afterDate) - { - $next = $this->nextRecurrence($afterDate); - while (is_object($next)) { - if (!$this->hasException($next->year, $next->month, $next->mday) && - !$this->hasCompletion($next->year, $next->month, $next->mday)) { - return $next; - } - $next->mday++; - $next = $this->nextRecurrence($next); - } - - return false; - } - - /** - * Adds an absolute recurrence date. - * - * @param integer $year The year of the instance. - * @param integer $month The month of the instance. - * @param integer $mday The day of the month of the instance. - */ - public function addRDate($year, $month, $mday) - { - $this->rdates[] = new Horde_Date($year, $month, $mday); - } - - /** - * Adds an exception to a recurring event. - * - * @param integer $year The year of the execption. - * @param integer $month The month of the execption. - * @param integer $mday The day of the month of the exception. - */ - public function addException($year, $month, $mday) - { - $key = sprintf('%04d%02d%02d', $year, $month, $mday); - if (array_search($key, $this->exceptions) === false) { - $this->exceptions[] = sprintf('%04d%02d%02d', $year, $month, $mday); - } - } - - /** - * Deletes an exception from a recurring event. - * - * @param integer $year The year of the execption. - * @param integer $month The month of the execption. - * @param integer $mday The day of the month of the exception. - */ - public function deleteException($year, $month, $mday) - { - $key = array_search(sprintf('%04d%02d%02d', $year, $month, $mday), $this->exceptions); - if ($key !== false) { - unset($this->exceptions[$key]); - } - } - - /** - * Checks if an exception exists for a given reccurence of an event. - * - * @param integer $year The year of the reucrance. - * @param integer $month The month of the reucrance. - * @param integer $mday The day of the month of the reucrance. - * - * @return boolean True if an exception exists for the given date. - */ - public function hasException($year, $month, $mday) - { - return in_array(sprintf('%04d%02d%02d', $year, $month, $mday), - $this->getExceptions()); - } - - /** - * Retrieves all the exceptions for this event. - * - * @return array Array containing the dates of all the exceptions in - * YYYYMMDD form. - */ - public function getExceptions() - { - return $this->exceptions; - } - - /** - * Adds a completion to a recurring event. - * - * @param integer $year The year of the execption. - * @param integer $month The month of the execption. - * @param integer $mday The day of the month of the completion. - */ - public function addCompletion($year, $month, $mday) - { - $this->completions[] = sprintf('%04d%02d%02d', $year, $month, $mday); - } - - /** - * Deletes a completion from a recurring event. - * - * @param integer $year The year of the execption. - * @param integer $month The month of the execption. - * @param integer $mday The day of the month of the completion. - */ - public function deleteCompletion($year, $month, $mday) - { - $key = array_search(sprintf('%04d%02d%02d', $year, $month, $mday), $this->completions); - if ($key !== false) { - unset($this->completions[$key]); - } - } - - /** - * Checks if a completion exists for a given reccurence of an event. - * - * @param integer $year The year of the reucrance. - * @param integer $month The month of the recurrance. - * @param integer $mday The day of the month of the recurrance. - * - * @return boolean True if a completion exists for the given date. - */ - public function hasCompletion($year, $month, $mday) - { - return in_array(sprintf('%04d%02d%02d', $year, $month, $mday), - $this->getCompletions()); - } - - /** - * Retrieves all the completions for this event. - * - * @return array Array containing the dates of all the completions in - * YYYYMMDD form. - */ - public function getCompletions() - { - return $this->completions; - } - - /** - * Parses a vCalendar 1.0 recurrence rule. - * - * @link http://www.imc.org/pdi/vcal-10.txt - * @link http://www.shuchow.com/vCalAddendum.html - * - * @param string $rrule A vCalendar 1.0 conform RRULE value. - */ - public function fromRRule10($rrule) - { - $this->reset(); - - if (!$rrule) { - return; - } - - if (!preg_match('/([A-Z]+)(\d+)?(.*)/', $rrule, $matches)) { - // No recurrence data - event does not recur. - $this->setRecurType(self::RECUR_NONE); - } - - // Always default the recurInterval to 1. - $this->setRecurInterval(!empty($matches[2]) ? $matches[2] : 1); - - $remainder = trim($matches[3]); - - switch ($matches[1]) { - case 'D': - $this->setRecurType(self::RECUR_DAILY); - break; - - case 'W': - $this->setRecurType(self::RECUR_WEEKLY); - if (!empty($remainder)) { - $mask = 0; - while (preg_match('/^ ?[A-Z]{2} ?/', $remainder, $matches)) { - $day = trim($matches[0]); - $remainder = substr($remainder, strlen($matches[0])); - $mask |= $maskdays[$day]; - } - $this->setRecurOnDay($mask); - } else { - // Recur on the day of the week of the original recurrence. - $maskdays = array( - Horde_Date::DATE_SUNDAY => Horde_Date::MASK_SUNDAY, - Horde_Date::DATE_MONDAY => Horde_Date::MASK_MONDAY, - Horde_Date::DATE_TUESDAY => Horde_Date::MASK_TUESDAY, - Horde_Date::DATE_WEDNESDAY => Horde_Date::MASK_WEDNESDAY, - Horde_Date::DATE_THURSDAY => Horde_Date::MASK_THURSDAY, - Horde_Date::DATE_FRIDAY => Horde_Date::MASK_FRIDAY, - Horde_Date::DATE_SATURDAY => Horde_Date::MASK_SATURDAY, - ); - $this->setRecurOnDay($maskdays[$this->start->dayOfWeek()]); - } - break; - - case 'MP': - $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY); - break; - - case 'MD': - $this->setRecurType(self::RECUR_MONTHLY_DATE); - break; - - case 'YM': - $this->setRecurType(self::RECUR_YEARLY_DATE); - break; - - case 'YD': - $this->setRecurType(self::RECUR_YEARLY_DAY); - break; - } - - // We don't support modifiers at the moment, strip them. - while ($remainder && !preg_match('/^(#\d+|\d{8})($| |T\d{6})/', $remainder)) { - $remainder = substr($remainder, 1); - } - if (!empty($remainder)) { - if (strpos($remainder, '#') === 0) { - $this->setRecurCount(substr($remainder, 1)); - } else { - list($year, $month, $mday, $hour, $min, $sec, $tz) = - sscanf($remainder, '%04d%02d%02dT%02d%02d%02d%s'); - $this->setRecurEnd(new Horde_Date(array('year' => $year, - 'month' => $month, - 'mday' => $mday, - 'hour' => $hour, - 'min' => $min, - 'sec' => $sec), - $tz == 'Z' ? 'UTC' : $this->start->timezone)); - } - } - } - - /** - * Creates a vCalendar 1.0 recurrence rule. - * - * @link http://www.imc.org/pdi/vcal-10.txt - * @link http://www.shuchow.com/vCalAddendum.html - * - * @param Horde_Icalendar $calendar A Horde_Icalendar object instance. - * - * @return string A vCalendar 1.0 conform RRULE value. - */ - public function toRRule10($calendar) - { - switch ($this->recurType) { - case self::RECUR_NONE: - return ''; - - case self::RECUR_DAILY: - $rrule = 'D' . $this->recurInterval; - break; - - case self::RECUR_WEEKLY: - $rrule = 'W' . $this->recurInterval; - $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); - - for ($i = 0; $i <= 7; ++$i) { - if ($this->recurOnDay(pow(2, $i))) { - $rrule .= ' ' . $vcaldays[$i]; - } - } - break; - - case self::RECUR_MONTHLY_DATE: - $rrule = 'MD' . $this->recurInterval . ' ' . trim($this->start->mday); - break; - - case self::RECUR_MONTHLY_WEEKDAY: - $nth_weekday = (int)($this->start->mday / 7); - if (($this->start->mday % 7) > 0) { - $nth_weekday++; - } - - $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); - $rrule = 'MP' . $this->recurInterval . ' ' . $nth_weekday . '+ ' . $vcaldays[$this->start->dayOfWeek()]; - - break; - - case self::RECUR_YEARLY_DATE: - $rrule = 'YM' . $this->recurInterval . ' ' . trim($this->start->month); - break; - - case self::RECUR_YEARLY_DAY: - $rrule = 'YD' . $this->recurInterval . ' ' . $this->start->dayOfYear(); - break; - - default: - return ''; - } - - if ($this->hasRecurEnd()) { - $recurEnd = clone $this->recurEnd; - return $rrule . ' ' . $calendar->_exportDateTime($recurEnd); - } - - return $rrule . ' #' . (int)$this->getRecurCount(); - } - - /** - * Parses an iCalendar 2.0 recurrence rule. - * - * @link http://rfc.net/rfc2445.html#s4.3.10 - * @link http://rfc.net/rfc2445.html#s4.8.5 - * @link http://www.shuchow.com/vCalAddendum.html - * - * @param string $rrule An iCalendar 2.0 conform RRULE value. - */ - public function fromRRule20($rrule) - { - $this->reset(); - - // Parse the recurrence rule into keys and values. - $rdata = array(); - $parts = explode(';', $rrule); - foreach ($parts as $part) { - $value = null; - if (strpos($part, '=')) { - list($part, $value) = explode('=', $part, 2); - } - $rdata[strtoupper($part)] = $value; - } - - if (isset($rdata['FREQ'])) { - // Always default the recurInterval to 1. - $this->setRecurInterval(isset($rdata['INTERVAL']) ? $rdata['INTERVAL'] : 1); - - $maskdays = array( - 'SU' => Horde_Date::MASK_SUNDAY, - 'MO' => Horde_Date::MASK_MONDAY, - 'TU' => Horde_Date::MASK_TUESDAY, - 'WE' => Horde_Date::MASK_WEDNESDAY, - 'TH' => Horde_Date::MASK_THURSDAY, - 'FR' => Horde_Date::MASK_FRIDAY, - 'SA' => Horde_Date::MASK_SATURDAY, - ); - - switch (strtoupper($rdata['FREQ'])) { - case 'DAILY': - $this->setRecurType(self::RECUR_DAILY); - break; - - case 'WEEKLY': - $this->setRecurType(self::RECUR_WEEKLY); - if (isset($rdata['BYDAY'])) { - $days = explode(',', $rdata['BYDAY']); - $mask = 0; - foreach ($days as $day) { - $mask |= $maskdays[$day]; - } - $this->setRecurOnDay($mask); - } else { - // Recur on the day of the week of the original - // recurrence. - $maskdays = array( - Horde_Date::DATE_SUNDAY => Horde_Date::MASK_SUNDAY, - Horde_Date::DATE_MONDAY => Horde_Date::MASK_MONDAY, - Horde_Date::DATE_TUESDAY => Horde_Date::MASK_TUESDAY, - Horde_Date::DATE_WEDNESDAY => Horde_Date::MASK_WEDNESDAY, - Horde_Date::DATE_THURSDAY => Horde_Date::MASK_THURSDAY, - Horde_Date::DATE_FRIDAY => Horde_Date::MASK_FRIDAY, - Horde_Date::DATE_SATURDAY => Horde_Date::MASK_SATURDAY); - $this->setRecurOnDay($maskdays[$this->start->dayOfWeek()]); - } - break; - - case 'MONTHLY': - if (isset($rdata['BYDAY'])) { - $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY); - if (preg_match('/(-?[1-4])([A-Z]+)/', $rdata['BYDAY'], $m)) { - $this->setRecurOnDay($maskdays[$m[2]]); - $this->setRecurNthWeekday($m[1]); - } - } else { - $this->setRecurType(self::RECUR_MONTHLY_DATE); - } - break; - - case 'YEARLY': - if (isset($rdata['BYYEARDAY'])) { - $this->setRecurType(self::RECUR_YEARLY_DAY); - } elseif (isset($rdata['BYDAY'])) { - $this->setRecurType(self::RECUR_YEARLY_WEEKDAY); - if (preg_match('/(-?[1-4])([A-Z]+)/', $rdata['BYDAY'], $m)) { - $this->setRecurOnDay($maskdays[$m[2]]); - $this->setRecurNthWeekday($m[1]); - } - if ($rdata['BYMONTH']) { - $months = explode(',', $rdata['BYMONTH']); - $this->setRecurByMonth($months); - } - } else { - $this->setRecurType(self::RECUR_YEARLY_DATE); - } - break; - } - - // MUST take into account the time portion if it is present. - // See Bug: 12869 and Bug: 2813 - if (isset($rdata['UNTIL'])) { - if (preg_match('/^(\d{4})-?(\d{2})-?(\d{2})T? ?(\d{2}):?(\d{2}):?(\d{2})(?:\.\d+)?(Z?)$/', $rdata['UNTIL'], $parts)) { - $until = new Horde_Date($rdata['UNTIL'], 'UTC'); - $until->setTimezone($this->start->timezone); - } else { - list($year, $month, $mday) = sscanf($rdata['UNTIL'], - '%04d%02d%02d'); - $until = new Horde_Date( - array('year' => $year, - 'month' => $month, - 'mday' => $mday + 1), - $this->start->timezone - ); - } - $this->setRecurEnd($until); - } - if (isset($rdata['COUNT'])) { - $this->setRecurCount($rdata['COUNT']); - } - } else { - // No recurrence data - event does not recur. - $this->setRecurType(self::RECUR_NONE); - } - } - - /** - * Creates an iCalendar 2.0 recurrence rule. - * - * @link http://rfc.net/rfc2445.html#s4.3.10 - * @link http://rfc.net/rfc2445.html#s4.8.5 - * @link http://www.shuchow.com/vCalAddendum.html - * - * @param Horde_Icalendar $calendar A Horde_Icalendar object instance. - * - * @return string An iCalendar 2.0 conform RRULE value. - */ - public function toRRule20($calendar) - { - switch ($this->recurType) { - case self::RECUR_NONE: - return ''; - - case self::RECUR_DAILY: - $rrule = 'FREQ=DAILY;INTERVAL=' . $this->recurInterval; - break; - - case self::RECUR_WEEKLY: - $rrule = 'FREQ=WEEKLY;INTERVAL=' . $this->recurInterval; - $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); - - for ($i = $flag = 0; $i <= 7; ++$i) { - if ($this->recurOnDay(pow(2, $i))) { - if ($flag == 0) { - $rrule .= ';BYDAY='; - $flag = 1; - } else { - $rrule .= ','; - } - $rrule .= $vcaldays[$i]; - } - } - break; - - case self::RECUR_MONTHLY_DATE: - $rrule = 'FREQ=MONTHLY;INTERVAL=' . $this->recurInterval; - break; - - case self::RECUR_MONTHLY_WEEKDAY: - if (isset($this->recurNthDay)) { - $nth_weekday = $this->recurNthDay; - $day_of_week = log($this->recurData, 2); - } else { - $day_of_week = $this->start->dayOfWeek(); - $nth_weekday = (int)($this->start->mday / 7); - if (($this->start->mday % 7) > 0) { - $nth_weekday++; - } - } - $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); - $rrule = 'FREQ=MONTHLY;INTERVAL=' . $this->recurInterval - . ';BYDAY=' . $nth_weekday . $vcaldays[$day_of_week]; - break; - - case self::RECUR_YEARLY_DATE: - $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval; - break; - - case self::RECUR_YEARLY_DAY: - $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval - . ';BYYEARDAY=' . $this->start->dayOfYear(); - break; - - case self::RECUR_YEARLY_WEEKDAY: - if (isset($this->recurNthDay)) { - $nth_weekday = $this->recurNthDay; - $day_of_week = log($this->recurData, 2); - } else { - $day_of_week = $this->start->dayOfWeek(); - $nth_weekday = (int)($this->start->mday / 7); - if (($this->start->mday % 7) > 0) { - $nth_weekday++; - } - } - $months = !empty($this->recurMonths) ? join(',', $this->recurMonths) : $this->start->month; - $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); - $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval - . ';BYDAY=' - . $nth_weekday - . $vcaldays[$day_of_week] - . ';BYMONTH=' . $this->start->month; - break; - } - - if ($this->hasRecurEnd()) { - $recurEnd = clone $this->recurEnd; - $rrule .= ';UNTIL=' . $calendar->_exportDateTime($recurEnd); - } - if ($count = $this->getRecurCount()) { - $rrule .= ';COUNT=' . $count; - } - return $rrule; - } - - /** - * Parses the recurrence data from a Kolab hash. - * - * @param array $hash The hash to convert. - * - * @return boolean True if the hash seemed valid, false otherwise. - */ - public function fromKolab($hash) - { - $this->reset(); - - if (!isset($hash['interval']) || !isset($hash['cycle'])) { - $this->setRecurType(self::RECUR_NONE); - return false; - } - - $this->setRecurInterval((int)$hash['interval']); - - $month2number = array( - 'january' => 1, - 'february' => 2, - 'march' => 3, - 'april' => 4, - 'may' => 5, - 'june' => 6, - 'july' => 7, - 'august' => 8, - 'september' => 9, - 'october' => 10, - 'november' => 11, - 'december' => 12, - ); - - $parse_day = false; - $set_daymask = false; - $update_month = false; - $update_daynumber = false; - $update_weekday = false; - $nth_weekday = -1; - - switch ($hash['cycle']) { - case 'daily': - $this->setRecurType(self::RECUR_DAILY); - break; - - case 'weekly': - $this->setRecurType(self::RECUR_WEEKLY); - $parse_day = true; - $set_daymask = true; - break; - - case 'monthly': - if (!isset($hash['daynumber'])) { - $this->setRecurType(self::RECUR_NONE); - return false; - } - - switch ($hash['type']) { - case 'daynumber': - $this->setRecurType(self::RECUR_MONTHLY_DATE); - $update_daynumber = true; - break; - - case 'weekday': - $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY); - $this->setRecurNthWeekday($hash['daynumber']); - $parse_day = true; - $set_daymask = true; - break; - } - break; - - case 'yearly': - if (!isset($hash['type'])) { - $this->setRecurType(self::RECUR_NONE); - return false; - } - - switch ($hash['type']) { - case 'monthday': - $this->setRecurType(self::RECUR_YEARLY_DATE); - $update_month = true; - $update_daynumber = true; - break; - - case 'yearday': - if (!isset($hash['daynumber'])) { - $this->setRecurType(self::RECUR_NONE); - return false; - } - - $this->setRecurType(self::RECUR_YEARLY_DAY); - // Start counting days in January. - $hash['month'] = 'january'; - $update_month = true; - $update_daynumber = true; - break; - - case 'weekday': - if (!isset($hash['daynumber'])) { - $this->setRecurType(self::RECUR_NONE); - return false; - } - - $this->setRecurType(self::RECUR_YEARLY_WEEKDAY); - $this->setRecurNthWeekday($hash['daynumber']); - $parse_day = true; - $set_daymask = true; - - if ($hash['month'] && isset($month2number[$hash['month']])) { - $this->setRecurByMonth($month2number[$hash['month']]); - } - break; - } - } - - if (isset($hash['range-type']) && isset($hash['range'])) { - switch ($hash['range-type']) { - case 'number': - $this->setRecurCount((int)$hash['range']); - break; - - case 'date': - $recur_end = new Horde_Date($hash['range']); - $recur_end->hour = 23; - $recur_end->min = 59; - $recur_end->sec = 59; - $this->setRecurEnd($recur_end); - break; - } - } - - // Need to parse ? - $last_found_day = -1; - if ($parse_day) { - if (!isset($hash['day'])) { - $this->setRecurType(self::RECUR_NONE); - return false; - } - - $mask = 0; - $bits = array( - 'monday' => Horde_Date::MASK_MONDAY, - 'tuesday' => Horde_Date::MASK_TUESDAY, - 'wednesday' => Horde_Date::MASK_WEDNESDAY, - 'thursday' => Horde_Date::MASK_THURSDAY, - 'friday' => Horde_Date::MASK_FRIDAY, - 'saturday' => Horde_Date::MASK_SATURDAY, - 'sunday' => Horde_Date::MASK_SUNDAY, - ); - $days = array( - 'monday' => Horde_Date::DATE_MONDAY, - 'tuesday' => Horde_Date::DATE_TUESDAY, - 'wednesday' => Horde_Date::DATE_WEDNESDAY, - 'thursday' => Horde_Date::DATE_THURSDAY, - 'friday' => Horde_Date::DATE_FRIDAY, - 'saturday' => Horde_Date::DATE_SATURDAY, - 'sunday' => Horde_Date::DATE_SUNDAY, - ); - - foreach ($hash['day'] as $day) { - // Validity check. - if (empty($day) || !isset($bits[$day])) { - continue; - } - - $mask |= $bits[$day]; - $last_found_day = $days[$day]; - } - - if ($set_daymask) { - $this->setRecurOnDay($mask); - } - } - - if ($update_month || $update_daynumber || $update_weekday) { - if ($update_month) { - if (isset($month2number[$hash['month']])) { - $this->start->month = $month2number[$hash['month']]; - } - } - - if ($update_daynumber) { - if (!isset($hash['daynumber'])) { - $this->setRecurType(self::RECUR_NONE); - return false; - } - - $this->start->mday = $hash['daynumber']; - } - - if ($update_weekday) { - $this->setNthWeekday($nth_weekday); - } - } - - // Exceptions. - if (isset($hash['exclusion'])) { - foreach ($hash['exclusion'] as $exception) { - if ($exception instanceof DateTime) { - $this->exceptions[] = $exception->format('Ymd'); - } - } - } - - if (isset($hash['complete'])) { - foreach ($hash['complete'] as $completion) { - if ($exception instanceof DateTime) { - $this->completions[] = $completion->format('Ymd'); - } - } - } - - return true; - } - - /** - * Export this object into a Kolab hash. - * - * @return array The recurrence hash. - */ - public function toKolab() - { - if ($this->getRecurType() == self::RECUR_NONE) { - return array(); - } - - $day2number = array( - 0 => 'sunday', - 1 => 'monday', - 2 => 'tuesday', - 3 => 'wednesday', - 4 => 'thursday', - 5 => 'friday', - 6 => 'saturday' - ); - $month2number = array( - 1 => 'january', - 2 => 'february', - 3 => 'march', - 4 => 'april', - 5 => 'may', - 6 => 'june', - 7 => 'july', - 8 => 'august', - 9 => 'september', - 10 => 'october', - 11 => 'november', - 12 => 'december' - ); - - $hash = array('interval' => $this->getRecurInterval()); - $start = $this->getRecurStart(); - - switch ($this->getRecurType()) { - case self::RECUR_DAILY: - $hash['cycle'] = 'daily'; - break; - - case self::RECUR_WEEKLY: - $hash['cycle'] = 'weekly'; - $bits = array( - 'monday' => Horde_Date::MASK_MONDAY, - 'tuesday' => Horde_Date::MASK_TUESDAY, - 'wednesday' => Horde_Date::MASK_WEDNESDAY, - 'thursday' => Horde_Date::MASK_THURSDAY, - 'friday' => Horde_Date::MASK_FRIDAY, - 'saturday' => Horde_Date::MASK_SATURDAY, - 'sunday' => Horde_Date::MASK_SUNDAY, - ); - $days = array(); - foreach ($bits as $name => $bit) { - if ($this->recurOnDay($bit)) { - $days[] = $name; - } - } - $hash['day'] = $days; - break; - - case self::RECUR_MONTHLY_DATE: - $hash['cycle'] = 'monthly'; - $hash['type'] = 'daynumber'; - $hash['daynumber'] = $start->mday; - break; - - case self::RECUR_MONTHLY_WEEKDAY: - $hash['cycle'] = 'monthly'; - $hash['type'] = 'weekday'; - $hash['daynumber'] = $start->weekOfMonth(); - $hash['day'] = array ($day2number[$start->dayOfWeek()]); - break; - - case self::RECUR_YEARLY_DATE: - $hash['cycle'] = 'yearly'; - $hash['type'] = 'monthday'; - $hash['daynumber'] = $start->mday; - $hash['month'] = $month2number[$start->month]; - break; - - case self::RECUR_YEARLY_DAY: - $hash['cycle'] = 'yearly'; - $hash['type'] = 'yearday'; - $hash['daynumber'] = $start->dayOfYear(); - break; - - case self::RECUR_YEARLY_WEEKDAY: - $hash['cycle'] = 'yearly'; - $hash['type'] = 'weekday'; - $hash['daynumber'] = $start->weekOfMonth(); - $hash['day'] = array ($day2number[$start->dayOfWeek()]); - $hash['month'] = $month2number[$start->month]; - } - - if ($this->hasRecurCount()) { - $hash['range-type'] = 'number'; - $hash['range'] = $this->getRecurCount(); - } elseif ($this->hasRecurEnd()) { - $date = $this->getRecurEnd(); - $hash['range-type'] = 'date'; - $hash['range'] = $date->toDateTime(); - } else { - $hash['range-type'] = 'none'; - $hash['range'] = ''; - } - - // Recurrence exceptions - $hash['exclusion'] = $hash['complete'] = array(); - foreach ($this->exceptions as $exception) { - $hash['exclusion'][] = new DateTime($exception); - } - foreach ($this->completions as $completionexception) { - $hash['complete'][] = new DateTime($completionexception); - } - - return $hash; - } - - /** - * Returns a simple object suitable for json transport representing this - * object. - * - * Possible properties are: - * - t: type - * - i: interval - * - e: end date - * - c: count - * - d: data - * - co: completions - * - ex: exceptions - * - * @return object A simple object. - */ - public function toJson() - { - $json = new stdClass; - $json->t = $this->recurType; - $json->i = $this->recurInterval; - if ($this->hasRecurEnd()) { - $json->e = $this->recurEnd->toJson(); - } - if ($this->recurCount) { - $json->c = $this->recurCount; - } - if ($this->recurData) { - $json->d = $this->recurData; - } - if ($this->completions) { - $json->co = $this->completions; - } - if ($this->exceptions) { - $json->ex = $this->exceptions; - } - return $json; - } - -} diff --git a/plugins/libcalendaring/lib/libcalendaring_recurrence.php b/plugins/libcalendaring/lib/libcalendaring_recurrence.php index b62ba42f..4aca2861 100644 --- a/plugins/libcalendaring/lib/libcalendaring_recurrence.php +++ b/plugins/libcalendaring/lib/libcalendaring_recurrence.php @@ -1,253 +1,278 @@ + * @author Aleksander Machniak + * Copyright (C) 2012-2022, Apheleia IT AG * * 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 . */ class libcalendaring_recurrence { protected $lib; protected $start; - protected $next; protected $engine; protected $recurrence; protected $dateonly = false; - protected $hour = 0; + protected $event; + protected $duration; /** * Default constructor * - * @param calendar The calendar plugin instance + * @param libcalendaring $lib The libcalendaring plugin instance + * @param array $event The event object to operate on */ - function __construct($lib) + function __construct($lib, $event = null) { - // 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; + $this->event = $event; + + if (!empty($event)) { + if (!empty($event['start']) && is_object($event['start']) + && !empty($event['end']) && is_object($event['end']) + ) { + $this->duration = $event['start']->diff($event['end']); + } + + $event['start']->_dateonly = !empty($event['allday']); - $this->lib = $lib; + $this->init($event['recurrence'], $event['start']); + } } /** * Initialize recurrence engine * * @param array The recurrence properties * @param DateTime The recurrence start date */ - public function init($recurrence, $start = null) + public function init($recurrence, $start) { + $this->start = $start; + $this->dateonly = !empty($start->_dateonly); $this->recurrence = $recurrence; - $this->engine = new Horde_Date_Recurrence($start); - $this->engine->fromRRule20(libcalendaring::to_rrule($recurrence)); + $event = [ + 'uid' => '1', + 'allday' => $this->dateonly, + 'recurrence' => $recurrence, + 'start' => $start, + // TODO: END/DURATION ??? + // TODO: moved occurrences ??? + ]; - $this->set_start($start); + $vcalendar = new libcalendaring_vcalendar($this->lib->timezone); - if (!empty($recurrence['EXDATE'])) { - foreach ((array) $recurrence['EXDATE'] as $exdate) { - if ($exdate instanceof DateTimeInterface) { - $this->engine->addException($exdate->format('Y'), $exdate->format('n'), $exdate->format('j')); - } - } - } - if (!empty($recurrence['RDATE'])) { - foreach ((array) $recurrence['RDATE'] as $rdate) { - if ($rdate instanceof DateTimeInterface) { - $this->engine->addRDate($rdate->format('Y'), $rdate->format('n'), $rdate->format('j')); - } - } - } + $ve = $vcalendar->toSabreComponent($event); + + $this->engine = new EventIterator($ve, null, $this->lib->timezone); } /** - * Setter for (new) recurrence start date + * Get date/time of the next occurence of this event, and push the iterator. * - * @param DateTime The recurrence start date + * @return DateTime|false object or False if recurrence ended */ - public function set_start($start) + public function next_start() { - $this->start = $start; - $this->dateonly = !empty($start->_dateonly); - $this->next = new Horde_Date($start, $this->lib->timezone->getName()); - $this->hour = $this->next->hour; - $this->engine->setRecurStart($this->next); + try { + $this->engine->next(); + $current = $this->engine->getDtStart(); + } + catch (Exception $e) { + // do nothing + } + + return $current ? $this->toDateTime($current) : false; } /** - * Get date/time of the next occurence of this event + * Get the next recurring instance of this event * - * @return DateTime|false object or False if recurrence ended + * @return array|false Array with event properties or False if recurrence ended */ - public function next() + public function next_instance() { - $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; - } + if ($next_start = $this->next_start()) { + $next = $this->event; + $next['start'] = $next_start; - // fix time for all-day events - if ($this->dateonly) { - $next->hour = $this->hour; - $next->min = 0; + if ($this->duration) { + $next['end'] = clone $next_start; + $next['end']->add($this->duration); } - $this->next = $next; + $next['recurrence_date'] = clone $next_start; + $next['_instance'] = libcalendaring::recurrence_instance_identifier($next, !empty($this->event['allday'])); + + unset($next['_formatobj']); - $time = $this->toDateTime($next); + return $next; } - return $time; + return false; } /** - * Get the end date of the occurence of this recurrence cycle + * Get the date of the end of the last occurrence of this recurrence cycle * - * @return DateTime|bool End datetime of the last occurence or False if recurrence exceeds limit + * @return DateTime|false End datetime of the last occurrence or False if there's no end date */ public function end() { // recurrence end date is given - if ($this->recurrence['UNTIL'] instanceof DateTimeInterface) { + if (isset($this->recurrence['UNTIL']) && $this->recurrence['UNTIL'] instanceof DateTimeInterface) { return $this->recurrence['UNTIL']; } - // take the last RDATE entry if set - if (is_array($this->recurrence['RDATE']) && !empty($this->recurrence['RDATE'])) { - $last = end($this->recurrence['RDATE']); - if ($last instanceof DateTimeInterface) { - return $last; + if (!$this->engine->isInfinite()) { + // run through all items till we reach the end + try { + foreach ($this->engine as $end) { + // do nothing + } } - } - - // 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++; + catch (Exception $e) { + // do nothing } } + else if (isset($this->event['end']) && $this->event['end'] instanceof DateTimeInterface) { + // determine a reasonable end date if none given + $end = clone $this->event['end']; + $end->add(new DateInterval('P100Y')); + } - return $last; + return isset($end) ? $this->toDateTime($end, false) : false; } /** * Find date/time of the first occurrence (excluding start date) + * + * @return DateTime|null First occurrence */ 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; + $start = clone $this->start; + $interval = $this->recurrence['INTERVAL'] ?? 1; + $freq = $this->recurrence['FREQ'] ?? null; - switch ($frequency) { + switch ($freq) { 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; + case 'DAILY': + if (!empty($this->recurrence['BYMONTH'])) { + break; + } + default: return $start; } - $r = $this->recurrence; - $r['INTERVAL'] = $interval; - if (!empty($r['COUNT'])) { + $recurrence = $this->recurrence; + + if (!empty($recurrence['COUNT'])) { // Increase count so we do not stop the loop to early - $r['COUNT'] += 100; + $recurrence['COUNT'] += 100; } // Create recurrence that starts in the past - $recurrence = new self($this->lib); - $recurrence->init($r, $start); + $self = new self($this->lib); + $self->init($recurrence, $start); + + // TODO: This method does not work the same way as the kolab_date_recurrence based on + // kolabcalendaring. I.e. if an event start date does not match the recurrence rule + // it will be returned, kolab_date_recurrence will return the next occurrence in such a case + // which is the intended result of this function. + // See some commented out test cases in tests/RecurrenceTest.php // find the first occurrence $found = false; - while ($next = $recurrence->next()) { + while ($next = $self->next_start()) { $start = $next; - if ($next >= $orig_start) { + if ($next >= $this->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); + rcube::raise_error( + [ + 'file' => __FILE__, 'line' => __LINE__, + 'message' => sprintf("Failed to find a first occurrence. Start: %s, Recurrence: %s", + $this->start->format(DateTime::ISO8601), json_encode($recurrence)), + ], + true + ); return null; } - $start = $this->toDateTime($start); - - return $start; + return $this->toDateTime($start); } - private function toDateTime($date) + /** + * Convert any DateTime into libcalendaring_datetime + */ + protected function toDateTime($date, $useStart = true) { - if ($date Instanceof Horde_Date) { - $date = $date->toDateTime(); - } - if ($date instanceof DateTimeInterface) { $date = libcalendaring_datetime::createFromFormat( 'Y-m-d\\TH:i:s', $date->format('Y-m-d\\TH:i:s'), - $date->getTimezone() + // Sabre will loose timezone on all-day events, use the event start's timezone + $this->start->getTimezone() ); } $date->_dateonly = $this->dateonly; + if ($useStart && $this->dateonly) { + // Sabre sets time to 00:00:00 for all-day events, + // let's copy the time from the event's start + $date->setTime((int) $this->start->format('H'), (int) $this->start->format('i'), (int) $this->start->format('s')); + } + return $date; } } diff --git a/plugins/libcalendaring/lib/libcalendaring_vcalendar.php b/plugins/libcalendaring/lib/libcalendaring_vcalendar.php index c88fe2cc..b801981b 100644 --- a/plugins/libcalendaring/lib/libcalendaring_vcalendar.php +++ b/plugins/libcalendaring/lib/libcalendaring_vcalendar.php @@ -1,1536 +1,1556 @@ * * Copyright (C) 2013-2015, Kolab Systems AG * * 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 . */ use \Sabre\VObject; use \Sabre\VObject\DateTimeParser; /** * Class to parse and build vCalendar (iCalendar) files * * Uses the Sabre VObject library, version 3.x. * */ class libcalendaring_vcalendar implements Iterator { private $timezone; private $attach_uri = null; private $prodid = '-//Roundcube libcalendaring//Sabre//Sabre VObject//EN'; private $type_component_map = array('event' => 'VEVENT', 'task' => 'VTODO'); private $attendee_keymap = array( 'name' => 'CN', 'status' => 'PARTSTAT', 'role' => 'ROLE', 'cutype' => 'CUTYPE', 'rsvp' => 'RSVP', 'delegated-from' => 'DELEGATED-FROM', 'delegated-to' => 'DELEGATED-TO', 'schedule-status' => 'SCHEDULE-STATUS', 'schedule-agent' => 'SCHEDULE-AGENT', 'sent-by' => 'SENT-BY', ); private $organizer_keymap = array( 'name' => 'CN', 'schedule-status' => 'SCHEDULE-STATUS', 'schedule-agent' => 'SCHEDULE-AGENT', 'sent-by' => 'SENT-BY', ); private $iteratorkey = 0; private $charset; private $forward_exceptions; private $vhead; private $fp; private $vtimezones = array(); public $method; public $agent = ''; public $objects = array(); public $freebusy = array(); /** * Default constructor */ function __construct($tz = null) { $this->timezone = $tz; $this->prodid = '-//Roundcube libcalendaring ' . RCUBE_VERSION . '//Sabre//Sabre VObject ' . VObject\Version::VERSION . '//EN'; } /** * Setter for timezone information */ public function set_timezone($tz) { $this->timezone = $tz; } /** * Setter for URI template for attachment links */ public function set_attach_uri($uri) { $this->attach_uri = $uri; } /** * Setter for a custom PRODID attribute */ public function set_prodid($prodid) { $this->prodid = $prodid; } /** * Setter for a user-agent string to tweak input/output accordingly */ public function set_agent($agent) { $this->agent = $agent; } /** * Free resources by clearing member vars */ public function reset() { $this->vhead = ''; $this->method = ''; $this->objects = array(); $this->freebusy = array(); $this->vtimezones = array(); $this->iteratorkey = 0; if ($this->fp) { fclose($this->fp); $this->fp = null; } } /** * Import events from iCalendar format * * @param string vCalendar input * @param string Input charset (from envelope) * @param boolean True if parsing exceptions should be forwarded to the caller * @return array List of events extracted from the input */ public function import($vcal, $charset = 'UTF-8', $forward_exceptions = false, $memcheck = true) { // TODO: convert charset to UTF-8 if other try { // estimate the memory usage and try to avoid fatal errors when allowed memory gets exhausted if ($memcheck) { $count = substr_count($vcal, 'BEGIN:VEVENT') + substr_count($vcal, 'BEGIN:VTODO'); $expected_memory = $count * 70*1024; // assume ~ 70K per event (empirically determined) if (!rcube_utils::mem_check($expected_memory)) { throw new Exception("iCal file too big"); } } $vobject = VObject\Reader::read($vcal, VObject\Reader::OPTION_FORGIVING | VObject\Reader::OPTION_IGNORE_INVALID_LINES); if ($vobject) return $this->import_from_vobject($vobject); } catch (Exception $e) { if ($forward_exceptions) { throw $e; } else { rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "iCal data parse error: " . $e->getMessage()), true, false); } } return array(); } /** * Read iCalendar events from a file * * @param string File path to read from * @param string Input charset (from envelope) * @param boolean True if parsing exceptions should be forwarded to the caller * @return array List of events extracted from the file */ public function import_from_file($filepath, $charset = 'UTF-8', $forward_exceptions = false) { if ($this->fopen($filepath, $charset, $forward_exceptions)) { while ($this->_parse_next(false)) { // nop } fclose($this->fp); $this->fp = null; } return $this->objects; } /** * Open a file to read iCalendar events sequentially * * @param string File path to read from * @param string Input charset (from envelope) * @param boolean True if parsing exceptions should be forwarded to the caller * @return boolean True if file contents are considered valid */ public function fopen($filepath, $charset = 'UTF-8', $forward_exceptions = false) { $this->reset(); // just to be sure... @ini_set('auto_detect_line_endings', true); $this->charset = $charset; $this->forward_exceptions = $forward_exceptions; $this->fp = fopen($filepath, 'r'); // check file content first $begin = fread($this->fp, 1024); if (!preg_match('/BEGIN:VCALENDAR/i', $begin)) { return false; } fseek($this->fp, 0); return $this->_parse_next(); } /** * Parse the next event/todo/freebusy object from the input file */ private function _parse_next($reset = true) { if ($reset) { $this->iteratorkey = 0; $this->objects = array(); $this->freebusy = array(); } $next = $this->_next_component(); $buffer = $next; // load the next component(s) too, as they could contain recurrence exceptions while (preg_match('/(RRULE|RECURRENCE-ID)[:;]/i', $next)) { $next = $this->_next_component(); $buffer .= $next; } // parse the vevent block surrounded with the vcalendar heading if (strlen($buffer) && preg_match('/BEGIN:(VEVENT|VTODO|VFREEBUSY)/i', $buffer)) { try { $this->import($this->vhead . $buffer . "END:VCALENDAR", $this->charset, true, false); } catch (Exception $e) { if ($this->forward_exceptions) { throw new VObject\ParseException($e->getMessage() . " in\n" . $buffer); } else { // write the failing section to error log rcube::raise_error(array( 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => $e->getMessage() . " in\n" . $buffer), true, false); } // advance to next return $this->_parse_next($reset); } return count($this->objects) > 0; } return false; } /** * Helper method to read the next calendar component from the file */ private function _next_component() { $buffer = ''; $vcalendar_head = false; while (($line = fgets($this->fp, 1024)) !== false) { // ignore END:VCALENDAR lines if (preg_match('/END:VCALENDAR/i', $line)) { continue; } // read vcalendar header (with timezone defintion) if (preg_match('/BEGIN:VCALENDAR/i', $line)) { $this->vhead = ''; $vcalendar_head = true; } // end of VCALENDAR header part if ($vcalendar_head && preg_match('/BEGIN:(VEVENT|VTODO|VFREEBUSY)/i', $line)) { $vcalendar_head = false; } if ($vcalendar_head) { $this->vhead .= $line; } else { $buffer .= $line; if (preg_match('/END:(VEVENT|VTODO|VFREEBUSY)/i', $line)) { break; } } } return $buffer; } /** * Import objects from an already parsed Sabre\VObject\Component object * * @param object Sabre\VObject\Component to read from * @return array List of events extracted from the file */ public function import_from_vobject($vobject) { $seen = array(); $exceptions = array(); if ($vobject->name == 'VCALENDAR') { $this->method = strval($vobject->METHOD); $this->agent = strval($vobject->PRODID); foreach ($vobject->getComponents() as $ve) { if ($ve->name == 'VEVENT' || $ve->name == 'VTODO') { // convert to hash array representation $object = $this->_to_array($ve); // temporarily store this as exception if (!empty($object['recurrence_date'])) { $exceptions[] = $object; } else if (empty($seen[$object['uid']])) { $seen[$object['uid']] = true; $this->objects[] = $object; } } else if ($ve->name == 'VFREEBUSY') { $this->objects[] = $this->_parse_freebusy($ve); } } // add exceptions to the according master events foreach ($exceptions as $exception) { $uid = $exception['uid']; // make this exception the master if (empty($seen[$uid])) { $seen[$uid] = true; $this->objects[] = $exception; } else { foreach ($this->objects as $i => $object) { // add as exception to existing entry with a matching UID if ($object['uid'] == $uid) { $this->objects[$i]['exceptions'][] = $exception; if (!empty($object['recurrence'])) { $this->objects[$i]['recurrence']['EXCEPTIONS'] = &$this->objects[$i]['exceptions']; } break; } } } } } return $this->objects; } /** * Getter for free-busy periods */ public function get_busy_periods() { $out = array(); foreach ((array)$this->freebusy['periods'] as $period) { if ($period[2] != 'FREE') { $out[] = $period; } } return $out; } /** * Helper method to determine whether the connected client is an Apple device */ private function is_apple() { return stripos($this->agent, 'Apple') !== false || stripos($this->agent, 'Mac OS X') !== false || stripos($this->agent, 'iOS/') !== false; } /** * Convert the given VEvent object to a libkolab compatible array representation * * @param object Vevent object to convert * @return array Hash array with object properties */ private function _to_array($ve) { $event = array( 'uid' => self::convert_string($ve->UID), 'title' => self::convert_string($ve->SUMMARY), '_type' => $ve->name == 'VTODO' ? 'task' : 'event', // set defaults 'priority' => 0, 'attendees' => array(), 'x-custom' => array(), ); // Catch possible exceptions when date is invalid (Bug #2144) // We can skip these fields, they aren't critical foreach (array('CREATED' => 'created', 'LAST-MODIFIED' => 'changed', 'DTSTAMP' => 'changed') as $attr => $field) { try { if (empty($event[$field]) && !empty($ve->{$attr})) { $event[$field] = $ve->{$attr}->getDateTime(); } } catch (Exception $e) {} } // map other attributes to internal fields foreach ($ve->children() as $prop) { if (!($prop instanceof VObject\Property)) continue; $value = strval($prop); switch ($prop->name) { case 'DTSTART': case 'DTEND': case 'DUE': $propmap = array('DTSTART' => 'start', 'DTEND' => 'end', 'DUE' => 'due'); $event[$propmap[$prop->name]] = self::convert_datetime($prop); break; case 'TRANSP': $event['free_busy'] = strval($prop) == 'TRANSPARENT' ? 'free' : 'busy'; break; case 'STATUS': if ($value == 'TENTATIVE') $event['free_busy'] = 'tentative'; else if ($value == 'CANCELLED') $event['cancelled'] = true; else if ($value == 'COMPLETED') $event['complete'] = 100; $event['status'] = $value; break; case 'COMPLETED': if (self::convert_datetime($prop)) { $event['status'] = 'COMPLETED'; $event['complete'] = 100; } break; case 'PRIORITY': if (is_numeric($value)) $event['priority'] = $value; break; case 'RRULE': $params = !empty($event['recurrence']) && is_array($event['recurrence']) ? $event['recurrence'] : array(); // parse recurrence rule attributes foreach ($prop->getParts() as $k => $v) { $params[strtoupper($k)] = is_array($v) ? implode(',', $v) : $v; } if (!empty($params['UNTIL'])) { $params['UNTIL'] = date_create($params['UNTIL']); } if (empty($params['INTERVAL'])) { $params['INTERVAL'] = 1; } $event['recurrence'] = array_filter($params); break; case 'EXDATE': if (!empty($value)) { $exdates = array_map(function($_) { return is_array($_) ? $_[0] : $_; }, self::convert_datetime($prop, true)); if (!empty($event['recurrence']['EXDATE'])) { $event['recurrence']['EXDATE'] = array_merge($event['recurrence']['EXDATE'], $exdates); } else { $event['recurrence']['EXDATE'] = $exdates; } } break; case 'RDATE': if (!empty($value)) { $rdates = array_map(function($_) { return is_array($_) ? $_[0] : $_; }, self::convert_datetime($prop, true)); if (!empty($event['recurrence']['RDATE'])) { $event['recurrence']['RDATE'] = array_merge($event['recurrence']['RDATE'], $rdates); } else { $event['recurrence']['RDATE'] = $rdates; } } break; case 'RECURRENCE-ID': $event['recurrence_date'] = self::convert_datetime($prop); if ($prop->offsetGet('RANGE') == 'THISANDFUTURE' || $prop->offsetGet('THISANDFUTURE') !== null) { $event['thisandfuture'] = true; } break; case 'RELATED-TO': $reltype = $prop->offsetGet('RELTYPE'); if ($reltype == 'PARENT' || $reltype === null) { $event['parent_id'] = $value; } break; case 'SEQUENCE': $event['sequence'] = intval($value); break; case 'PERCENT-COMPLETE': $event['complete'] = intval($value); break; case 'LOCATION': case 'DESCRIPTION': case 'URL': case 'COMMENT': $event[strtolower($prop->name)] = self::convert_string($prop); break; case 'CATEGORY': case 'CATEGORIES': if (!empty($event['categories'])) { $event['categories'] = array_merge((array) $event['categories'], $prop->getParts()); } else { $event['categories'] = $prop->getParts(); } break; case 'X-MICROSOFT-CDO-BUSYSTATUS': if ($value == 'OOF') { $event['free_busy'] = 'outofoffice'; } else if (in_array($value, array('FREE', 'BUSY', 'TENTATIVE'))) { $event['free_busy'] = strtolower($value); } break; case 'ATTENDEE': case 'ORGANIZER': $params = array('RSVP' => false); foreach ($prop->parameters() as $pname => $pvalue) { switch ($pname) { case 'RSVP': $params[$pname] = strtolower($pvalue) == 'true'; break; case 'CN': $params[$pname] = self::unescape($pvalue); break; default: $params[$pname] = strval($pvalue); break; } } $attendee = self::map_keys($params, array_flip($this->attendee_keymap)); $attendee['email'] = preg_replace('!^mailto:!i', '', $value); if ($prop->name == 'ORGANIZER') { $attendee['role'] = 'ORGANIZER'; $attendee['status'] = 'ACCEPTED'; $event['organizer'] = $attendee; if (array_key_exists('schedule-agent', $attendee)) { $schedule_agent = $attendee['schedule-agent']; } } else if (empty($event['organizer']) || $attendee['email'] != $event['organizer']['email']) { $event['attendees'][] = $attendee; } break; case 'ATTACH': $params = self::parameters_array($prop); if (substr($value, 0, 4) == 'http' && !strpos($value, ':attachment:')) { $event['links'][] = $value; } else if (strlen($value) && strtoupper($params['VALUE']) == 'BINARY') { $attachment = self::map_keys($params, array('FMTTYPE' => 'mimetype', 'X-LABEL' => 'name', 'X-APPLE-FILENAME' => 'name')); $attachment['data'] = $value; $attachment['size'] = strlen($value); $event['attachments'][] = $attachment; } break; default: if (substr($prop->name, 0, 2) == 'X-') $event['x-custom'][] = array($prop->name, strval($value)); break; } } // check DURATION property if no end date is set if (empty($event['end']) && $ve->DURATION) { try { $duration = new DateInterval(strval($ve->DURATION)); $end = clone $event['start']; $end->add($duration); $event['end'] = $end; } catch (\Exception $e) { trigger_error(strval($e), E_USER_WARNING); } } // validate event dates if ($event['_type'] == 'event') { $event['allday'] = !empty($event['start']->_dateonly); // events may lack the DTEND property, set it to DTSTART (RFC5545 3.6.1) if (empty($event['end'])) { $event['end'] = clone $event['start']; } // shift end-date by one day (except Thunderbird) else if ($event['allday'] && is_object($event['end'])) { $event['end']->sub(new \DateInterval('PT23H')); } // sanity-check and fix end date if (!empty($event['end']) && $event['end'] < $event['start']) { $event['end'] = clone $event['start']; } } // make organizer part of the attendees list for compatibility reasons if (!empty($event['organizer']) && is_array($event['attendees']) && $event['_type'] == 'event') { array_unshift($event['attendees'], $event['organizer']); } // find alarms foreach ($ve->select('VALARM') as $valarm) { $action = 'DISPLAY'; $trigger = null; $alarm = array(); foreach ($valarm->children() as $prop) { $value = strval($prop); switch ($prop->name) { case 'TRIGGER': foreach ($prop->parameters as $param) { if ($param->name == 'VALUE' && $param->getValue() == 'DATE-TIME') { $trigger = '@' . $prop->getDateTime()->format('U'); $alarm['trigger'] = $prop->getDateTime(); } else if ($param->name == 'RELATED') { $alarm['related'] = $param->getValue(); } } if (!$trigger && ($values = libcalendaring::parse_alarm_value($value))) { $trigger = $values[2]; } if (empty($alarm['trigger'])) { $alarm['trigger'] = rtrim(preg_replace('/([A-Z])0[WDHMS]/', '\\1', $value), 'T'); // if all 0-values have been stripped, assume 'at time' if ($alarm['trigger'] == 'P') { $alarm['trigger'] = 'PT0S'; } } break; case 'ACTION': $action = $alarm['action'] = strtoupper($value); break; case 'SUMMARY': case 'DESCRIPTION': case 'DURATION': $alarm[strtolower($prop->name)] = self::convert_string($prop); break; case 'REPEAT': $alarm['repeat'] = intval($value); break; case 'ATTENDEE': $alarm['attendees'][] = preg_replace('!^mailto:!i', '', $value); break; case 'ATTACH': $params = self::parameters_array($prop); if (strlen($value) && (preg_match('/^[a-z]+:/', $value) || strtoupper($params['VALUE']) == 'URI')) { // we only support URI-type of attachments here $alarm['uri'] = $value; } break; } } if ($action != 'NONE') { // store first alarm in legacy property if ($trigger && empty($event['alarms'])) { $event['alarms'] = $trigger . ':' . $action; } if (!empty($alarm['trigger'])) { $event['valarms'][] = $alarm; } } } // assign current timezone to event start/end if (!empty($event['start']) && $event['start'] instanceof DateTimeInterface) { $this->_apply_timezone($event['start']); } else { unset($event['start']); } if (!empty($event['end']) && $event['end'] instanceof DateTimeInterface) { $this->_apply_timezone($event['end']); } else { unset($event['end']); } // some iTip CANCEL messages only contain the start date if (empty($event['end']) && !empty($event['start']) && $this->method == 'CANCEL') { $event['end'] = clone $event['start']; } // T2531: Remember SCHEDULE-AGENT in custom property to properly // support event updates via CalDAV when SCHEDULE-AGENT=CLIENT is used if (isset($schedule_agent)) { $event['x-custom'][] = array('SCHEDULE-AGENT', $schedule_agent); } // minimal validation if (empty($event['uid']) || ($event['_type'] == 'event' && empty($event['start']) != empty($event['end']))) { throw new VObject\ParseException('Object validation failed: missing mandatory object properties'); } return $event; } /** * Apply user timezone to DateTime object */ private function _apply_timezone(&$date) { if (empty($this->timezone)) { return; } // For date-only we'll keep the date and time intact if (!empty($date->_dateonly)) { $dt = new libcalendaring_datetime(null, $this->timezone); $dt->setDate($date->format('Y'), $date->format('n'), $date->format('j')); $dt->setTime($date->format('G'), $date->format('i'), 0); $date = $dt; } else { $date->setTimezone($this->timezone); } } /** * Parse the given vfreebusy component into an array representation */ private function _parse_freebusy($ve) { $this->freebusy = array('_type' => 'freebusy', 'periods' => array()); $seen = array(); foreach ($ve->children() as $prop) { if (!($prop instanceof VObject\Property)) continue; $value = strval($prop); switch ($prop->name) { case 'CREATED': case 'LAST-MODIFIED': case 'DTSTAMP': case 'DTSTART': case 'DTEND': $propmap = array( 'DTSTART' => 'start', 'DTEND' => 'end', 'CREATED' => 'created', 'LAST-MODIFIED' => 'changed', 'DTSTAMP' => 'changed' ); $this->freebusy[$propmap[$prop->name]] = self::convert_datetime($prop); break; case 'ORGANIZER': $this->freebusy['organizer'] = preg_replace('!^mailto:!i', '', $value); break; case 'FREEBUSY': // The freebusy component can hold more than 1 value, separated by commas. $periods = explode(',', $value); $fbtype = strval($prop['FBTYPE']) ?: 'BUSY'; // skip dupes if (!empty($seen[$value.':'.$fbtype])) { break; } $seen[$value.':'.$fbtype] = true; foreach ($periods as $period) { // Every period is formatted as [start]/[end]. The start is an // absolute UTC time, the end may be an absolute UTC time, or // duration (relative) value. list($busyStart, $busyEnd) = explode('/', $period); $busyStart = DateTimeParser::parse($busyStart); $busyEnd = DateTimeParser::parse($busyEnd); if ($busyEnd instanceof \DateInterval) { $tmp = clone $busyStart; $tmp->add($busyEnd); $busyEnd = $tmp; } if ($busyEnd && $busyEnd > $busyStart) $this->freebusy['periods'][] = array($busyStart, $busyEnd, $fbtype); } break; case 'COMMENT': $this->freebusy['comment'] = $value; } } return $this->freebusy; } /** * */ public static function convert_string($prop) { return strval($prop); } /** * */ public static function unescape($prop) { return str_replace('\,', ',', strval($prop)); } /** * Helper method to correctly interpret an all-day date value */ public static function convert_datetime($prop, $as_array = false) { if (empty($prop)) { return $as_array ? [] : null; } if ($prop instanceof VObject\Property\ICalendar\DateTime) { if (count($prop->getDateTimes()) > 1) { $dt = []; $dateonly = !$prop->hasTime(); foreach ($prop->getDateTimes() as $item) { $item = libcalendaring_datetime::createFromImmutable($item); $item->_dateonly = $dateonly; $dt[] = $item; } } else { $dt = libcalendaring_datetime::createFromImmutable($prop->getDateTime()); if (!$prop->hasTime()) { $dt->_dateonly = true; } } } else if ($prop instanceof VObject\Property\ICalendar\Period) { $dt = []; foreach ($prop->getParts() as $val) { try { list($start, $end) = explode('/', $val); $start = DateTimeParser::parseDateTime($start); // This is a duration value. if ($end[0] === 'P') { $dur = DateTimeParser::parseDuration($end); $end = clone $start; $end->add($dur); } else { $end = DateTimeParser::parseDateTime($end); } $dt[] = [libcalendaring_datetime::createFromImmutable($start), libcalendaring_datetime::createFromImmutable($end)]; } catch (Exception $e) { // ignore single date parse errors } } } else if ($prop instanceof \DateTimeInterface) { $dt = libcalendaring_datetime::createFromImmutable($prop); } // force return value to array if requested if ($as_array && !is_array($dt)) { $dt = empty($dt) ? [] : [$dt]; } return $dt; } /** * Create a Sabre\VObject\Property instance from a PHP DateTime object * * @param object VObject\Document parent node to create property for * @param string Property name * @param object DateTime * @param boolean Set as UTC date * @param boolean Set as VALUE=DATE property */ public function datetime_prop($cal, $name, $dt, $utc = false, $dateonly = null, $set_type = false) { if ($utc) { $dt->setTimeZone(new \DateTimeZone('UTC')); $is_utc = true; } else { $is_utc = ($tz = $dt->getTimezone()) && in_array($tz->getName(), array('UTC','GMT','Z')); } $is_dateonly = $dateonly === null ? !empty($dt->_dateonly) : (bool) $dateonly; $vdt = $cal->createProperty($name, $dt, null, $is_dateonly ? 'DATE' : 'DATE-TIME'); if ($is_dateonly) { $vdt['VALUE'] = 'DATE'; } else if ($set_type) { $vdt['VALUE'] = 'DATE-TIME'; } // register timezone for VTIMEZONE block if (!$is_utc && !$dateonly && $tz && ($tzname = $tz->getName())) { $ts = $dt->format('U'); if (!empty($this->vtimezones[$tzname])) { $this->vtimezones[$tzname][0] = min($this->vtimezones[$tzname][0], $ts); $this->vtimezones[$tzname][1] = max($this->vtimezones[$tzname][1], $ts); } else { $this->vtimezones[$tzname] = array($ts, $ts); } } return $vdt; } /** * Copy values from one hash array to another using a key-map */ public static function map_keys($values, $map) { $out = array(); foreach ($map as $from => $to) { if (isset($values[$from])) $out[$to] = is_array($values[$from]) ? join(',', $values[$from]) : $values[$from]; } return $out; } /** * */ private static function parameters_array($prop) { $params = array(); foreach ($prop->parameters() as $name => $value) { $params[strtoupper($name)] = strval($value); } return $params; } /** * Export events to iCalendar format * * @param array Events as array * @param string VCalendar method to advertise * @param boolean Directly send data to stdout instead of returning * @param callable Callback function to fetch attachment contents, false if no attachment export * @param boolean Add VTIMEZONE block with timezone definitions for the included events * @return string Events in iCalendar format (http://tools.ietf.org/html/rfc5545) */ public function export($objects, $method = null, $write = false, $get_attachment = false, $with_timezones = true) { $this->method = $method; // encapsulate in VCALENDAR container $vcal = new VObject\Component\VCalendar(); $vcal->VERSION = '2.0'; $vcal->PRODID = $this->prodid; $vcal->CALSCALE = 'GREGORIAN'; if (!empty($method)) { $vcal->METHOD = $method; } // write vcalendar header if ($write) { echo preg_replace('/END:VCALENDAR[\r\n]*$/m', '', $vcal->serialize()); } foreach ($objects as $object) { $this->_to_ical($object, !$write?$vcal:false, $get_attachment); } // include timezone information if ($with_timezones || !empty($method)) { foreach ($this->vtimezones as $tzid => $range) { $vt = self::get_vtimezone($tzid, $range[0], $range[1], $vcal); if (empty($vt)) { continue; // no timezone information found } if ($write) { echo $vt->serialize(); } else { $vcal->add($vt); } } } if ($write) { echo "END:VCALENDAR\r\n"; return true; } else { return $vcal->serialize(); } } + /** + * Converts internal event representation to Sabre component + * + * @param array Event + * @param callable Callback function to fetch attachment contents, false if no attachment export + * + * @return Sabre\VObject\Component\VEvent Sabre component + */ + public function toSabreComponent($object, $get_attachment = false) + { + $vcal = new VObject\Component\VCalendar(); + + $this->_to_ical($object, $vcal, $get_attachment); + + return $vcal->getBaseComponent(); + } + /** * Build a valid iCal format block from the given event * * @param array Hash array with event/task properties from libkolab * @param object VCalendar object to append event to or false for directly sending data to stdout * @param callable Callback function to fetch attachment contents, false if no attachment export * @param object RECURRENCE-ID property when serializing a recurrence exception */ private function _to_ical($event, $vcal, $get_attachment, $recurrence_id = null) { $type = !empty($event['_type']) ? $event['_type'] : 'event'; $cal = $vcal ?: new VObject\Component\VCalendar(); $ve = $cal->create($this->type_component_map[$type]); $ve->UID = $event['uid']; // set DTSTAMP according to RFC 5545, 3.8.7.2. $dtstamp = !empty($event['changed']) && empty($this->method) ? $event['changed'] : new DateTime('now', new \DateTimeZone('UTC')); $ve->DTSTAMP = $this->datetime_prop($cal, 'DTSTAMP', $dtstamp, true); // all-day events end the next day if (!empty($event['allday']) && !empty($event['end'])) { $event['end'] = clone $event['end']; $event['end']->add(new \DateInterval('P1D')); $event['end']->_dateonly = true; } if (!empty($event['created'])) { $ve->add($this->datetime_prop($cal, 'CREATED', $event['created'], true)); } if (!empty($event['changed'])) { $ve->add($this->datetime_prop($cal, 'LAST-MODIFIED', $event['changed'], true)); } if (!empty($event['start'])) { $ve->add($this->datetime_prop($cal, 'DTSTART', $event['start'], false, !empty($event['allday']))); } if (!empty($event['end'])) { $ve->add($this->datetime_prop($cal, 'DTEND', $event['end'], false, !empty($event['allday']))); } if (!empty($event['due'])) { $ve->add($this->datetime_prop($cal, 'DUE', $event['due'], false)); } // we're exporting a recurrence instance only if (!$recurrence_id && !empty($event['recurrence_date']) && $event['recurrence_date'] instanceof DateTimeInterface) { $recurrence_id = $this->datetime_prop($cal, 'RECURRENCE-ID', $event['recurrence_date'], false, !empty($event['allday'])); if (!empty($event['thisandfuture'])) { $recurrence_id->add('RANGE', 'THISANDFUTURE'); } } if ($recurrence_id) { $ve->add($recurrence_id); } - $ve->add('SUMMARY', $event['title']); + if (!empty($event['title'])) { + $ve->add('SUMMARY', $event['title']); + } if (!empty($event['location'])) { $ve->add($this->is_apple() ? new vobject_location_property($cal, 'LOCATION', $event['location']) : $cal->create('LOCATION', $event['location'])); } + if (!empty($event['description'])) { $ve->add('DESCRIPTION', strtr($event['description'], array("\r\n" => "\n", "\r" => "\n"))); // normalize line endings } if (isset($event['sequence'])) { $ve->add('SEQUENCE', $event['sequence']); } if (!empty($event['recurrence']) && !$recurrence_id) { $exdates = $rdates = null; if (isset($event['recurrence']['EXDATE'])) { $exdates = $event['recurrence']['EXDATE']; unset($event['recurrence']['EXDATE']); // don't serialize EXDATEs into RRULE value } if (isset($event['recurrence']['RDATE'])) { $rdates = $event['recurrence']['RDATE']; unset($event['recurrence']['RDATE']); // don't serialize RDATEs into RRULE value } if (!empty($event['recurrence']['FREQ'])) { $ve->add('RRULE', libcalendaring::to_rrule($event['recurrence'], !empty($event['allday']))); } // add EXDATEs each one per line (for Thunderbird Lightning) if (is_array($exdates)) { foreach ($exdates as $exdate) { if ($exdate instanceof DateTimeInterface) { $ve->add($this->datetime_prop($cal, 'EXDATE', $exdate)); } } } // add RDATEs if (is_array($rdates)) { foreach ($rdates as $rdate) { $ve->add($this->datetime_prop($cal, 'RDATE', $rdate)); } } } if (!empty($event['categories'])) { $cat = $cal->create('CATEGORIES'); $cat->setParts((array)$event['categories']); $ve->add($cat); } if (!empty($event['free_busy'])) { $ve->add('TRANSP', $event['free_busy'] == 'free' ? 'TRANSPARENT' : 'OPAQUE'); // for Outlook clients we provide the X-MICROSOFT-CDO-BUSYSTATUS property if (stripos($this->agent, 'outlook') !== false) { $ve->add('X-MICROSOFT-CDO-BUSYSTATUS', $event['free_busy'] == 'outofoffice' ? 'OOF' : strtoupper($event['free_busy'])); } } if (!empty($event['priority'])) { $ve->add('PRIORITY', $event['priority']); } if (!empty($event['cancelled'])) { $ve->add('STATUS', 'CANCELLED'); } else if (!empty($event['free_busy']) && $event['free_busy'] == 'tentative') { $ve->add('STATUS', 'TENTATIVE'); } else if (!empty($event['complete']) && $event['complete'] == 100) { $ve->add('STATUS', 'COMPLETED'); } else if (!empty($event['status'])) { $ve->add('STATUS', $event['status']); } if (!empty($event['complete'])) { $ve->add('PERCENT-COMPLETE', intval($event['complete'])); } // Apple iCal and BusyCal required the COMPLETED date to be set in order to consider a task complete if ( (!empty($event['status']) && $event['status'] == 'COMPLETED') || (!empty($event['complete']) && $event['complete'] == 100) ) { $completed = !empty($event['changed']) ? $event['changed'] : new DateTime('now - 1 hour'); $ve->add($this->datetime_prop($cal, 'COMPLETED', $completed, true)); } if (!empty($event['valarms'])) { foreach ($event['valarms'] as $alarm) { $va = $cal->createComponent('VALARM'); $va->action = $alarm['action']; if ($alarm['trigger'] instanceof DateTimeInterface) { $va->add($this->datetime_prop($cal, 'TRIGGER', $alarm['trigger'], true, null, true)); } else { $alarm_props = array(); if (!empty($alarm['related']) && strtoupper($alarm['related']) == 'END') { $alarm_props['RELATED'] = 'END'; } $va->add('TRIGGER', $alarm['trigger'], $alarm_props); } if (!empty($alarm['action']) && $alarm['action'] == 'EMAIL') { if (!empty($alarm['attendees'])) { foreach ((array) $alarm['attendees'] as $attendee) { $va->add('ATTENDEE', 'mailto:' . $attendee); } } } if (!empty($alarm['description'])) { $va->add('DESCRIPTION', $alarm['description']); } if (!empty($alarm['summary'])) { $va->add('SUMMARY', $alarm['summary']); } if (!empty($alarm['duration'])) { $va->add('DURATION', $alarm['duration']); $va->add('REPEAT', !empty($alarm['repeat']) ? intval($alarm['repeat']) : 0); } if (!empty($alarm['uri'])) { $va->add('ATTACH', $alarm['uri'], array('VALUE' => 'URI')); } $ve->add($va); } } // legacy support else if (!empty($event['alarms'])) { $va = $cal->createComponent('VALARM'); list($trigger, $va->action) = explode(':', $event['alarms']); $val = libcalendaring::parse_alarm_value($trigger); if (!empty($val[3])) { $va->add('TRIGGER', $val[3]); } else if ($val[0] instanceof DateTimeInterface) { $va->add($this->datetime_prop($cal, 'TRIGGER', $val[0], true, null, true)); } $ve->add($va); } // Find SCHEDULE-AGENT if (!empty($event['x-custom'])) { foreach ((array) $event['x-custom'] as $prop) { if ($prop[0] === 'SCHEDULE-AGENT') { $schedule_agent = $prop[1]; } } } if (!empty($event['attendees'])) { foreach ((array) $event['attendees'] as $attendee) { if ($attendee['role'] == 'ORGANIZER') { if (empty($event['organizer'])) $event['organizer'] = $attendee; } else if (!empty($attendee['email'])) { if (isset($attendee['rsvp'])) { $attendee['rsvp'] = $attendee['rsvp'] ? 'TRUE' : null; } $mailto = $attendee['email']; $attendee = array_filter(self::map_keys($attendee, $this->attendee_keymap)); if (isset($schedule_agent) && !isset($attendee['SCHEDULE-AGENT'])) { $attendee['SCHEDULE-AGENT'] = $schedule_agent; } $ve->add('ATTENDEE', 'mailto:' . $mailto, $attendee); } } } if (!empty($event['organizer'])) { $organizer = array_filter(self::map_keys($event['organizer'], $this->organizer_keymap)); if (isset($schedule_agent) && !isset($organizer['SCHEDULE-AGENT'])) { $organizer['SCHEDULE-AGENT'] = $schedule_agent; } $ve->add('ORGANIZER', 'mailto:' . $event['organizer']['email'], $organizer); } if (!empty($event['url'])) { foreach ((array) $event['url'] as $url) { if (!empty($url)) { $ve->add('URL', $url); } } } if (!empty($event['parent_id'])) { $ve->add('RELATED-TO', $event['parent_id'], array('RELTYPE' => 'PARENT')); } if (!empty($event['comment'])) { $ve->add('COMMENT', $event['comment']); } $memory_limit = parse_bytes(ini_get('memory_limit')); // export attachments if (!empty($event['attachments'])) { foreach ((array)$event['attachments'] as $attach) { // check available memory and skip attachment export if we can't buffer it // @todo: use rcube_utils::mem_check() if (is_callable($get_attachment) && $memory_limit > 0 && ($memory_used = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024) && $attach['size'] && $memory_used + $attach['size'] * 3 > $memory_limit) { continue; } // embed attachments using the given callback function if (is_callable($get_attachment) && ($data = call_user_func($get_attachment, $attach['id'], $event))) { // embed attachments for iCal $ve->add('ATTACH', $data, array_filter(array('VALUE' => 'BINARY', 'ENCODING' => 'BASE64', 'FMTTYPE' => $attach['mimetype'], 'X-LABEL' => $attach['name']))); unset($data); // attempt to free memory } // list attachments as absolute URIs else if (!empty($this->attach_uri)) { $ve->add('ATTACH', strtr($this->attach_uri, array( '{{id}}' => urlencode($attach['id']), '{{name}}' => urlencode($attach['name']), '{{mimetype}}' => urlencode($attach['mimetype']), )), array('FMTTYPE' => $attach['mimetype'], 'VALUE' => 'URI')); } } } if (!empty($event['links'])) { foreach ((array) $event['links'] as $uri) { $ve->add('ATTACH', $uri); } } // add custom properties if (!empty($event['x-custom'])) { foreach ((array) $event['x-custom'] as $prop) { $ve->add($prop[0], $prop[1]); } } // append to vcalendar container if ($vcal) { $vcal->add($ve); } else { // serialize and send to stdout echo $ve->serialize(); } // append recurrence exceptions if (!empty($event['recurrence']) && !empty($event['recurrence']['EXCEPTIONS'])) { foreach ($event['recurrence']['EXCEPTIONS'] as $ex) { $exdate = !empty($ex['recurrence_date']) ? $ex['recurrence_date'] : $ex['start']; $recurrence_id = $this->datetime_prop($cal, 'RECURRENCE-ID', $exdate, false, !empty($event['allday'])); if (!empty($ex['thisandfuture'])) { $recurrence_id->add('RANGE', 'THISANDFUTURE'); } $ex['uid'] = $ve->UID; $this->_to_ical($ex, $vcal, $get_attachment, $recurrence_id); } } } /** * Returns a VTIMEZONE component for a Olson timezone identifier * with daylight transitions covering the given date range. * * @param string Timezone ID as used in PHP's Date functions * @param integer Unix timestamp with first date/time in this timezone * @param integer Unix timestap with last date/time in this timezone * @param VObject\Component\VCalendar Optional VCalendar component * * @return mixed A Sabre\VObject\Component object representing a VTIMEZONE definition * or false if no timezone information is available */ public static function get_vtimezone($tzid, $from = 0, $to = 0, $cal = null) { // TODO: Consider using tzurl.org database for better interoperability e.g. with Outlook if (!$from) $from = time(); if (!$to) $to = $from; if (!$cal) $cal = new VObject\Component\VCalendar(); if (is_string($tzid)) { try { $tz = new \DateTimeZone($tzid); } catch (\Exception $e) { return false; } } else if (is_a($tzid, '\\DateTimeZone')) { $tz = $tzid; } if (empty($tz) || !is_a($tz, '\\DateTimeZone')) { return false; } $year = 86400 * 360; $transitions = $tz->getTransitions($from - $year, $to + $year); // Make sure VTIMEZONE contains at least one STANDARD/DAYLIGHT component // when there's only one transition in specified time period (T5626) if (count($transitions) == 1) { // Get more transitions and use OFFSET from the previous to last $more_transitions = $tz->getTransitions(0, $to + $year); if (count($more_transitions) > 1) { $index = count($more_transitions) - 2; $tzfrom = $more_transitions[$index]['offset'] / 3600; } } $vt = $cal->createComponent('VTIMEZONE'); $vt->TZID = $tz->getName(); $std = null; $dst = null; foreach ($transitions as $i => $trans) { $cmp = null; if (!isset($tzfrom)) { $tzfrom = $trans['offset'] / 3600; continue; } if ($trans['isdst']) { $t_dst = $trans['ts']; $dst = $cal->createComponent('DAYLIGHT'); $cmp = $dst; } else { $t_std = $trans['ts']; $std = $cal->createComponent('STANDARD'); $cmp = $std; } if ($cmp) { $dt = new DateTime($trans['time']); $offset = $trans['offset'] / 3600; $cmp->DTSTART = $dt->format('Ymd\THis'); $cmp->TZOFFSETFROM = sprintf('%+03d%02d', floor($tzfrom), ($tzfrom - floor($tzfrom)) * 60); $cmp->TZOFFSETTO = sprintf('%+03d%02d', floor($offset), ($offset - floor($offset)) * 60); if (!empty($trans['abbr'])) { $cmp->TZNAME = $trans['abbr']; } $tzfrom = $offset; $vt->add($cmp); } // we covered the entire date range if ($std && $dst && min($t_std, $t_dst) < $from && max($t_std, $t_dst) > $to) { break; } } // add X-MICROSOFT-CDO-TZID if available $microsoftExchangeMap = array_flip(VObject\TimeZoneUtil::$microsoftExchangeMap); if (array_key_exists($tz->getName(), $microsoftExchangeMap)) { $vt->add('X-MICROSOFT-CDO-TZID', $microsoftExchangeMap[$tz->getName()]); } return $vt; } /*** Implement PHP 5 Iterator interface to make foreach work ***/ #[\ReturnTypeWillChange] function current() { return $this->objects[$this->iteratorkey]; } #[\ReturnTypeWillChange] function key() { return $this->iteratorkey; } #[\ReturnTypeWillChange] function next() { $this->iteratorkey++; // read next chunk if we're reading from a file if (empty($this->objects[$this->iteratorkey]) && $this->fp) { $this->_parse_next(true); } return $this->valid(); } #[\ReturnTypeWillChange] function rewind() { $this->iteratorkey = 0; } #[\ReturnTypeWillChange] function valid() { return !empty($this->objects[$this->iteratorkey]); } } /** * Override Sabre\VObject\Property\Text that quotes commas in the location property * because Apple clients treat that property as list. */ class vobject_location_property extends VObject\Property\Text { /** * List of properties that are considered 'structured'. * * @var array */ protected $structuredValues = [ // vCard 'N', 'ADR', 'ORG', 'GENDER', 'LOCATION', // iCalendar 'REQUEST-STATUS', ]; } diff --git a/plugins/libcalendaring/tests/RecurrenceTest.php b/plugins/libcalendaring/tests/RecurrenceTest.php index 7d191474..cdbb2a8d 100644 --- a/plugins/libcalendaring/tests/RecurrenceTest.php +++ b/plugins/libcalendaring/tests/RecurrenceTest.php @@ -1,272 +1,273 @@ * * Copyright (C) 2022, Apheleia IT AG * * 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 . */ class RecurrenceTest extends PHPUnit\Framework\TestCase { private $plugin; function setUp(): void { $rcube = rcmail::get_instance(); $rcube->plugins->load_plugin('libcalendaring', true, true); $this->plugin = $rcube->plugins->get_plugin('libcalendaring'); } /** * Test for libcalendaring_recurrence::first_occurrence() * * @dataProvider data_first_occurrence */ function test_first_occurrence($recurrence_data, $start, $expected) { $start = new DateTime($start); if (!empty($recurrence_data['UNTIL'])) { $recurrence_data['UNTIL'] = new DateTime($recurrence_data['UNTIL']); } $recurrence = $this->plugin->get_recurrence(); $recurrence->init($recurrence_data, $start); $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', ), ); } /** * Test for libcalendaring_recurrence::first_occurrence() for all-day events * * @dataProvider data_first_occurrence */ function test_first_occurrence_allday($recurrence_data, $start, $expected) { $start = new libcalendaring_datetime($start); $start->_dateonly = true; if (!empty($recurrence_data['UNTIL'])) { $recurrence_data['UNTIL'] = new DateTime($recurrence_data['UNTIL']); } $recurrence = $this->plugin->get_recurrence(); $recurrence->init($recurrence_data, $start); $first = $recurrence->first_occurrence(); $this->assertEquals($expected, $first ? $first->format('Y-m-d H:i:s') : ''); if ($expected) { $this->assertTrue($first->_dateonly); } } /** - * Test for libcalendaring_recurrence::next() + * Test for libcalendaring_recurrence::next_instance() */ function test_next_instance() { date_default_timezone_set('America/New_York'); $start = new libcalendaring_datetime('2017-08-31 11:00:00', new DateTimeZone('Europe/Berlin')); - $start->_dateonly = true; - - $recurrence = $this->plugin->get_recurrence(); - - $recurrence->init(['FREQ' => 'WEEKLY', 'INTERVAL' => '1'], $start); + $event = [ + 'start' => $start, + 'recurrence' => ['FREQ' => 'WEEKLY', 'INTERVAL' => '1'], + 'allday' => true, + ]; - $next = $recurrence->next(); + $recurrence = new libcalendaring_recurrence($this->plugin, $event); + $next = $recurrence->next_instance(); - $this->assertEquals($start->format('2017-09-07 H:i:s'), $next->format('Y-m-d H:i:s'), 'Same time'); - $this->assertEquals($start->getTimezone()->getName(), $next->getTimezone()->getName(), 'Same timezone'); - $this->assertTrue($next->_dateonly, '_dateonly flag'); + $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->assertTrue($next['start']->_dateonly, '_dateonly flag'); } } diff --git a/plugins/libkolab/lib/kolab_date_recurrence.php b/plugins/libkolab/lib/kolab_date_recurrence.php index 9b09074b..f2110b03 100644 --- a/plugins/libkolab/lib/kolab_date_recurrence.php +++ b/plugins/libkolab/lib/kolab_date_recurrence.php @@ -1,239 +1,241 @@ * * Copyright (C) 2012-2016, Kolab Systems AG * * 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 . */ 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 bool Return a Unix timestamp instead of a DateTime object * * @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 + * Get the end date of the last 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 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 DateTimeInterface) { $end_dt = clone $event['end']; $end_dt->add(new DateInterval('P100Y')); return $end_dt; } return false; } /** * Find date/time of the first occurrence + * + * @return DateTime|null 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/tasklist/tasklist.php b/plugins/tasklist/tasklist.php index a62d8dda..1ef2e863 100644 --- a/plugins/tasklist/tasklist.php +++ b/plugins/tasklist/tasklist.php @@ -1,2523 +1,2523 @@ * * Copyright (C) 2012, Kolab Systems AG * * 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 . */ class tasklist extends rcube_plugin { const FILTER_MASK_TODAY = 1; const FILTER_MASK_TOMORROW = 2; const FILTER_MASK_WEEK = 4; const FILTER_MASK_LATER = 8; const FILTER_MASK_NODATE = 16; const FILTER_MASK_OVERDUE = 32; const FILTER_MASK_FLAGGED = 64; const FILTER_MASK_COMPLETE = 128; const FILTER_MASK_ASSIGNED = 256; const FILTER_MASK_MYTASKS = 512; const SESSION_KEY = 'tasklist_temp'; public static $filter_masks = array( 'today' => self::FILTER_MASK_TODAY, 'tomorrow' => self::FILTER_MASK_TOMORROW, 'week' => self::FILTER_MASK_WEEK, 'later' => self::FILTER_MASK_LATER, 'nodate' => self::FILTER_MASK_NODATE, 'overdue' => self::FILTER_MASK_OVERDUE, 'flagged' => self::FILTER_MASK_FLAGGED, 'complete' => self::FILTER_MASK_COMPLETE, 'assigned' => self::FILTER_MASK_ASSIGNED, 'mytasks' => self::FILTER_MASK_MYTASKS, ); public $task = '?(?!login|logout).*'; public $allowed_prefs = array('tasklist_sort_col','tasklist_sort_order'); public $rc; public $lib; public $timezone; public $ui; public $home; // declare public to be used in other classes // These are handled by __get() // public $driver; // public $itip; // public $ical; private $collapsed_tasks = array(); private $message_tasks = array(); private $task_titles = array(); /** * Plugin initialization. */ function init() { $this->require_plugin('libcalendaring'); $this->require_plugin('libkolab'); $this->rc = rcube::get_instance(); $this->lib = libcalendaring::get_instance(); $this->register_task('tasks', 'tasklist'); // load plugin configuration $this->load_config(); $this->timezone = $this->lib->timezone; // proceed initialization in startup hook $this->add_hook('startup', array($this, 'startup')); $this->add_hook('user_delete', array($this, 'user_delete')); } /** * Startup hook */ public function startup($args) { // the tasks module can be enabled/disabled by the kolab_auth plugin if ($this->rc->config->get('tasklist_disabled', false) || !$this->rc->config->get('tasklist_enabled', true)) return; // load localizations $this->add_texts('localization/', $args['task'] == 'tasks' && (!$args['action'] || $args['action'] == 'print')); $this->rc->load_language($_SESSION['language'], array('tasks.tasks' => $this->gettext('navtitle'))); // add label for task title if ($args['task'] == 'tasks' && $args['action'] != 'save-pref') { $this->load_driver(); // register calendar actions $this->register_action('index', array($this, 'tasklist_view')); $this->register_action('task', array($this, 'task_action')); $this->register_action('tasklist', array($this, 'tasklist_action')); $this->register_action('counts', array($this, 'fetch_counts')); $this->register_action('fetch', array($this, 'fetch_tasks')); $this->register_action('print', array($this, 'print_tasks')); $this->register_action('dialog-ui', array($this, 'mail_message2task')); $this->register_action('get-attachment', array($this, 'attachment_get')); $this->register_action('upload', array($this, 'attachment_upload')); $this->register_action('import', array($this, 'import_tasks')); $this->register_action('export', array($this, 'export_tasks')); $this->register_action('mailimportitip', array($this, 'mail_import_itip')); $this->register_action('mailimportattach', array($this, 'mail_import_attachment')); $this->register_action('itip-status', array($this, 'task_itip_status')); $this->register_action('itip-remove', array($this, 'task_itip_remove')); $this->register_action('itip-decline-reply', array($this, 'mail_itip_decline_reply')); $this->register_action('itip-delegate', array($this, 'mail_itip_delegate')); $this->add_hook('refresh', array($this, 'refresh')); $this->collapsed_tasks = array_filter(explode(',', $this->rc->config->get('tasklist_collapsed_tasks', ''))); } else if ($args['task'] == 'mail') { if ($args['action'] == 'show' || $args['action'] == 'preview') { if ($this->rc->config->get('tasklist_mail_embed', true)) { $this->add_hook('message_load', array($this, 'mail_message_load')); } $this->add_hook('template_object_messagebody', array($this, 'mail_messagebody_html')); } // add 'Create event' item to message menu if ($this->api->output->type == 'html' && (empty($_GET['_rel']) || $_GET['_rel'] != 'task')) { $this->api->add_content(html::tag('li', array('role' => 'menuitem'), $this->api->output->button(array( 'command' => 'tasklist-create-from-mail', 'label' => 'tasklist.createfrommail', 'type' => 'link', 'classact' => 'icon taskaddlink active', 'class' => 'icon taskaddlink disabled', 'innerclass' => 'icon taskadd', ))), 'messagemenu'); $this->api->output->add_label('tasklist.createfrommail'); } } if (!$this->rc->output->ajax_call && empty($this->rc->output->env['framed'])) { $this->load_ui(); $this->ui->init(); } // add hooks for alarms handling $this->add_hook('pending_alarms', array($this, 'pending_alarms')); $this->add_hook('dismiss_alarms', array($this, 'dismiss_alarms')); } /** * */ private function load_ui() { if (!$this->ui) { require_once($this->home . '/tasklist_ui.php'); $this->ui = new tasklist_ui($this); } } /** * 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('tasklist_driver', 'database'); $driver_class = 'tasklist_' . $driver_name . '_driver'; require_once($this->home . '/drivers/tasklist_driver.php'); require_once($this->home . '/drivers/' . $driver_name . '/' . $driver_class . '.php'); $this->driver = new $driver_class($this); $this->rc->output->set_env('tasklist_driver', $driver_name); } /** * Dispatcher for task-related actions initiated by the client */ public function task_action() { $filter = intval(rcube_utils::get_input_value('filter', rcube_utils::INPUT_GPC)); $action = rcube_utils::get_input_value('action', rcube_utils::INPUT_GPC); $rec = rcube_utils::get_input_value('t', rcube_utils::INPUT_POST, true); $oldrec = $rec; $success = $refresh = $got_msg = false; // force notify if hidden + active $itip_send_option = (int)$this->rc->config->get('calendar_itip_send_option', 3); if ($itip_send_option === 1 && empty($rec['_reportpartstat'])) { $rec['_notify'] = 1; } switch ($action) { case 'new': $oldrec = null; $rec = $this->prepare_task($rec); $rec['uid'] = $this->generate_uid(); $temp_id = !empty($rec['tempid']) ? $rec['tempid'] : null; if ($success = $this->driver->create_task($rec)) { $refresh = $this->driver->get_task($rec); if ($temp_id) $refresh['tempid'] = $temp_id; $this->cleanup_task($rec); } break; case 'complete': $complete = intval(rcube_utils::get_input_value('complete', rcube_utils::INPUT_POST)); if (!($rec = $this->driver->get_task($rec))) { break; } $oldrec = $rec; $rec['status'] = $complete ? 'COMPLETED' : ($rec['complete'] > 0 ? 'IN-PROCESS' : 'NEEDS-ACTION'); // sent itip notifications if enabled (no user interaction here) if (($itip_send_option & 1)) { if ($this->is_attendee($rec)) { $rec['_reportpartstat'] = $rec['status']; } else if ($this->is_organizer($rec)) { $rec['_notify'] = 1; } } case 'edit': $oldrec = $this->driver->get_task($rec); $rec = $this->prepare_task($rec); $clone = $this->handle_recurrence($rec, $this->driver->get_task($rec)); if ($success = $this->driver->edit_task($rec)) { $new_task = $this->driver->get_task($rec); $new_task['tempid'] = $rec['id']; $refresh[] = $new_task; $this->cleanup_task($rec); // add clone from recurring task if ($clone && $this->driver->create_task($clone)) { $new_clone = $this->driver->get_task($clone); $new_clone['tempid'] = $clone['id']; $refresh[] = $new_clone; $this->driver->clear_alarms($rec['id']); } // move all childs if list assignment was changed if (!empty($rec['_fromlist']) && !empty($rec['list']) && $rec['_fromlist'] != $rec['list']) { foreach ($this->driver->get_childs(array('id' => $rec['id'], 'list' => $rec['_fromlist']), true) as $cid) { $child = array('id' => $cid, 'list' => $rec['list'], '_fromlist' => $rec['_fromlist']); if ($this->driver->move_task($child)) { $r = $this->driver->get_task($child); if ((bool)($filter & self::FILTER_MASK_COMPLETE) == $this->driver->is_complete($r)) { $r['tempid'] = $cid; $refresh[] = $r; } } } } } break; case 'move': foreach ((array)$rec['id'] as $id) { $r = $rec; $r['id'] = $id; if ($this->driver->move_task($r)) { $new_task = $this->driver->get_task($r); $new_task['tempid'] = $id; $refresh[] = $new_task; $success = true; // move all childs, too foreach ($this->driver->get_childs(array('id' => $id, 'list' => $rec['_fromlist']), true) as $cid) { $child = $rec; $child['id'] = $cid; if ($this->driver->move_task($child)) { $r = $this->driver->get_task($child); if ((bool)($filter & self::FILTER_MASK_COMPLETE) == $this->driver->is_complete($r)) { $r['tempid'] = $cid; $refresh[] = $r; } } } } } break; case 'delete': $mode = intval(rcube_utils::get_input_value('mode', rcube_utils::INPUT_POST)); $oldrec = $this->driver->get_task($rec); if ($success = $this->driver->delete_task($rec, false)) { // delete/modify all childs foreach ($this->driver->get_childs($rec, $mode) as $cid) { $child = array('id' => $cid, 'list' => $rec['list']); if ($mode == 1) { // delete all childs if ($this->driver->delete_task($child, false)) { if ($this->driver->undelete) $_SESSION['tasklist_undelete'][$rec['id']][] = $cid; } else $success = false; } else { $child['parent_id'] = strval($oldrec['parent_id']); $this->driver->edit_task($child); } } // update parent task to adjust list of children if (!empty($oldrec['parent_id'])) { $parent = array('id' => $oldrec['parent_id'], 'list' => $rec['list']); if ($parent = $this->driver->get_task()) { $refresh[] = $parent; } } } if (!$success) $this->rc->output->command('plugin.reload_data'); break; case 'undelete': if ($success = $this->driver->undelete_task($rec)) { $refresh[] = $this->driver->get_task($rec); foreach ((array)$_SESSION['tasklist_undelete'][$rec['id']] as $cid) { if ($this->driver->undelete_task($rec)) { $refresh[] = $this->driver->get_task($rec); } } } break; case 'collapse': foreach (explode(',', $rec['id']) as $rec_id) { if (intval(rcube_utils::get_input_value('collapsed', rcube_utils::INPUT_GPC))) { $this->collapsed_tasks[] = $rec_id; } else { $i = array_search($rec_id, $this->collapsed_tasks); if ($i !== false) unset($this->collapsed_tasks[$i]); } } $this->rc->user->save_prefs(array('tasklist_collapsed_tasks' => join(',', array_unique($this->collapsed_tasks)))); return; // avoid further actions case 'rsvp': $status = rcube_utils::get_input_value('status', rcube_utils::INPUT_GPC); $noreply = intval(rcube_utils::get_input_value('noreply', rcube_utils::INPUT_GPC)) || $status == 'needs-action'; $task = $this->driver->get_task($rec); $task['attendees'] = $rec['attendees']; $task['_type'] = 'task'; // send invitation to delegatee + add it as attendee if ($status == 'delegated' && $rec['to']) { $itip = $this->load_itip(); if ($itip->delegate_to($task, $rec['to'], (bool)$rec['rsvp'])) { $this->rc->output->show_message('tasklist.itipsendsuccess', 'confirmation'); $refresh[] = $task; $noreply = false; } } $rec = $task; if ($success = $this->driver->edit_task($rec)) { if (!$noreply) { // let the reply clause further down send the iTip message $rec['_reportpartstat'] = $status; } } break; case 'changelog': $data = $this->driver->get_task_changelog($rec); 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 ($change['date']) { $dt = $lib->adjust_timezone($change['date']); if ($dt instanceof DateTime) { $change['date'] = $this->rc->format_date($dt, $dtformat, false); } } }); $this->rc->output->command('plugin.task_render_changelog', $data); } else { $this->rc->output->command('plugin.task_render_changelog', false); } $got_msg = true; break; case 'diff': $data = $this->driver->get_task_diff($rec, $rec['rev1'], $rec['rev2']); if (is_array($data)) { // convert some properties, similar to self::_client_event() $lib = $this->lib; $date_format = $this->rc->config->get('date_format', 'Y-m-d'); $time_format = $this->rc->config->get('time_format', 'H:i'); array_walk($data['changes'], function(&$change, $i) use ($lib, $date_format, $time_format) { // convert date cols if (in_array($change['property'], array('date','start','created','changed'))) { if (!empty($change['old'])) { $dtformat = strlen($change['old']) == 10 ? $date_format : $date_format . ' ' . $time_format; $change['old_'] = $lib->adjust_timezone($change['old'], strlen($change['old']) == 10)->format($dtformat); } if (!empty($change['new'])) { $dtformat = strlen($change['new']) == 10 ? $date_format : $date_format . ' ' . $time_format; $change['new_'] = $lib->adjust_timezone($change['new'], strlen($change['new']) == 10)->format($dtformat); } } // 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'] == 'complete') { $change['old_'] = intval($change['old']) . '%'; $change['new_'] = intval($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'] = array_merge((array)$change['old'], $change['new']); $change['new']['classname'] = rcube_utils::file2class($change['new']['mimetype'], $change['new']['name']); } } // resolve parent_id to the refered task title for display if ($change['property'] == 'parent_id') { $change['property'] = 'parent-title'; if (!empty($change['old']) && ($old_parent = $this->driver->get_task(array('id' => $change['old'], 'list' => $rec['list'])))) { $change['old_'] = $old_parent['title']; } if (!empty($change['new']) && ($new_parent = $this->driver->get_task(array('id' => $change['new'], 'list' => $rec['list'])))) { $change['new_'] = $new_parent['title']; } } // 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.task_show_diff', $data); } else { $this->rc->output->command('display_message', $this->gettext('objectdiffnotavailable'), 'error'); } $got_msg = true; break; case 'show': if ($rec = $this->driver->get_task_revison($rec, $rec['rev'])) { $this->encode_task($rec); $rec['readonly'] = 1; $this->rc->output->command('plugin.task_show_revision', $rec); } else { $this->rc->output->command('display_message', $this->gettext('objectnotfound'), 'error'); } $got_msg = true; break; case 'restore': if ($success = $this->driver->restore_task_revision($rec, $rec['rev'])) { $refresh = $this->driver->get_task($rec); $this->rc->output->command('display_message', $this->gettext(array('name' => 'objectrestoresuccess', 'vars' => array('rev' => $rec['rev']))), 'confirmation'); $this->rc->output->command('plugin.close_history_dialog'); } else { $this->rc->output->command('display_message', $this->gettext('objectrestoreerror'), 'error'); } $got_msg = true; break; } if ($success) { $this->rc->output->show_message('successfullysaved', 'confirmation'); $this->update_counts($oldrec, $refresh); } else if (!$got_msg) { $this->rc->output->show_message('tasklist.errorsaving', 'error'); } // send out notifications if ($success && !empty($rec['_notify']) && ($rec['attendees'] || $oldrec['attendees'])) { // make sure we have the complete record $task = $action == 'delete' ? $oldrec : $this->driver->get_task($rec); // only notify if data really changed (TODO: do diff check on client already) if (!$oldrec || $action == 'delete' || self::task_diff($task, $oldrec)) { $sent = $this->notify_attendees($task, $oldrec, $action, $rec['_comment']); if ($sent > 0) $this->rc->output->show_message('tasklist.itipsendsuccess', 'confirmation'); else if ($sent < 0) $this->rc->output->show_message('tasklist.errornotifying', 'error'); } } if ($success && !empty($rec['_reportpartstat']) && $rec['_reportpartstat'] != 'NEEDS-ACTION') { // get the full record after update if (!$task) { $task = $this->driver->get_task($rec); } // send iTip REPLY with the updated partstat if ($task['organizer'] && ($idx = $this->is_attendee($task)) !== false) { $sender = $task['attendees'][$idx]; $status = strtolower($sender['status']); if (!empty($_POST['comment'])) $task['comment'] = rcube_utils::get_input_value('comment', rcube_utils::INPUT_POST); $itip = $this->load_itip(); $itip->set_sender_email($sender['email']); if ($itip->send_itip_message($this->to_libcal($task), 'REPLY', $task['organizer'], 'itipsubject' . $status, 'itipmailbody' . $status)) $this->rc->output->command('display_message', $this->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $task['organizer']['name'] ?: $task['organizer']['email']))), 'confirmation'); else $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error'); } } // unlock client $this->rc->output->command('plugin.unlock_saving', $success); if ($refresh) { if (!empty($refresh['id'])) { $this->encode_task($refresh); } else if (is_array($refresh)) { foreach ($refresh as $i => $r) $this->encode_task($refresh[$i]); } $this->rc->output->command('plugin.update_task', $refresh); } else if ($success && ($action == 'delete' || $action == 'undelete')) { $this->rc->output->command('plugin.refresh_tagcloud'); } } /** * Load iTIP functions */ private function load_itip() { if (empty($this->itip)) { require_once __DIR__ . '/../libcalendaring/lib/libcalendaring_itip.php'; $this->itip = new libcalendaring_itip($this, 'tasklist'); $this->itip->set_rsvp_actions(array('accepted','declined','delegated')); $this->itip->set_rsvp_status(array('accepted','tentative','declined','delegated','in-process','completed')); } return $this->itip; } /** * repares new/edited task properties before save */ private function prepare_task($rec) { // try to be smart and extract date from raw input if (!empty($rec['raw'])) { foreach (array('today','tomorrow','sunday','monday','tuesday','wednesday','thursday','friday','saturday','sun','mon','tue','wed','thu','fri','sat') as $word) { $locwords[] = '/^' . preg_quote(mb_strtolower($this->gettext($word))) . '\b/i'; $normwords[] = $word; $datewords[] = $word; } foreach (array('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','now','dec') as $month) { $locwords[] = '/(' . preg_quote(mb_strtolower($this->gettext('long'.$month))) . '|' . preg_quote(mb_strtolower($this->gettext($month))) . ')\b/i'; $normwords[] = $month; $datewords[] = $month; } foreach (array('on','this','next','at') as $word) { $fillwords[] = preg_quote(mb_strtolower($this->gettext($word))); $fillwords[] = $word; } $raw = trim($rec['raw']); $date_str = ''; // translate localized keywords $raw = preg_replace('/^(' . join('|', $fillwords) . ')\s*/i', '', $raw); $raw = preg_replace($locwords, $normwords, $raw); // find date pattern $date_pattern = '!^(\d+[./-]\s*)?((?:\d+[./-])|' . join('|', $datewords) . ')\.?(\s+\d{4})?[:;,]?\s+!i'; if (preg_match($date_pattern, $raw, $m)) { $date_str .= $m[1] . $m[2] . $m[3]; $raw = preg_replace(array($date_pattern, '/^(' . join('|', $fillwords) . ')\s*/i'), '', $raw); // add year to date string if ($m[1] && !$m[3]) $date_str .= date('Y'); } // find time pattern $time_pattern = '/^(\d+([:.]\d+)?(\s*[hapm.]+)?),?\s+/i'; if (preg_match($time_pattern, $raw, $m)) { $has_time = true; $date_str .= ($date_str ? ' ' : 'today ') . $m[1]; $raw = preg_replace($time_pattern, '', $raw); } // yes, raw input matched a (valid) date if (strlen($date_str) && strtotime($date_str) && ($date = new DateTime($date_str, $this->timezone))) { $rec['date'] = $date->format('Y-m-d'); if ($has_time) $rec['time'] = $date->format('H:i'); $rec['title'] = $raw; } else $rec['title'] = $rec['raw']; } // normalize input from client if (isset($rec['complete'])) { $rec['complete'] = floatval($rec['complete']); if ($rec['complete'] > 1) $rec['complete'] /= 100; } if (isset($rec['flagged'])) $rec['flagged'] = intval($rec['flagged']); // fix for garbage input if ($rec['description'] == 'null') $rec['description'] = ''; foreach ($rec as $key => $val) { if ($val === 'null') $rec[$key] = null; } if (!empty($rec['date'])) { $this->normalize_dates($rec, 'date', 'time'); } if (!empty($rec['startdate'])) { $this->normalize_dates($rec, 'startdate', 'starttime'); } // convert tags to array, filter out empty entries if (isset($rec['tags']) && !is_array($rec['tags'])) { $rec['tags'] = array_filter((array)$rec['tags']); } // convert the submitted alarm values if (!empty($rec['valarms'])) { $valarms = array(); foreach (libcalendaring::from_client_alarms($rec['valarms']) as $alarm) { // alarms can only work with a date (either task start, due or absolute alarm date) if (is_a($alarm['trigger'], 'DateTime') || $rec['date'] || $rec['startdate']) $valarms[] = $alarm; } $rec['valarms'] = $valarms; } // convert the submitted recurrence settings if (is_array($rec['recurrence'])) { $refdate = null; if (!empty($rec['date'])) { $refdate = new DateTime($rec['date'] . ' ' . $rec['time'], $this->timezone); } else if (!empty($rec['startdate'])) { $refdate = new DateTime($rec['startdate'] . ' ' . $rec['starttime'], $this->timezone); } if ($refdate) { $rec['recurrence'] = $this->lib->from_client_recurrence($rec['recurrence'], $refdate); // translate count into an absolute end date. - // why? because when shifting completed tasks to the next recurrence, + // why? because when shifting completed tasks to the next occurrence, // the initial start date to count from gets lost. if (!empty($rec['recurrence']['COUNT'])) { $engine = libcalendaring::get_recurrence(); $engine->init($rec['recurrence'], $refdate); if ($until = $engine->end()) { $rec['recurrence']['UNTIL'] = $until; unset($rec['recurrence']['COUNT']); } } } else { // recurrence requires a reference date $rec['recurrence'] = ''; } } $attachments = array(); $taskid = $rec['id']; if (!empty($_SESSION[self::SESSION_KEY]) && $_SESSION[self::SESSION_KEY]['id'] == $taskid) { if (!empty($_SESSION[self::SESSION_KEY]['attachments'])) { foreach ($_SESSION[self::SESSION_KEY]['attachments'] as $id => $attachment) { if (is_array($rec['attachments']) && in_array($id, $rec['attachments'])) { $attachments[$id] = $this->rc->plugins->exec_hook('attachment_get', $attachment); unset($attachments[$id]['abort'], $attachments[$id]['group']); } } } } $rec['attachments'] = $attachments; // convert link references into simple URIs if (array_key_exists('links', $rec)) { $rec['links'] = array_map(function($link) { return is_array($link) ? $link['uri'] : strval($link); }, (array)$rec['links']); } // convert invalid data if (isset($rec['attendees']) && !is_array($rec['attendees'])) { $rec['attendees'] = array(); } if (!empty($rec['attendees'])) { foreach ((array) $rec['attendees'] as $i => $attendee) { if (is_string($attendee['rsvp'])) { $rec['attendees'][$i]['rsvp'] = $attendee['rsvp'] == 'true' || $attendee['rsvp'] == '1'; } } } // copy the task status to my attendee partstat if (!empty($rec['_reportpartstat'])) { if (($idx = $this->is_attendee($rec)) !== false) { if (!($rec['_reportpartstat'] == 'NEEDS-ACTION' && $rec['attendees'][$idx]['status'] == 'ACCEPTED')) $rec['attendees'][$idx]['status'] = $rec['_reportpartstat']; else unset($rec['_reportpartstat']); } } // set organizer from identity selector if ((isset($rec['_identity']) || (!empty($rec['attendees']) && empty($rec['organizer']))) && ($identity = $this->rc->user->get_identity($rec['_identity']))) { $rec['organizer'] = array('name' => $identity['name'], 'email' => $identity['email']); } if (is_numeric($rec['id']) && $rec['id'] < 0) unset($rec['id']); return $rec; } /** * Utility method to convert a tasks date/time values into a normalized format */ private function normalize_dates(&$rec, $date_key, $time_key) { try { // parse date from user format (#2801) $date_format = $this->rc->config->get(empty($rec[$time_key]) ? 'date_format' : 'date_long', 'Y-m-d'); $date = DateTime::createFromFormat($date_format, trim($rec[$date_key] . ' ' . $rec[$time_key]), $this->timezone); // fall back to default strtotime logic if (empty($date)) { $date = new DateTime($rec[$date_key] . ' ' . $rec[$time_key], $this->timezone); } $rec[$date_key] = $date->format('Y-m-d'); if (!empty($rec[$time_key])) $rec[$time_key] = $date->format('H:i'); return true; } catch (Exception $e) { $rec[$date_key] = $rec[$time_key] = null; } return false; } /** * Releases some resources after successful save */ private function cleanup_task(&$rec) { // remove temp. attachment files if (!empty($_SESSION[self::SESSION_KEY]) && ($taskid = $_SESSION[self::SESSION_KEY]['id'])) { $this->rc->plugins->exec_hook('attachments_cleanup', array('group' => $taskid)); $this->rc->session->remove(self::SESSION_KEY); } } /** * When flagging a recurring task as complete, * clone it and shift dates to the next occurrence */ private function handle_recurrence(&$rec, $old) { $clone = null; if ($this->driver->is_complete($rec) && $old && !$this->driver->is_complete($old) && is_array($rec['recurrence'])) { $engine = libcalendaring::get_recurrence(); $rrule = $rec['recurrence']; $updates = array(); // compute the next occurrence of date attributes foreach (array('date'=>'time', 'startdate'=>'starttime') as $date_key => $time_key) { if (empty($rec[$date_key])) continue; $date = new DateTime($rec[$date_key] . ' ' . $rec[$time_key], $this->timezone); $engine->init($rrule, $date); - if ($next = $engine->next()) { + if ($next = $engine->next_start()) { $updates[$date_key] = $next->format('Y-m-d'); if (!empty($rec[$time_key])) $updates[$time_key] = $next->format('H:i'); } } // shift absolute alarm dates if (!empty($updates) && is_array($rec['valarms'])) { $updates['valarms'] = array(); unset($rrule['UNTIL'], $rrule['COUNT']); // make recurrence rule unlimited foreach ($rec['valarms'] as $i => $alarm) { if ($alarm['trigger'] instanceof DateTime) { $engine->init($rrule, $alarm['trigger']); - if ($next = $engine->next()) { + if ($next = $engine->next_start()) { $alarm['trigger'] = $next; } } $updates['valarms'][$i] = $alarm; } } if (!empty($updates)) { // clone task to save a completed copy $clone = $rec; $clone['uid'] = $this->generate_uid(); $clone['parent_id'] = $rec['id']; unset($clone['id'], $clone['recurrence'], $clone['attachments']); // update the task but unset completed flag $rec = array_merge($rec, $updates); $rec['complete'] = $old['complete']; $rec['status'] = $old['status']; } } return $clone; } /** * Send out an invitation/notification to all task attendees */ private function notify_attendees($task, $old, $action = 'edit', $comment = null) { if ($action == 'delete' || ($task['status'] == 'CANCELLED' && $old['status'] != $task['status'])) { $task['cancelled'] = true; $is_cancelled = true; } $itip = $this->load_itip(); $emails = $this->lib->get_user_emails(); $itip_notify = (int)$this->rc->config->get('calendar_itip_send_option', 3); // add comment to the iTip attachment $task['comment'] = $comment; // needed to generate VTODO instead of VEVENT entry $task['_type'] = 'task'; // compose multipart message using PEAR:Mail_Mime $method = $action == 'delete' ? 'CANCEL' : 'REQUEST'; $object = $this->to_libcal($task); $message = $itip->compose_itip_message($object, $method, $task['sequence'] > $old['sequence']); // list existing attendees from the $old task $old_attendees = array(); foreach ((array)$old['attendees'] as $attendee) { $old_attendees[] = $attendee['email']; } // send to every attendee $sent = 0; $current = array(); foreach ((array)$task['attendees'] as $attendee) { $current[] = strtolower($attendee['email']); // skip myself for obvious reasons if (!$attendee['email'] || in_array(strtolower($attendee['email']), $emails)) { continue; } // skip if notification is disabled for this attendee if ($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 || $task['sequence'] > $old['sequence']; $bodytext = $is_cancelled ? 'itipcancelmailbody' : ($is_new ? 'invitationmailbody' : 'itipupdatemailbody'); $subject = $is_cancelled ? 'itipcancelsubject' : ($is_new ? 'invitationsubject' : ($task['title'] ? 'itipupdatesubject' : 'itipupdatesubjectempty')); // finally send the message if ($itip->send_itip_message($object, $method, $attendee, $subject, $bodytext, $message, $is_rsvp)) $sent++; else $sent = -100; } // send CANCEL message to removed attendees foreach ((array)$old['attendees'] as $attendee) { if (!$attendee['email'] || in_array(strtolower($attendee['email']), $current)) { continue; } $vtodo = $this->to_libcal($old); $vtodo['cancelled'] = $is_cancelled; $vtodo['attendees'] = array($attendee); $vtodo['comment'] = $comment; if ($itip->send_itip_message($vtodo, 'CANCEL', $attendee, 'itipcancelsubject', 'itipcancelmailbody')) $sent++; else $sent = -100; } return $sent; } /** * Compare two task objects and return differing properties * * @param array Event A * @param array Event B * @return array List of differing task properties */ public static function task_diff($a, $b) { $diff = array(); $ignore = array('changed' => 1, 'attachments' => 1); foreach (array_unique(array_merge(array_keys($a), array_keys($b))) as $key) { if (!$ignore[$key] && $a[$key] != $b[$key]) $diff[] = $key; } // only compare number of attachments if (count($a['attachments']) != count($b['attachments'])) $diff[] = 'attachments'; return $diff; } /** * Dispatcher for tasklist actions initiated by the client */ public function tasklist_action() { $action = rcube_utils::get_input_value('action', rcube_utils::INPUT_GPC); $list = rcube_utils::get_input_value('l', rcube_utils::INPUT_GPC, true); $success = false; unset($list['_token']); if (isset($list['showalarms'])) { $list['showalarms'] = intval($list['showalarms']); } switch ($action) { case 'form-new': case 'form-edit': $this->load_ui(); echo $this->ui->tasklist_editform($action, $list); exit; case 'new': $list += array('showalarms' => true, 'active' => true, 'editable' => true); if ($insert_id = $this->driver->create_list($list)) { $list['id'] = $insert_id; if (empty($list['_reload'])) { $this->load_ui(); $list['html'] = $this->ui->tasklist_list_item($insert_id, $list, $jsenv); $list += (array)$jsenv[$insert_id]; } $this->rc->output->command('plugin.insert_tasklist', $list); $success = true; } break; case 'edit': if ($newid = $this->driver->edit_list($list)) { $list['oldid'] = $list['id']; $list['id'] = $newid; $this->rc->output->command('plugin.update_tasklist', $list); $success = true; } break; case 'subscribe': $success = $this->driver->subscribe_list($list); break; case 'delete': if (($success = $this->driver->delete_list($list))) $this->rc->output->command('plugin.destroy_tasklist', $list); break; case 'search': $this->load_ui(); $results = array(); $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_lists($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->tasklist_list_item($id, $prop, $jsenv); $prop += (array)$jsenv[$id]; $prop['editname'] = $editname; $prop['html'] = $html; $results[] = $prop; } // report more results available if (!empty($this->driver->search_more_results)) { $this->rc->output->show_message('autocompletemore', 'notice'); } $this->rc->output->command('multi_thread_http_response', $results, rcube_utils::get_input_value('_reqid', rcube_utils::INPUT_GPC)); return; } if ($success) { $this->rc->output->show_message('successfullysaved', 'confirmation'); } else { $this->rc->output->show_message('tasklist.errorsaving', 'error'); } $this->rc->output->command('plugin.unlock_saving'); } /** * Get counts for active tasks divided into different selectors */ public function fetch_counts() { if (isset($_REQUEST['lists'])) { $lists = rcube_utils::get_input_value('lists', rcube_utils::INPUT_GPC); } else { foreach ($this->driver->get_lists() as $list) { if (!empty($list['active'])) { $lists[] = $list['id']; } } } $counts = $this->driver->count_tasks($lists); $this->rc->output->command('plugin.update_counts', $counts); } /** * Adjust the cached counts after changing a task */ public function update_counts($oldrec, $newrec) { // rebuild counts until this function is finally implemented $this->fetch_counts(); // $this->rc->output->command('plugin.update_counts', $counts); } /** * */ public function fetch_tasks() { $mask = intval(rcube_utils::get_input_value('filter', rcube_utils::INPUT_GPC)); $search = rcube_utils::get_input_value('q', rcube_utils::INPUT_GPC); $lists = rcube_utils::get_input_value('lists', rcube_utils::INPUT_GPC); $filter = array('mask' => $mask, 'search' => $search); $data = $this->tasks_data($this->driver->list_tasks($filter, $lists)); $this->rc->output->command('plugin.data_ready', array( 'filter' => $mask, 'lists' => $lists, 'search' => $search, 'data' => $data, 'tags' => $this->driver->get_tags(), )); } /** * Handler for printing calendars */ public function print_tasks() { // Add CSS stylesheets to the page header $skin_path = $this->local_skin_path(); $this->include_stylesheet($skin_path . '/print.css'); $this->include_script('tasklist.js'); $this->rc->output->add_handlers(array( 'plugin.tasklist_print' => array($this, 'print_tasks_list'), )); $this->rc->output->set_pagetitle($this->gettext('print')); $this->rc->output->send('tasklist.print'); } /** * Handler for printing calendars */ public function print_tasks_list($attrib) { $mask = intval(rcube_utils::get_input_value('filter', rcube_utils::INPUT_GPC)); $search = rcube_utils::get_input_value('q', rcube_utils::INPUT_GPC); $lists = rcube_utils::get_input_value('lists', rcube_utils::INPUT_GPC); $filter = array('mask' => $mask, 'search' => $search); $data = $this->tasks_data($this->driver->list_tasks($filter, $lists)); // we'll build the tasks table in javascript on page load // where we have sorting methods, etc. $this->rc->output->set_env('tasks', $data); $this->rc->output->set_env('filtermask', $mask); return $this->ui->tasks_resultview($attrib); } /** * Prepare and sort the given task records to be sent to the client */ private function tasks_data($records) { $data = $this->task_tree = $this->task_titles = array(); foreach ($records as $rec) { if (!empty($rec['parent_id'])) { $this->task_tree[$rec['id']] = $rec['parent_id']; } $this->encode_task($rec); $data[] = $rec; } // assign hierarchy level indicators for later sorting array_walk($data, array($this, 'task_walk_tree')); return $data; } /** * Prepare the given task record before sending it to the client */ private function encode_task(&$rec) { $rec['mask'] = $this->filter_mask($rec); $rec['flagged'] = intval($rec['flagged']); $rec['complete'] = floatval($rec['complete']); if (is_object($rec['created'])) { $rec['created_'] = $this->rc->format_date($rec['created']); $rec['created'] = $rec['created']->format('U'); } if (is_object($rec['changed'])) { $rec['changed_'] = $this->rc->format_date($rec['changed']); $rec['changed'] = $rec['changed']->format('U'); } else { $rec['changed'] = null; } if ($rec['date']) { try { $date = new DateTime($rec['date'] . ' ' . $rec['time'], $this->timezone); $rec['datetime'] = intval($date->format('U')); $rec['date'] = $date->format($this->rc->config->get('date_format', 'Y-m-d')); $rec['_hasdate'] = 1; } catch (Exception $e) { $rec['date'] = $rec['datetime'] = null; } } else { $rec['date'] = $rec['datetime'] = null; $rec['_hasdate'] = 0; } if ($rec['startdate']) { try { $date = new DateTime($rec['startdate'] . ' ' . $rec['starttime'], $this->timezone); $rec['startdatetime'] = intval($date->format('U')); $rec['startdate'] = $date->format($this->rc->config->get('date_format', 'Y-m-d')); } catch (Exception $e) { $rec['startdate'] = $rec['startdatetime'] = null; } } if (!empty($rec['valarms'])) { $rec['alarms_text'] = libcalendaring::alarms_text($rec['valarms']); $rec['valarms'] = libcalendaring::to_client_alarms($rec['valarms']); } if (!empty($rec['recurrence'])) { $rec['recurrence_text'] = $this->lib->recurrence_text($rec['recurrence']); $rec['recurrence'] = $this->lib->to_client_recurrence($rec['recurrence'], $rec['time'] || $rec['starttime']); } if (!empty($rec['attachments'])) { foreach ((array) $rec['attachments'] as $k => $attachment) { $rec['attachments'][$k]['classname'] = rcube_utils::file2class($attachment['mimetype'], $attachment['name']); } } // convert link URIs references into structs if (array_key_exists('links', $rec)) { foreach ((array) $rec['links'] as $i => $link) { if (strpos($link, 'imap://') === 0 && ($msgref = $this->driver->get_message_reference($link, 'task'))) { $rec['links'][$i] = $msgref; } } } // Convert HTML description into plain text if ($this->is_html($rec)) { $h2t = new rcube_html2text($rec['description'], false, true, 0); $rec['description'] = $h2t->get_text(); } if (!is_array($rec['tags'])) $rec['tags'] = (array)$rec['tags']; sort($rec['tags'], SORT_LOCALE_STRING); if (in_array($rec['id'], $this->collapsed_tasks)) $rec['collapsed'] = true; if (empty($rec['parent_id'])) $rec['parent_id'] = null; $this->task_titles[$rec['id']] = $rec['title']; } /** * Determine whether the given task description is HTML formatted */ private function is_html($task) { // check for opening and closing or tags return (preg_match('/<(html|body)(\s+[a-z]|>)/', $task['description'], $m) && strpos($task['description'], '') > 0); } /** * Callback function for array_walk over all tasks. * Sets tree depth and parent titles */ private function task_walk_tree(&$rec) { $rec['_depth'] = 0; $parent_titles = array(); $parent_id = isset($this->task_tree[$rec['id']]) ? $this->task_tree[$rec['id']] : null; while ($parent_id) { $rec['_depth']++; if (isset($this->task_titles[$parent_id])) { array_unshift($parent_titles, $this->task_titles[$parent_id]); } $parent_id = isset($this->task_tree[$parent_id]) ? $this->task_tree[$parent_id] : null; } if (count($parent_titles)) { $rec['parent_title'] = join(' ยป ', array_filter($parent_titles)); } } /** * Compute the filter mask of the given task * * @param array Hash array with Task record properties * @return int Filter mask */ public function filter_mask($rec) { static $today, $today_date, $tomorrow, $weeklimit; if (!$today) { $today_date = new DateTime('now', $this->timezone); $today = $today_date->format('Y-m-d'); $tomorrow_date = new DateTime('now + 1 day', $this->timezone); $tomorrow = $tomorrow_date->format('Y-m-d'); // In Kolab-mode we hide "Next 7 days" filter, which means // "Later" should catch tasks with date after tomorrow (#5353) if ($this->rc->output->get_env('tasklist_driver') == 'kolab') { $weeklimit = $tomorrow; } else { $week_date = new DateTime('now + 7 days', $this->timezone); $weeklimit = $week_date->format('Y-m-d'); } } $mask = 0; $start = $rec['startdate'] ?: '1900-00-00'; $duedate = $rec['date'] ?: '3000-00-00'; if ($rec['flagged']) $mask |= self::FILTER_MASK_FLAGGED; if ($this->driver->is_complete($rec)) $mask |= self::FILTER_MASK_COMPLETE; if (empty($rec['date'])) $mask |= self::FILTER_MASK_NODATE; else if ($rec['date'] < $today) $mask |= self::FILTER_MASK_OVERDUE; if (empty($rec['recurrence']) || $duedate < $today || $start > $weeklimit) { if ($duedate <= $today || ($rec['startdate'] && $start <= $today)) $mask |= self::FILTER_MASK_TODAY; else if (($start > $today && $start <= $tomorrow) || ($duedate > $today && $duedate <= $tomorrow)) $mask |= self::FILTER_MASK_TOMORROW; else if (($start > $tomorrow && $start <= $weeklimit) || ($duedate > $tomorrow && $duedate <= $weeklimit)) $mask |= self::FILTER_MASK_WEEK; else if ($start > $weeklimit || $duedate > $weeklimit) $mask |= self::FILTER_MASK_LATER; } else if ($rec['startdate'] || $rec['date']) { $date = new DateTime($rec['startdate'] ?: $rec['date'], $this->timezone); // set safe recurrence start while ($date->format('Y-m-d') >= $today) { switch ($rec['recurrence']['FREQ']) { case 'DAILY': $date = clone $today_date; $date->sub(new DateInterval('P1D')); break; case 'WEEKLY': $date->sub(new DateInterval('P7D')); break; case 'MONTHLY': $date->sub(new DateInterval('P1M')); break; case 'YEARLY': $date->sub(new DateInterval('P1Y')); break; default; break 2; } } $date->_dateonly = true; $engine = libcalendaring::get_recurrence(); $engine->init($rec['recurrence'], $date); // check task occurrences (stop next week) // FIXME: is there a faster way of doing this? - while ($date = $engine->next()) { + while ($date = $engine->next_start()) { $date = $date->format('Y-m-d'); // break iteration asap if ($date > $duedate || ($mask & self::FILTER_MASK_LATER)) { break; } if ($date == $today) { $mask |= self::FILTER_MASK_TODAY; } else if ($date == $tomorrow) { $mask |= self::FILTER_MASK_TOMORROW; } else if ($date > $tomorrow && $date <= $weeklimit) { $mask |= self::FILTER_MASK_WEEK; } else if ($date > $weeklimit) { $mask |= self::FILTER_MASK_LATER; break; } } } // add masks for assigned tasks if ($this->is_organizer($rec) && !empty($rec['attendees']) && $this->is_attendee($rec) === false) $mask |= self::FILTER_MASK_ASSIGNED; else if (/*empty($rec['attendees']) ||*/ $this->is_attendee($rec) !== false) $mask |= self::FILTER_MASK_MYTASKS; return $mask; } /** * Determine whether the current user is an attendee of the given task */ public function is_attendee($task) { $emails = $this->lib->get_user_emails(); foreach ((array)$task['attendees'] as $i => $attendee) { if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) { return $i; } } return false; } /** * Determine whether the current user is the organizer of the given task */ public function is_organizer($task) { $emails = $this->lib->get_user_emails(); return (empty($task['organizer']) || in_array(strtolower($task['organizer']['email']), $emails)); } /******* UI functions ********/ /** * Render main view of the tasklist task */ public function tasklist_view() { $this->ui->init(); $this->ui->init_templates(); // set autocompletion env $this->rc->output->set_env('autocomplete_threads', (int)$this->rc->config->get('autocomplete_threads', 0)); $this->rc->output->set_env('autocomplete_max', (int)$this->rc->config->get('autocomplete_max', 15)); $this->rc->output->set_env('autocomplete_min_length', $this->rc->config->get('autocomplete_min_length')); $this->rc->output->add_label('autocompletechars', 'autocompletemore', 'delete', 'close'); $this->rc->output->set_pagetitle($this->gettext('navtitle')); $this->rc->output->send('tasklist.mainview'); } /** * Handler for keep-alive requests * This will check for updated data in active lists and sync them to the client */ public function refresh($attr) { // refresh the entire list every 10th time to also sync deleted items if (rand(0,10) == 10) { $this->rc->output->command('plugin.reload_data'); return; } $filter = array( 'since' => $attr['last'], 'search' => rcube_utils::get_input_value('q', rcube_utils::INPUT_GPC), 'mask' => intval(rcube_utils::get_input_value('filter', rcube_utils::INPUT_GPC)) & self::FILTER_MASK_COMPLETE, ); $lists = rcube_utils::get_input_value('lists', rcube_utils::INPUT_GPC);; $updates = $this->driver->list_tasks($filter, $lists); if (!empty($updates)) { $this->rc->output->command('plugin.refresh_tasks', $this->tasks_data($updates), true); // update counts $counts = $this->driver->count_tasks($lists); $this->rc->output->command('plugin.update_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(); if ($alarms = $this->driver->pending_alarms($p['time'] ?: time())) { foreach ($alarms as $alarm) { // encode alarm object to suit the expectations of the calendaring code if ($alarm['date']) $alarm['start'] = new DateTime($alarm['date'].' '.$alarm['time'], $this->timezone); $alarm['id'] = 'task:' . $alarm['id']; // prefix ID with task: $alarm['allday'] = empty($alarm['time']) ? 1 : 0; $p['alarms'][] = $alarm; } } return $p; } /** * Handler for alarm dismiss hook triggered by the calendar module */ public function dismiss_alarms($p) { $this->load_driver(); foreach ((array)$p['ids'] as $id) { if (strpos($id, 'task:') === 0) $p['success'] |= $this->driver->dismiss_alarm(substr($id, 5), $p['snooze']); } return $p; } /** * Handler for importing .ics files */ function import_tasks() { // 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 && $_FILES['_data']['tmp_name']) { $source = rcube_utils::get_input_value('source', rcube_utils::INPUT_GPC); $lists = $this->driver->get_lists(); $list = $lists[$source] ?: $this->get_default_tasklist(); $source = $list['id']; // 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, $source, $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 the uploaded file directly $count = $this->import_from_file($_FILES['_data']['tmp_name'], $source, $errors); } if ($count) { $this->rc->output->command('display_message', $this->gettext(array('name' => 'importsuccess', 'vars' => array('nr' => $count))), 'confirmation'); $this->rc->output->command('plugin.import_success', array('source' => $source, 'refetch' => true)); } else if (!$errors) { $this->rc->output->command('display_message', $this->gettext('importnone'), 'notice'); $this->rc->output->command('plugin.import_success', array('source' => $source)); } else { $this->rc->output->command('plugin.import_error', array('message' => $this->gettext('importerror') . ($msg ? ': ' . $msg : ''))); } } else { if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) { $msg = $this->rc->gettext(array('name' => 'filesizeerror', 'vars' => array( 'size' => $this->rc->show_bytes(parse_bytes(ini_get('upload_max_filesize')))))); } else { $msg = $this->rc->gettext('fileuploaderror'); } $this->rc->output->command('plugin.import_error', array('message' => $msg)); } $this->rc->output->send('iframe'); } /** * Helper function to parse and import a single .ics file */ private function import_from_file($filepath, $source, &$errors) { $user_email = $this->rc->user->get_username(); $ical = $this->get_ical(); $errors = !$ical->fopen($filepath); $count = $i = 0; foreach ($ical as $task) { // keep the browser connection alive on long import jobs if (++$i > 100 && $i % 100 == 0) { echo ""; ob_flush(); } if ($task['_type'] == 'task') { $task['list'] = $source; if ($this->driver->create_task($task)) { $count++; } else { $errors++; } } } return $count; } /** * Construct the ics file for exporting tasks to iCalendar format */ function export_tasks() { $source = rcube_utils::get_input_value('source', rcube_utils::INPUT_GPC); $task_id = rcube_utils::get_input_value('id', rcube_utils::INPUT_GPC); $attachments = (bool) rcube_utils::get_input_value('attachments', rcube_utils::INPUT_GPC); $this->load_driver(); $browser = new rcube_browser; $lists = $this->driver->get_lists(); $tasks = array(); $filter = array(); // get message UIDs for filter if ($source && ($list = $lists[$source])) { $filename = html_entity_decode($list['name']) ?: $sorce; $filter = array($source => true); } else if ($task_id) { $filename = 'tasks'; foreach (explode(',', $task_id) as $id) { list($list_id, $task_id) = explode(':', $id, 2); if ($list_id && $task_id) { $filter[$list_id][] = $task_id; } } } // Get tasks foreach ($filter as $list_id => $uids) { $_filter = is_array($uids) ? array('uid' => $uids) : null; $_tasks = $this->driver->list_tasks($_filter, $list_id); if (!empty($_tasks)) { $tasks = array_merge($tasks, $_tasks); } } // Set file name if ($source && count($tasks) == 1) { $filename = $tasks[0]['title'] ?: 'task'; } $filename .= '.ics'; $filename = $browser->ie ? rawurlencode($filename) : addcslashes($filename, '"'); $tasks = array_map(array($this, 'to_libcal'), $tasks); // Give plugins a possibility to implement other output formats or modify the result $plugin = $this->rc->plugins->exec_hook('tasks_export', array( 'result' => $tasks, 'attachments' => $attachments, 'filename' => $filename, 'plugin' => $this, )); if ($plugin['abort']) { exit; } $this->rc->output->nocacheing_headers(); // don't kill the connection if download takes more than 30 sec. @set_time_limit(0); header("Content-Type: text/calendar"); header("Content-Disposition: inline; filename=\"". $plugin['filename'] ."\""); $this->get_ical()->export($plugin['result'], '', true, !empty($plugin['attachments']) ? array($this->driver, 'get_attachment_body') : null); exit; } /******* Attachment handling *******/ /** * Handler for attachments upload */ public function attachment_upload() { $handler = new kolab_attachments_handler(); $handler->attachment_upload(self::SESSION_KEY); } /** * 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(); } $task = rcube_utils::get_input_value('_t', rcube_utils::INPUT_GPC); $list = rcube_utils::get_input_value('_list', 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); $task = array('id' => $task, 'list' => $list, 'rev' => $rev); $attachment = $this->driver->get_attachment($id, $task); // show part page if (!empty($_GET['_frame'])) { $handler->attachment_page($attachment); } // deliver attachment content else if ($attachment) { $attachment['body'] = $this->driver->get_attachment_body($id, $task); $handler->attachment_get($attachment); } // if we arrive here, the requested part was not found header('HTTP/1.1 404 Not Found'); exit; } /******* Email related function *******/ public function mail_message2task() { $this->load_ui(); $this->ui->init(); $this->ui->init_templates(); $this->ui->tasklists(); $uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET); $mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GET); $task = array(); $imap = $this->rc->get_storage(); $message = new rcube_message($uid, $mbox); if ($message->headers) { $task['title'] = trim($message->subject); $task['description'] = trim($message->first_text_part()); $task['id'] = -$uid; $this->load_driver(); // add a reference to the email message if ($msgref = $this->driver->get_message_reference($message->headers, $mbox)) { $task['links'] = array($msgref); } // copy mail attachments to task else if ($message->attachments && $this->driver->attachments) { if (!is_array($_SESSION[self::SESSION_KEY]) || $_SESSION[self::SESSION_KEY]['id'] != $task['id']) { $_SESSION[self::SESSION_KEY] = array( 'id' => $task['id'], 'attachments' => array(), ); } foreach ((array)$message->attachments as $part) { $attachment = array( 'data' => $imap->get_message_part($uid, $part->mime_id, $part), 'size' => $part->size, 'name' => $part->filename, 'mimetype' => $part->mimetype, 'group' => $task['id'], ); $attachment = $this->rc->plugins->exec_hook('attachment_save', $attachment); if ($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' $task['attachments'][] = $attachment; } } } $this->rc->output->set_env('task_prop', $task); } else { $this->rc->output->command('display_message', $this->gettext('messageopenerror'), 'error'); } $this->rc->output->send('tasklist.dialog'); } /** * Add UI element to copy task invitations or updates to the tasklist */ 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_tasks = false; $ical_objects = $this->lib->get_mail_ical_objects(); // show a box for every task in the file foreach ($ical_objects as $idx => $task) { if ($task['_type'] != 'task') { continue; } $has_tasks = true; // get prepared inline UI for this event object if ($ical_objects->method) { $html .= html::div('tasklist-invitebox invitebox boxinformation', $this->itip->mail_itip_inline_ui( $task, $ical_objects->method, $ical_objects->mime_id . ':' . $idx, 'tasks', rcube_utils::anytodatetime($ical_objects->message_date) ) ); } // limit listing if ($idx >= 3) { break; } } // list linked tasks $links = array(); foreach ($this->message_tasks as $task) { $checkbox = new html_checkbox(array( 'name' => 'completed', 'class' => 'complete pretty-checkbox', 'title' => $this->gettext('complete'), 'data-list' => $task['list'], )); $complete = $this->driver->is_complete($task); $links[] = html::tag('li', 'messagetaskref' . ($complete ? ' complete' : ''), $checkbox->show($complete ? $task['id'] : null, array('value' => $task['id'])) . ' ' . html::a(array( 'href' => $this->rc->url(array( 'task' => 'tasks', 'list' => $task['list'], 'id' => $task['id'], )), 'class' => 'messagetasklink', 'rel' => $task['id'] . '@' . $task['list'], 'target' => '_blank', ), rcube::Q($task['title'])) ); } if (count($links)) { $html .= html::div('messagetasklinks boxinformation', html::tag('ul', 'tasklist', join("\n", $links))); } // prepend iTip/relation boxes to message body if ($html) { $this->load_ui(); $this->ui->init(); $p['content'] = $html . $p['content']; $this->rc->output->add_label('tasklist.savingdata','tasklist.deletetaskconfirm','tasklist.declinedeleteconfirm'); } // add "Save to tasks" button into attachment menu if ($has_tasks) { $this->add_button(array( 'id' => 'attachmentsavetask', 'name' => 'attachmentsavetask', 'type' => 'link', 'wrapper' => 'li', 'command' => 'attachment-save-task', 'class' => 'icon tasklistlink disabled', 'classact' => 'icon tasklistlink active', 'innerclass' => 'icon taskadd', 'label' => 'tasklist.savetotasklist', ), 'attachmentmenu'); } return $p; } /** * Lookup backend storage and find notes associated with the given message */ public function mail_message_load($p) { if (empty($p['object']->headers->others['x-kolab-type'])) { $this->load_driver(); $this->message_tasks = $this->driver->get_message_related_tasks($p['object']->headers, $p['object']->folder); // sort message tasks by completeness and due date $driver = $this->driver; array_walk($this->message_tasks, array($this, 'encode_task')); usort($this->message_tasks, function($a, $b) use ($driver) { $a_complete = intval($driver->is_complete($a)); $b_complete = intval($driver->is_complete($b)); $d = $a_complete - $b_complete; if (!$d) $d = $b['_hasdate'] - $a['_hasdate']; if (!$d) $d = $a['datetime'] - $b['datetime']; return $d; }); } } /** * Load iCalendar functions */ public function get_ical() { if (empty($this->ical)) { $this->ical = libcalendaring::get_ical(); } return $this->ical; } /** * Get properties of the tasklist this user has specified as default */ public function get_default_tasklist($lists = null) { if ($lists === null) { $lists = $this->driver->get_lists(tasklist_driver::FILTER_PERSONAL | tasklist_driver::FILTER_WRITEABLE); } $list = null; foreach ($lists as $l) { if ($l['default']) { $list = $l; } if ($l['editable']) { $first = $l; } } return $list ?: $first; } /** * 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->ctype_parameters['charset']) { $charset = $part->ctype_parameters['charset']; } if ($part) { $tasks = $this->get_ical()->import($part, $charset); } } $success = $existing = 0; if (!empty($tasks)) { // find writeable tasklist to store task $cal_id = !empty($_REQUEST['_list']) ? rcube_utils::get_input_value('_list', rcube_utils::INPUT_POST) : null; $lists = $this->driver->get_lists(); foreach ($tasks as $task) { // save to tasklist $list = $lists[$cal_id] ?: $this->get_default_tasklist(); if ($list && $list['editable'] && $task['_type'] == 'task') { $task = $this->from_ical($task); $task['list'] = $list['id']; if (!$this->driver->get_task($task['uid'])) { $success += (bool) $this->driver->create_task($task); } else { $existing++; } } } } if ($success) { $this->rc->output->command('display_message', $this->gettext(array( 'name' => 'importsuccess', 'vars' => array('nr' => $success), )), 'confirmation'); } else if ($existing) { $this->rc->output->command('display_message', $this->gettext('importwarningexists'), 'warning'); } else { $this->rc->output->command('display_message', $this->gettext('errorimportingtask'), 'error'); } } /** * Handler for POST request to import an event attached to a mail message */ public function mail_import_itip() { $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); $comment = rcube_utils::get_input_value('_comment', 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)) || $status == 'needs-action'; $error_msg = $this->gettext('errorimportingtask'); $success = false; if ($status == 'delegated') { $delegates = rcube_mime::decode_address_list(rcube_utils::get_input_value('_to', rcube_utils::INPUT_POST, true), 1, false); $delegate = reset($delegates); if (empty($delegate) || empty($delegate['mailto'])) { $this->rc->output->command('display_message', $this->gettext('libcalendaring.delegateinvalidaddress'), 'error'); return; } } // successfully parsed tasks? if ($task = $this->lib->mail_get_itip_object($mbox, $uid, $mime_id, 'task')) { $task = $this->from_ical($task); // forward iTip request to delegatee if ($delegate) { $rsvpme = rcube_utils::get_input_value('_rsvp', rcube_utils::INPUT_POST); $itip = $this->load_itip(); $task['comment'] = $comment; if ($itip->delegate_to($task, $delegate, !empty($rsvpme))) { $this->rc->output->show_message('tasklist.itipsendsuccess', 'confirmation'); } else { $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error'); } unset($task['comment']); } $mode = tasklist_driver::FILTER_PERSONAL | tasklist_driver::FILTER_SHARED | tasklist_driver::FILTER_WRITEABLE; // find writeable list to store the task $list_id = !empty($_REQUEST['_folder']) ? rcube_utils::get_input_value('_folder', rcube_utils::INPUT_POST) : null; $lists = $this->driver->get_lists($mode); $list = $lists[$list_id]; $dontsave = ($_REQUEST['_folder'] === '' && $task['_method'] == 'REQUEST'); // select default list except user explicitly selected 'none' if (!$list && !$dontsave) { $list = $this->get_default_tasklist($lists); } $metadata = array( 'uid' => $task['uid'], 'changed' => is_object($task['changed']) ? $task['changed']->format('U') : 0, 'sequence' => intval($task['sequence']), 'fallback' => strtoupper($status), 'method' => $task['_method'], 'task' => 'tasks', ); // update my attendee status according to submitted method if (!empty($status)) { $organizer = $task['organizer']; $emails = $this->lib->get_user_emails(); foreach ($task['attendees'] as $i => $attendee) { if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) { $metadata['attendee'] = $attendee['email']; $metadata['rsvp'] = $attendee['role'] != 'NON-PARTICIPANT'; $reply_sender = $attendee['email']; $task['attendees'][$i]['status'] = strtoupper($status); if (!in_array($task['attendees'][$i]['status'], array('NEEDS-ACTION','DELEGATED'))) { $task['attendees'][$i]['rsvp'] = false; // unset RSVP attribute } } } // add attendee with this user's default identity if not listed if (!$reply_sender) { $sender_identity = $this->rc->user->list_emails(true); $task['attendees'][] = array( 'name' => $sender_identity['name'], 'email' => $sender_identity['email'], 'role' => 'OPT-PARTICIPANT', 'status' => strtoupper($status), ); $metadata['attendee'] = $sender_identity['email']; } } // save to tasklist if ($list && $list['editable']) { $task['list'] = $list['id']; // check for existing task with the same UID $existing = $this->find_task($task['uid'], $mode); if ($existing) { // only update attendee status if ($task['_method'] == 'REPLY') { // try to identify the attendee using the email sender address $existing_attendee = -1; $existing_attendee_emails = array(); foreach ($existing['attendees'] as $i => $attendee) { $existing_attendee_emails[] = $attendee['email']; if ($task['_sender'] && ($attendee['email'] == $task['_sender'] || $attendee['email'] == $task['_sender_utf'])) { $existing_attendee = $i; } } $task_attendee = null; foreach ($task['attendees'] as $attendee) { if ($task['_sender'] && ($attendee['email'] == $task['_sender'] || $attendee['email'] == $task['_sender_utf'])) { $task_attendee = $attendee; $metadata['fallback'] = $attendee['status']; $metadata['attendee'] = $attendee['email']; $metadata['rsvp'] = $attendee['rsvp'] || $attendee['role'] != 'NON-PARTICIPANT'; if ($attendee['status'] != 'DELEGATED') { break; } } // also copy delegate attendee else if (!empty($attendee['delegated-from']) && (stripos($attendee['delegated-from'], $task['_sender']) !== false || stripos($attendee['delegated-from'], $task['_sender_utf']) !== false) && (!in_array($attendee['email'], $existing_attendee_emails))) { $existing['attendees'][] = $attendee; } } // if delegatee has declined, set delegator's RSVP=True if ($task_attendee && $task_attendee['status'] == 'DECLINED' && $task_attendee['delegated-from']) { foreach ($existing['attendees'] as $i => $attendee) { if ($attendee['email'] == $task_attendee['delegated-from']) { $existing['attendees'][$i]['rsvp'] = true; break; } } } // found matching attendee entry in both existing and new events if ($existing_attendee >= 0 && $task_attendee) { $existing['attendees'][$existing_attendee] = $task_attendee; $success = $this->driver->edit_task($existing); } // update the entire attendees block else if (($task['sequence'] >= $existing['sequence'] || $task['changed'] >= $existing['changed']) && $task_attendee) { $existing['attendees'][] = $task_attendee; $success = $this->driver->edit_task($existing); } else { $error_msg = $this->gettext('newerversionexists'); } } // delete the task when declined else if ($status == 'declined' && $delete) { $deleted = $this->driver->delete_task($existing, true); $success = true; } // import the (newer) task else if ($task['sequence'] >= $existing['sequence'] || $task['changed'] >= $existing['changed']) { $task['id'] = $existing['id']; $task['list'] = $existing['list']; // preserve my participant status for regular updates if (empty($status)) { $this->lib->merge_attendees($task, $existing); } // set status=CANCELLED on CANCEL messages if ($task['_method'] == 'CANCEL') { $task['status'] = 'CANCELLED'; } // update attachments list, allow attachments update only on REQUEST (#5342) if ($task['_method'] == 'REQUEST') { $task['deleted_attachments'] = true; } else { unset($task['attachments']); } // show me as free when declined (#1670) if ($status == 'declined' || $task['status'] == 'CANCELLED') { $task['free_busy'] = 'free'; } $success = $this->driver->edit_task($task); } else if (!empty($status)) { $existing['attendees'] = $task['attendees']; if ($status == 'declined') { // 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_tasklists'))) { $success = $this->driver->create_task($task); } else if ($status == 'declined') { $error_msg = null; } } else if ($status == 'declined' || $dontsave) { $error_msg = null; } else { $error_msg = $this->gettext('nowritetasklistfound'); } } if ($success || $dontsave) { if ($success) { $message = $task['_method'] == 'REPLY' ? 'attendeupdateesuccess' : ($deleted ? 'successremoval' : ($existing ? 'updatedsuccessfully' : 'importedsuccessfully')); $this->rc->output->command('display_message', $this->gettext(array('name' => $message, 'vars' => array('list' => $list['name']))), 'confirmation'); } $metadata['rsvp'] = intval($metadata['rsvp']); $metadata['after_action'] = $this->rc->config->get('calendar_itip_after_action', 0); $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 ($task['_method'] == 'REQUEST' && $organizer && !$noreply && !in_array(strtolower($organizer['email']), $emails) && !$error_msg) { $task['comment'] = $comment; $itip = $this->load_itip(); $itip->set_sender_email($reply_sender); if ($itip->send_itip_message($this->to_libcal($task), 'REPLY', $organizer, 'itipsubject' . $status, 'itipmailbody' . $status)) $this->rc->output->command('display_message', $this->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $organizer['name'] ?: $organizer['email']))), 'confirmation'); else $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error'); } $this->rc->output->send(); } /**** Task invitation plugin hooks ****/ /** * Handler for task/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(); } /** * Find a task in user tasklists */ protected function find_task($task, &$mode) { $this->load_driver(); // We search for writeable folders in personal namespace by default $mode = tasklist_driver::FILTER_WRITEABLE | tasklist_driver::FILTER_PERSONAL; $result = $this->driver->get_task($task, $mode); // ... now check shared folders if not found if (!$result) { $result = $this->driver->get_task($task, tasklist_driver::FILTER_WRITEABLE | tasklist_driver::FILTER_SHARED); if ($result) { $mode |= tasklist_driver::FILTER_SHARED; } } return $result; } /** * Handler for task/itip-status requests */ public function task_itip_status() { $data = rcube_utils::get_input_value('data', rcube_utils::INPUT_POST, true); // find local copy of the referenced task $existing = $this->find_task($data, $mode); $is_shared = $mode & tasklist_driver::FILTER_SHARED; $itip = $this->load_itip(); $response = $itip->get_itip_status($data, $existing); // get a list of writeable lists to save new tasks to if ((!$existing || $is_shared) && $response['action'] == 'rsvp' || $response['action'] == 'import') { $lists = $this->driver->get_lists($mode); $select = new html_select(array('name' => 'tasklist', 'id' => 'itip-saveto', 'is_escaped' => true, 'class' => 'form-control')); $select->add('--', ''); foreach ($lists as $list) { if ($list['editable']) { $select->add($list['name'], $list['id']); } } } if ($select) { $default_list = $this->get_default_tasklist($lists); $response['select'] = html::span('folder-select', $this->gettext('saveintasklist') . ' ' . $select->show($is_shared ? $existing['list'] : $default_list['id'])); } $this->rc->output->command('plugin.update_itip_object_status', $response); } /** * Handler for task/itip-remove requests */ public function task_itip_remove() { $success = false; $uid = rcube_utils::get_input_value('uid', rcube_utils::INPUT_POST); // search for event if only UID is given if ($task = $this->driver->get_task($uid)) { $success = $this->driver->delete_task($task, true); } if ($success) { $this->rc->output->show_message('tasklist.successremoval', 'confirmation'); } else { $this->rc->output->show_message('tasklist.errorsaving', 'error'); } } /******* Utility functions *******/ /** * 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)); } /** * Map task properties for ical exprort using libcalendaring */ public function to_libcal($task) { $object = $task; $object['_type'] = 'task'; $object['categories'] = (array)$task['tags']; // convert to datetime objects if (!empty($task['date'])) { $object['due'] = rcube_utils::anytodatetime($task['date'].' '.$task['time'], $this->timezone); if (empty($task['time'])) $object['due']->_dateonly = true; unset($object['date']); } if (!empty($task['startdate'])) { $object['start'] = rcube_utils::anytodatetime($task['startdate'].' '.$task['starttime'], $this->timezone); if (empty($task['starttime'])) $object['start']->_dateonly = true; unset($object['startdate']); } $object['complete'] = $task['complete'] * 100; if ($task['complete'] == 1.0 && empty($task['complete'])) { $object['status'] = 'COMPLETED'; } if ($task['flagged']) { $object['priority'] = 1; } else if (empty($task['priority'])) { $object['priority'] = 0; } return $object; } /** * Convert task properties from ical parser to the internal format */ public function from_ical($vtodo) { $task = $vtodo; $task['tags'] = array_filter((array)$vtodo['categories']); $task['flagged'] = $vtodo['priority'] == 1; $task['complete'] = floatval($vtodo['complete'] / 100); // convert from DateTime to internal date format if (is_a($vtodo['due'], 'DateTime')) { $due = $this->lib->adjust_timezone($vtodo['due']); $task['date'] = $due->format('Y-m-d'); if (!$vtodo['due']->_dateonly) $task['time'] = $due->format('H:i'); } // convert from DateTime to internal date format if (is_a($vtodo['start'], 'DateTime')) { $start = $this->lib->adjust_timezone($vtodo['start']); $task['startdate'] = $start->format('Y-m-d'); if (!$vtodo['start']->_dateonly) $task['starttime'] = $start->format('H:i'); } if (is_a($vtodo['dtstamp'], 'DateTime')) { $task['changed'] = $vtodo['dtstamp']; } unset($task['categories'], $task['due'], $task['start'], $task['dtstamp']); return $task; } /** * Handler for user_delete plugin hook */ public function user_delete($args) { $this->load_driver(); return $this->driver->user_delete($args); } /** * 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; } }