diff --git a/phpstan.neon b/phpstan.neon index aecda91a..1a5b7695 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,38 +1,36 @@ parameters: bootstrapFiles: - phpstan.bootstrap.php excludePaths: - plugins/libkolab/vendor fileExtensions: - php - php.dist - inc ignoreErrors: - '#Access to an undefined property (calendar|tasklist)::\$driver#' - '#Access to an undefined property (calendar|tasklist)::\$itip#' - '#Access to an undefined property (calendar|tasklist)::\$ical#' - '#unknown class (kolabformat|Address|Alarm|Contact|ContactReference|Configuration|Email|RecurrenceRule|Key|Related|Url|Snippet|Telephone)#' - - '#Call to an undefined static method PEAR::raiseError#' - #- '#Class .* constructor invoked with 0 parameters#' - '#class (Address|Affiliation|Alarm|Attachment|Attendee|Duration|ContactReference|Configuration|Dictionary|Email|EmailReference|DayPos|FileDriver|Key|NameComponents|SnippetCollection|RecurrenceRule|Related|Relation|EventCal|Snippet|Telephone|Url|vector.*|cDatetime|XMLObject|CustomProperty) not found#i' - '#Call to method .* on an unknown class (Affiliation|Attachment|Attendee|cDateTime|Dictionary|EventCal|FileDriver|NameComponents|Relation|snippet|vector.*)#' - '#Call to static method .* on an unknown class jqueryui#' - '#Access to an undefined property Kolab2FA\\.*::\$(username|secret)#' - '#Unsafe call to private method Firebase\\JWT\\JWT::.*#' - '#Access to an undefined property Sabre\\VObject.*::\$.*#' - '#invalid .*type vector#' - '#(cDateTime|EventCal)#' paths: - plugins - level: 3 + level: 4 scanDirectories: - program/include - program/actions treatPhpDocTypesAsCertain: false diff --git a/plugins/calendar/calendar.php b/plugins/calendar/calendar.php index 1fff88f8..099e3267 100644 --- a/plugins/calendar/calendar.php +++ b/plugins/calendar/calendar.php @@ -1,4005 +1,4005 @@ * @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 . */ #[AllowDynamicProperties] class calendar extends rcube_plugin { public const FREEBUSY_UNKNOWN = 0; public const FREEBUSY_FREE = 1; public const FREEBUSY_BUSY = 2; public const FREEBUSY_TENTATIVE = 3; public const FREEBUSY_OOF = 4; public const SESSION_KEY = 'calendar_temp'; public $task = '?(?!logout).*'; /** @var rcmail */ 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 $dst_active; public $ui; public $event; public $invitestatus; 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, ]; private $token; // These are implemented with __get() // private $ical; // private $itip; // private $driver; /** * Plugin initialization. */ public function init() { $this->rc = rcmail::get_instance(); $this->register_task('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']); } elseif ($this->rc->action == 'feed' && !empty($_REQUEST['_cal'])) { $this->add_hook('startup', [$this, 'ical_feed_export']); } elseif ($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'); require $this->home . '/lib/calendar_ui.php'; // load localizations $this->add_texts('localization/', $this->rc->task == 'calendar' && (!$this->rc->action || $this->rc->action == 'print')); $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; $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()); } // A hack to replace "Edit/Share Calendar" label with "Edit calendar", for non-Kolab driver if ($args['task'] == 'calendar' && $this->rc->config->get('calendar_driver', 'database') !== 'kolab') { $merge = ['calendar.editcalendar' => $this->gettext('edcalendar')]; $this->rc->load_language(null, [], $merge); $this->rc->output->command('add_label', $merge); } } 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? } } } elseif ($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']); } elseif ($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']); } elseif ($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); $rsvp_actions = ['accepted','tentative','declined','delegated']; if ($this->rc->config->get('kolab_invitation_calendars')) { $rsvp_actions[] = 'needs-action'; } $this->itip->set_rsvp_actions($this->rc->config->get('calendar_rsvp_actions', $rsvp_actions)); } 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 */ public 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('calendar_resources_freebusy', !empty($this->rc->config->get('kolab_freebusy_server'))); $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 $p Original parameters * * @return array Modified parameters */ public 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 $p Original parameters * * @return array Modified parameters */ public 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; } $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)); $first_hour = $this->rc->config->get('calendar_first_hour', $this->defaults['calendar_first_hour']); $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']); $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)); $select_hours = new html_select(['name' => '_work_start', 'id' => $field_id]); for ($h = 0; $h < 24; $h++) { $select_hours->add(date($time_format, mktime($h, 0, 0)), $h); } $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) . 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 = ''; $field_id = 'rcmfd_alarm'; if (!isset($no_override['calendar_default_alarm_type'])) { $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'])) { $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(['name' => "_categories[$key]", 'class' => $field_class, 'size' => 30, 'disabled' => $this->driver->categoriesimmutable]); $category_color = new html_inputfield(['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']['categoriesdefault'] = [ '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 $p Original parameters * * @return array Modified parameters */ public 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 */ public 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; $jsenv = []; 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 = $jsenv[$id] ?? []; // @phpstan-ignore-line $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 */ public 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 (!empty($old['recurrence_id']) && !empty($event['_savemode']) && ($event['_savemode'] == 'all' || ($event['_savemode'] == 'future' && $action == 'remove' && empty($event['_decline']))) ) { $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; } elseif ($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; } elseif ($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; } elseif ($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; } elseif ($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; } elseif ($success) { $this->rc->output->show_message('calendar.successremoval', 'confirmation'); $got_msg = true; } // send cancellation for the main event if (isset($event['_savemode']) && $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 elseif (isset($event['_savemode']) && $event['_savemode'] == 'future' && !is_bool($success)) { $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; $reply_sender = null; foreach ($old['attendees'] as $i => $attendee) { if ($attendee['role'] == 'ORGANIZER') { $organizer = $attendee; } elseif (!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'); } } elseif ($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; $reply_sender = null; foreach ($event['attendees'] as $i => $attendee) { if ($attendee['role'] == 'ORGANIZER') { $organizer = $attendee; } elseif (!empty($attendee['email']) && in_array_nocase($attendee['email'], $emails)) { $reply_sender = $attendee['email']; } elseif (!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 ($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; } elseif ($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 (!empty($event['_savemode']) && $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 (!empty($event['_savemode']) && ($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'] ?? null; // 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']; } elseif (!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 = $event['_comment'] ?? null; $sent = $this->notify_attendees($event, $old, $action, $comment); if ($sent > 0) { $this->rc->output->show_message('calendar.itipsendsuccess', 'confirmation'); } elseif ($sent < 0) { $this->rc->output->show_message('calendar.errornotifying', 'error'); } } } } /** * Handler for load-requests from fullcalendar * This will return pure JSON formatted output */ public 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 = implode('/', $path); [$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']); } elseif (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 */ public function check_recent() { // NOP $this->rc->output->send(); } /** * Hook triggered when a contact is saved */ public function contact_update($p) { // clear birthdays calendar cache if (!empty($p['record']['birthday'])) { $cache = $this->rc->get_cache('calendar.birthdays', 'db'); $cache->remove(); } } /** * */ public 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]); } elseif (empty($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') . (!empty($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; */ public 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 */ public 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); } [$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; } /** * */ public 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(implode(';', $identity['emails'])), 'ownedResources' => ';' . strtolower(implode(';', $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 Events as array * @param bool $addcss Add CSS class names according to calendar and categories * * @return string JSON encoded events */ public 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; if (!empty($event['attendees'])) { foreach ((array) $event['attendees'] as $i => $attendee) { if (!empty($attendee['role']) && $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 (!isset($event['attendees']) || !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'] ?? null; $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'] ?? null), 'description' => strval($event['description'] ?? null), 'location' => strval($event['location'] ?? null), ] + $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 elseif ($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 !empty($event['description']) && 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; } elseif ($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']); } $eventid = 'cal-' . (!empty($event['id']) ? $event['id'] : 'new'); $handler = new kolab_attachments_handler(); $event['attachments'] = $handler->attachments_set(self::SESSION_KEY, $eventid, $event['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; } elseif (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 elseif ($organizer === false && $owner !== false) { $event['attendees'][$owner]['role'] = 'ORGANIZER'; unset($event['attendees'][$owner]['rsvp']); } // fallback to the selected identity elseif ($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) { $handler = new kolab_attachments_handler(); $handler->attachments_cleanup(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 = $action == 'remove' || (!empty($event['status']) && $event['status'] == 'CANCELLED' && ($old['status'] ?? '') != $event['status']); $event['cancelled'] = $is_cancelled; if ($rsvp === null) { $rsvp = !$old || ($event['sequence'] ?? 0) > ($old['sequence'] ?? 0); } $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) { [$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 $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) { [$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 $t_end = 0; 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) { [$from, $to, $type] = $slot; if ($from < $t_end && $to > $t) { $status = $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; } $dts = new DateTime('@' . $start); $dts->setTimezone($this->timezone); $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 $a Event A * @param array $b 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 = $a[$key] ?? null; $bv = $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 $event The event object to be altered * @param array $attendees List of hash arrays each represeting an updated/added attendee * @param array $removed List of attendees' addresses to remove */ public static function merge_attendee_data(&$event, $attendees, $removed = []) { 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 */ public 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 */ public 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 ?? null); $this->rc->output->send(); } /** * Deliver event data for a resource's calendar */ public 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 */ public 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); $calendars = null; // 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']) ); } elseif (!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 || (!empty($event['status']) && $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) ? implode("\n", array_slice($before, -3)) : html::div('event-row no-event', $this->gettext('noearlierevents')), '%after%' => !empty($after) ? implode("\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 */ public 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 elseif (!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'); } } elseif ($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'])) { /** @var rcube_message_header $header */ foreach ($p['messages'] as $header) { $part = new StdClass(); $part->mimetype = $header->ctype; if (libcalendaring::part_is_vcalendar($part)) { $header->list_flags['attachmentClass'] = 'ical'; } elseif (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; $dontsave = false; $existing = null; + $event_attendee = null; 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 = $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' => $event['_instance'] ?? null, 'changed' => is_object($event['changed']) ? $event['changed']->format('U') : 0, 'sequence' => intval($event['sequence'] ?? 0), 'fallback' => strtoupper((string) $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) { $attendee_role = $attendee['role'] ?? null; $attendee_email = $attendee['email'] ?? null; if ($attendee_role == 'ORGANIZER') { $organizer = $attendee; } elseif ($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 (empty($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']) { + if ($existing && $cal_id && $calendar['id'] != $existing['calendar']) { $existing = null; } // Use only free_busy values that make sense in this context (T853612) if (!in_array($event['free_busy'] ?? '', ['free', 'busy'])) { unset($event['free_busy']); } - $event_attendee = null; $update_attendees = []; 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; 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']) || empty($attendee['role']) || $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'][] = $delegatee['email']; } } } } // 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 elseif ( ($event['sequence'] >= $existing['sequence'] || $event['changed'] >= $existing['changed']) && $event_attendee ) { $existing['attendees'][] = $event_attendee; $success = $this->driver->update_attendees($existing, $update_attendees); } elseif (!$event_attendee) { $error_msg = $this->gettext('errorunknownattendee'); } else { $error_msg = $this->gettext('newerversionexists'); } } // delete the event when declined (#1670) elseif ($status == 'declined' && $delete) { $deleted = $this->driver->remove_event($existing, true); $success = true; } // import the (newer) event elseif ($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 && ($event_attendee['role'] ?? '') == 'NON-PARTICIPANT') ) { $event['free_busy'] = 'free'; } $success = $this->driver->edit_event($event); } elseif (!empty($status)) { $existing['attendees'] = $event['attendees']; if ($status == 'declined' || ($event_attendee && ($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'); } - } elseif (!$existing && ($status != 'declined' || $this->rc->config->get('kolab_invitation_calendars'))) { + } elseif (empty($existing) && ($status != 'declined' || $this->rc->config->get('kolab_invitation_calendars'))) { if ($status == 'declined' || ($event['status'] ?? '') == 'CANCELLED' || ($event_attendee && ($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 (empty($master)) { $event['calendar'] = $calendar['id']; $success = $this->driver->new_event($event); } } elseif ($status == 'declined') { $error_msg = null; } } elseif ($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'] = $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; } elseif ($error_msg) { $this->rc->output->command('display_message', $error_msg, 'error'); } // send iTip reply if ($event['_method'] == 'REQUEST' && !empty($organizer) && !$noreply && !$error_msg && !empty($reply_sender) && !in_array(strtolower($organizer['email']), $emails ?? []) ) { $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 */ public 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 ?? null, '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 */ public 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); // establish imap connection $imap = $this->rc->get_storage(); $imap->set_folder($mbox); if ($uid && $mime_id) { $part = $imap->get_message_part($uid, $mime_id); if ($part) { $events = $this->get_ical()->import($part); } } $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'); } elseif ($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 elseif (!empty($message->attachments) && !empty($this->driver->attachments)) { $handler = new kolab_attachments_handler(); $event['attachments'] = $handler->copy_mail_attachments(self::SESSION_KEY, 'cal-', $message); } $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(); [$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']; } elseif ($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/libcalendaring plugins are loaded $this->load_driver(); $driver_name = $this->rc->config->get('calendar_driver', 'database'); // Use kolabcalendaring/kolabformat to compute recurring events only with the Kolab driver if ($driver_name == 'kolab' && 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 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/caldav/caldav_calendar.php b/plugins/calendar/drivers/caldav/caldav_calendar.php index 165fd460..ff19b4fd 100644 --- a/plugins/calendar/drivers/caldav/caldav_calendar.php +++ b/plugins/calendar/drivers/caldav/caldav_calendar.php @@ -1,875 +1,879 @@ * * 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 caldav_calendar extends kolab_storage_dav_folder { public $ready = false; public $rights = 'lrs'; public $editable = false; public $attachments = true; public $alarms = false; public $history = false; public $subscriptions = false; public $categories = []; public $storage; public $type = 'event'; protected $cal; protected $events = []; protected $search_fields = ['title', 'description', 'location', 'attendees', 'categories']; /** * Factory method to instantiate a caldav_calendar object * * @param string $id Calendar ID (encoded IMAP folder name) * @param calendar $calendar Calendar plugin object * * @return caldav_calendar Self instance */ public static function factory($id, $calendar) { return new caldav_calendar($id, $calendar); } /** * Default constructor */ public function __construct($folder_or_id, $calendar) { if ($folder_or_id instanceof kolab_storage_dav_folder) { $this->storage = $folder_or_id; } else { // $this->storage = kolab_storage_dav::get_folder($folder_or_id, 'event'); } $this->cal = $calendar; $this->ready = !empty($this->storage); // Set writeable and alarms flags according to folder permissions if ($this->ready) { $this->id = $this->storage->id; $this->attributes = $this->storage->attributes; $this->default = $this->storage->default; $this->subtype = $this->storage->subtype; $this->alarms = !isset($this->attributes['alarms']) || $this->attributes['alarms']; if ($this->storage->get_namespace() == 'personal') { $this->editable = true; $this->rights = 'lrswikxteav'; } else { $rights = $this->storage->get_myrights(); if ($rights) { $this->rights = $rights; if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false) { $this->editable = strpos($rights, 'i'); ; } } } } } /** * Getter for the folder name * * @return string Name of the folder */ public function get_realname() { return $this->get_name(); } /** * Return color to display this calendar */ public function get_color($default = null) { if ($color = $this->storage->get_color()) { return $color; } return $default ?: 'cc0000'; } /** * Compose an URL for CalDAV access to this calendar (if configured) */ public function get_caldav_url() { /* if ($template = $this->cal->rc->config->get('calendar_caldav_url', null)) { return strtr($template, [ '%h' => $_SERVER['HTTP_HOST'], '%u' => urlencode($this->cal->rc->get_user_name()), '%i' => urlencode($this->storage->get_uid()), '%n' => urlencode($this->name), ]); } */ return false; } /** * Update properties of this calendar folder * * @see caldav_driver::edit_calendar() */ public function update(&$prop) { return false; // NOP } /** * Getter for a single event object */ public function get_event($id) { // remove our occurrence identifier if it's there $master_id = preg_replace('/-\d{8}(T\d{6})?$/', '', $id); // directly access storage object if (empty($this->events[$id]) && $master_id == $id && ($record = $this->storage->get_object($id))) { $this->events[$id] = $record = $this->_to_driver_event($record, true); } // maybe a recurring instance is requested if (empty($this->events[$id]) && $master_id != $id) { $instance_id = substr($id, strlen($master_id) + 1); if ($record = $this->storage->get_object($master_id)) { $master = $record = $this->_to_driver_event($record); } if (!empty($master)) { // check for match on the first instance already if (!empty($master['_instance']) && $master['_instance'] == $instance_id) { $this->events[$id] = $master; } elseif (!empty($master['recurrence'])) { $start_date = $master['start']; // For performance reasons we'll get only the specific instance if (($date = substr($id, strlen($master_id) + 1, 8)) && strlen($date) == 8 && is_numeric($date)) { $start_date = new DateTime($date . 'T000000', $master['start']->getTimezone()); } $this->get_recurring_events($record, $start_date, null, $id, 1); } } } return $this->events[$id] ?? null; } /** * Get attachment body * @see calendar_driver::get_attachment_body() */ public function get_attachment_body($id, $event) { $event = $this->get_event($event['id']); $data = $this->storage->get_attachment($id, $event); /* if ($data === false) { // try again with master UID $uid = preg_replace('/-\d+(T\d{6})?$/', '', $event['id']); if ($uid != $event['id']) { $data = $this->storage->get_attachment($uid, $id); // TODO } } */ return $data; } /** * @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 bool $virtual Include virtual events (optional) * @param array $query Additional parameters to query storage * @param array $filter_query Additional query to filter events * * @return array A list of event records */ public function list_events($start, $end, $search = null, $virtual = true, $query = [], $filter_query = null) { // convert to DateTime for comparisons // #5190: make the range a little bit wider // to workaround possible timezone differences try { $start = new DateTime('@' . ($start - 12 * 3600)); } catch (Exception $e) { $start = new DateTime('@0'); } try { $end = new DateTime('@' . ($end + 12 * 3600)); } catch (Exception $e) { $end = new DateTime('today +10 years'); } // get email addresses of the current user $user_emails = $this->cal->get_user_emails(); // query Kolab storage $query[] = ['dtstart', '<=', $end]; $query[] = ['dtend', '>=', $start]; if (is_array($filter_query)) { $query = array_merge($query, $filter_query); } $words = []; $partstat_exclude = []; $events = []; if (!empty($search)) { $search = mb_strtolower($search); $words = rcube_utils::tokenize_string($search, 1); foreach (rcube_utils::normalize_string($search, true) as $word) { $query[] = ['words', 'LIKE', $word]; } } // set partstat filter to skip pending and declined invitations if (empty($filter_query) && $this->cal->rc->config->get('kolab_invitation_calendars') && $this->get_namespace() != 'other' ) { $partstat_exclude = ['NEEDS-ACTION', 'DECLINED']; } foreach ($this->storage->select($query) as $record) { if (empty($record)) { continue; } $event = $this->_to_driver_event($record, !$virtual, false); // remember seen categories if (!empty($event['categories'])) { $cat = is_array($event['categories']) ? $event['categories'][0] : $event['categories']; $this->categories[$cat]++; } // list events in requested time window if ($event['start'] <= $end && $event['end'] >= $start) { unset($event['_attendees']); $add = true; // skip the first instance of a recurring event if listed in exdate if ($virtual && !empty($event['recurrence']['EXDATE'])) { $event_date = $event['start']->format('Ymd'); $event_tz = $event['start']->getTimezone(); foreach ((array) $event['recurrence']['EXDATE'] as $exdate) { $ex = clone $exdate; $ex->setTimezone($event_tz); if ($ex->format('Ymd') == $event_date) { $add = false; break; } } } // find and merge exception for the first instance if ($virtual && !empty($event['recurrence']) && !empty($event['recurrence']['EXCEPTIONS'])) { foreach ($event['recurrence']['EXCEPTIONS'] as $exception) { if (libcalendaring::is_recurrence_exception($event, $exception)) { unset($exception['calendar'], $exception['className'], $exception['_folder_id']); // clone date objects from main event before adjusting them with exception data if (is_object($event['start'])) { $event['start'] = clone $record['start']; } if (is_object($event['end'])) { $event['end'] = clone $record['end']; } kolab_driver::merge_exception_data($event, $exception); } } } if ($add) { $events[] = $event; } } // resolve recurring events if (!empty($event['recurrence']) && $virtual == 1) { $events = array_merge($events, $this->get_recurring_events($event, $start, $end)); } // add top-level exceptions (aka loose single occurrences) elseif (!empty($record['exceptions'])) { foreach ($record['exceptions'] as $ex) { $component = $this->_to_driver_event($ex, false, false, $record); if ($component['start'] <= $end && $component['end'] >= $start) { $events[] = $component; } } } } // post-filter all events by fulltext search and partstat values $me = $this; $events = array_filter($events, function ($event) use ($words, $partstat_exclude, $user_emails, $me) { // fulltext search if (count($words)) { $hits = 0; foreach ($words as $word) { $hits += $me->fulltext_match($event, $word, false); } if ($hits < count($words)) { return false; } } // partstat filter if (count($partstat_exclude) && !empty($event['attendees'])) { foreach ($event['attendees'] as $attendee) { if ( in_array($attendee['email'], $user_emails) && in_array($attendee['status'], $partstat_exclude) ) { return false; } } } return true; }); // Apply event-to-mail relations // $config = kolab_storage_config::get_instance(); // $config->apply_links($events); return $events; } /** * Get number of events in the given calendar * * @param int $start Date range start (unix timestamp) * @param int $end Date range end (unix timestamp) * @param array $filter_query Additional query to filter events * * @return int Number of events */ public function count_events($start, $end = null, $filter_query = null) { // convert to DateTime for comparisons try { $start = new DateTime('@' . $start); } catch (Exception $e) { $start = new DateTime('@0'); } if ($end) { try { $end = new DateTime('@' . $end); } catch (Exception $e) { $end = null; } } // query Kolab storage $query[] = ['dtend', '>=', $start]; if ($end) { $query[] = ['dtstart', '<=', $end]; } // add query to exclude pending/declined invitations if (empty($filter_query)) { foreach ($this->cal->get_user_emails() as $email) { $query[] = ['tags', '!=', 'x-partstat:' . $email . ':needs-action']; $query[] = ['tags', '!=', 'x-partstat:' . $email . ':declined']; } } elseif (is_array($filter_query)) { $query = array_merge($query, $filter_query); } return $this->storage->count($query); } /** * Create a new event record * * @see calendar_driver::new_event() * * @return array|false The created record ID on success, False on error */ public function insert_event($event) { if (!is_array($event)) { return false; } // email links are stored separately // $links = !empty($event['links']) ? $event['links'] : []; // unset($event['links']); // generate new event from RC input $object = $this->_from_driver_event($event); $saved = $this->storage->save($object, 'event'); if (!$saved) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving event object to DAV server", ], true, false ); return false; } // save links in configuration.relation object // if ($this->save_links($event['uid'], $links)) { // $object['links'] = $links; // } $this->events = [$event['uid'] => $this->_to_driver_event($object, true)]; return $saved; } /** * Update a specific event record * * @return bool True on success, False on error */ public function update_event($event, $exception_id = null) { $updated = false; $old = $this->storage->get_object(!empty($event['uid']) ? $event['uid'] : $event['id']); if (!$old || PEAR::isError($old)) { return false; } // email links are stored separately // $links = !empty($event['links']) ? $event['links'] : []; // unset($event['links']); $object = $this->_from_driver_event($event, $old); $object['created'] = $old['created'] ?? null; $saved = $this->storage->save($object, 'event', $old['uid']); if (!$saved) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving event object to CalDAV server", ], true, false ); } else { // save links in configuration.relation object // if ($this->save_links($event['uid'], $links)) { // $object['links'] = $links; // } $updated = true; $this->events = [$event['uid'] => $this->_to_driver_event($object, true)]; // refresh local cache with recurring instances if ($exception_id) { $this->get_recurring_events($object, $event['start'], $event['end'], $exception_id); } } return $updated; } /** * Delete an event record * * @see calendar_driver::remove_event() * * @return bool True on success, False on error */ public function delete_event($event, $force = true) { $uid = !empty($event['uid']) ? $event['uid'] : $event['id']; $deleted = $this->storage->delete($uid, $force); if (!$deleted) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error deleting event '{$uid}' from CalDAV server", ], true, false ); } return $deleted; } /** * Restore deleted event record * * @see calendar_driver::undelete_event() * * @return bool True on success, False on error */ public function restore_event($event) { // TODO return false; } /** * Find messages linked with an event */ protected function get_links($uid) { return []; // TODO + /* $storage = kolab_storage_config::get_instance(); return $storage->get_object_links($uid); + */ } /** * Save message references (links) to an event */ protected function save_links($uid, $links) { return false; // TODO + /* $storage = kolab_storage_config::get_instance(); return $storage->save_object_links($uid, (array) $links); + */ } /** * Create instances of a recurring event * * @param array $event Hash array with event properties * @param DateTime $start Start date of the recurrence window * @param ?DateTime $end End date of the recurrence window * @param string $event_id ID of a specific recurring event instance * @param int $limit Max. number of instances to return * * @return array List of recurring event instances */ public function get_recurring_events($event, $start, $end = null, $event_id = null, $limit = null) { // determine a reasonable end date if none given if (!$end) { $end = clone $event['start']; $end->add(new DateInterval('P100Y')); } // read recurrence exceptions first $events = []; $exdata = []; $futuredata = []; $recurrence_id_format = libcalendaring::recurrence_id_format($event); $recurrence_rule = null; if (!empty($event['recurrence'])) { // copy the recurrence rule from the master event (to be used in the UI) $recurrence_rule = $event['recurrence']; unset($recurrence_rule['EXCEPTIONS'], $recurrence_rule['EXDATE']); if (!empty($event['recurrence']['EXCEPTIONS'])) { foreach ($event['recurrence']['EXCEPTIONS'] as $exception) { if (empty($exception['_instance'])) { $exception['_instance'] = libcalendaring::recurrence_instance_identifier($exception, !empty($event['allday'])); } $rec_event = $this->_to_driver_event($exception, false, false, $event); $rec_event['id'] = $event['uid'] . '-' . $exception['_instance']; $rec_event['isexception'] = 1; // found the specifically requested instance: register exception (single occurrence wins) if ( $rec_event['id'] == $event_id && (empty($this->events[$event_id]) || !empty($this->events[$event_id]['thisandfuture'])) ) { $rec_event['recurrence'] = $recurrence_rule; $rec_event['recurrence_id'] = $event['uid']; $this->events[$rec_event['id']] = $rec_event; } // remember this exception's date $exdate = substr($exception['_instance'], 0, 8); if (empty($exdata[$exdate]) || !empty($exdata[$exdate]['thisandfuture'])) { $exdata[$exdate] = $rec_event; } if (!empty($rec_event['thisandfuture'])) { $futuredata[$exdate] = $rec_event; } } } } // found the specifically requested instance, exiting... if ($event_id && !empty($this->events[$event_id])) { return [$this->events[$event_id]]; } // Check first occurrence, it might have been moved if (!empty($exdata[$event['start']->format('Ymd')])) { $first = $exdata[$event['start']->format('Ymd')]; // return it only if not already in the result, but in the requested period if (!($event['start'] <= $end && $event['end'] >= $start) && ($first['start'] <= $end && $first['end'] >= $start) ) { $events[] = $first; } } if ($limit && count($events) >= $limit) { return $events; } // use libcalendaring to compute recurring events $recurrence = libcalendaring::get_recurrence($event); $i = 0; while ($next_event = $recurrence->next_instance()) { $datestr = $next_event['start']->format('Ymd'); $instance_id = $next_event['start']->format($recurrence_id_format); // use this event data for future recurring instances $overlay_data = $futuredata[$datestr] ?? null; $rec_id = $event['uid'] . '-' . $instance_id; $exception = !empty($exdata[$datestr]) ? $exdata[$datestr] : $overlay_data; $event_start = $next_event['start']; $event_end = $next_event['end']; // copy some event from exception to get proper start/end dates if ($exception) { $event_copy = $next_event; caldav_driver::merge_exception_dates($event_copy, $exception); $event_start = $event_copy['start']; $event_end = $event_copy['end']; } // add to output if in range if (($event_start <= $end && $event_end >= $start) || ($event_id && $rec_id == $event_id)) { $rec_event = $this->_to_driver_event($next_event, false, false, $event); $rec_event['_instance'] = $instance_id; $rec_event['_count'] = $i + 1; if ($exception) { // copy data from exception caldav_driver::merge_exception_data($rec_event, $exception); } $rec_event['id'] = $rec_id; $rec_event['recurrence_id'] = $event['uid']; $rec_event['recurrence'] = $recurrence_rule; unset($rec_event['_attendees']); $events[] = $rec_event; if ($rec_id == $event_id) { $this->events[$rec_id] = $rec_event; break; } if ($limit && count($events) >= $limit) { return $events; } } elseif ($next_event['start'] > $end) { // stop loop if out of range break; } // avoid endless recursion loops if (++$i > 100000) { break; } } return $events; } /** * Convert from storage format to internal representation */ private function _to_driver_event($record, $noinst = false, $links = true, $master_event = null) { $record['calendar'] = $this->id; // remove (possibly outdated) cached parameters unset($record['_folder_id'], $record['className']); // if ($links && !array_key_exists('links', $record)) { // $record['links'] = $this->get_links($record['uid']); // } $ns = $this->get_namespace(); if ($ns == 'other') { $record['className'] = 'fc-event-ns-other'; } if ($ns == 'other' || !$this->cal->rc->config->get('kolab_invitation_calendars')) { $record = caldav_driver::add_partstat_class($record, ['NEEDS-ACTION', 'DECLINED'], $this->get_owner()); // Modify invitation status class name, when invitation calendars are disabled // we'll use opacity only for declined/needs-action events $record['className'] = !empty($record['className']) ? str_replace('-invitation', '', $record['className']) : ''; } // add instance identifier to first occurrence (master event) $recurrence_id_format = libcalendaring::recurrence_id_format($master_event ? $master_event : $record); if (!$noinst && !empty($record['recurrence']) && !empty($record['start']) && empty($record['recurrence_id']) && empty($record['_instance']) ) { $record['_instance'] = $record['start']->format($recurrence_id_format); } elseif (isset($record['recurrence_date']) && $record['recurrence_date'] instanceof DateTimeInterface) { $record['_instance'] = $record['recurrence_date']->format($recurrence_id_format); } // clean up exception data if (!empty($record['recurrence']) && !empty($record['recurrence']['EXCEPTIONS'])) { array_walk($record['recurrence']['EXCEPTIONS'], function (&$exception) { unset($exception['_attachments']); }); } return $record; } /** * Convert the given event record into a data structure that can be passed to the storage backend for saving * (opposite of self::_to_driver_event()) */ private function _from_driver_event($event, $old = []) { // set current user as ORGANIZER if ($identity = $this->cal->rc->user->list_emails(true)) { $event['attendees'] = !empty($event['attendees']) ? $event['attendees'] : []; $found = false; // there can be only resources on attendees list (T1484) // let's check the existence of an organizer foreach ($event['attendees'] as $attendee) { if (!empty($attendee['role']) && $attendee['role'] == 'ORGANIZER') { $found = true; break; } } if (!$found) { $event['attendees'][] = ['role' => 'ORGANIZER', 'name' => $identity['name'], 'email' => $identity['email']]; } $event['_owner'] = $identity['email']; } // remove EXDATE values if RDATE is given if (!empty($event['recurrence']['RDATE'])) { $event['recurrence']['EXDATE'] = []; } // remove recurrence information (e.g. EXDATES and EXCEPTIONS) entirely if (!empty($event['recurrence']) && empty($event['recurrence']['FREQ']) && empty($event['recurrence']['RDATE'])) { $event['recurrence'] = []; } // keep 'comment' from initial itip invitation if (!empty($old['comment'])) { $event['comment'] = $old['comment']; } // remove some internal properties which should not be cached $cleanup_fn = function (&$event) { unset($event['_savemode'], $event['_fromcalendar'], $event['_identity'], $event['_folder_id'], $event['calendar'], $event['className'], $event['recurrence_id'], $event['attachments'], $event['deleted_attachments']); }; $cleanup_fn($event); // clean up exception data if (!empty($event['exceptions'])) { array_walk($event['exceptions'], $cleanup_fn); } // copy meta data (starting with _) from old object foreach ((array) $old as $key => $val) { if (!isset($event[$key]) && $key[0] == '_') { $event[$key] = $val; } } return $event; } /** * Match the given word in the event contents */ public function fulltext_match($event, $word, $recursive = true) { $hits = 0; foreach ($this->search_fields as $col) { if (empty($event[$col])) { continue; } $sval = is_array($event[$col]) ? self::_complex2string($event[$col]) : $event[$col]; if (empty($sval)) { continue; } // do a simple substring matching (to be improved) $val = mb_strtolower($sval); if (strpos($val, $word) !== false) { $hits++; break; } } return $hits; } /** * Convert a complex event attribute to a string value */ private static function _complex2string($prop) { static $ignorekeys = ['role', 'status', 'rsvp']; $out = ''; if (is_array($prop)) { foreach ($prop as $key => $val) { if (is_numeric($key)) { $out .= self::_complex2string($val); } elseif (!in_array($key, $ignorekeys)) { $out .= $val . ' '; } } } elseif (is_string($prop) || is_numeric($prop)) { $out .= $prop . ' '; } return rtrim($out); } } diff --git a/plugins/calendar/drivers/caldav/caldav_driver.php b/plugins/calendar/drivers/caldav/caldav_driver.php index 85727b0b..43aa3b59 100644 --- a/plugins/calendar/drivers/caldav/caldav_driver.php +++ b/plugins/calendar/drivers/caldav/caldav_driver.php @@ -1,689 +1,690 @@ * * 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 . */ require_once(__DIR__ . '/../kolab/kolab_driver.php'); class caldav_driver extends kolab_driver { // features this backend supports public $alarms = true; public $attendees = true; public $freebusy = true; public $attachments = true; public $undelete = false; // TODO public $alarm_types = ['DISPLAY', 'AUDIO']; public $categoriesimmutable = true; protected $scheduling_properties = ['start', 'end', 'location']; /** * Default constructor */ public function __construct($cal) { $cal->require_plugin('libkolab'); // load helper classes *after* libkolab has been loaded (#3248) require_once(__DIR__ . '/caldav_calendar.php'); // require_once(__DIR__ . '/kolab_user_calendar.php'); // require_once(__DIR__ . '/caldav_invitation_calendar.php'); $this->cal = $cal; $this->rc = $cal->rc; // Initialize the CalDAV storage $url = $this->rc->config->get('calendar_caldav_server', 'http://localhost'); $this->storage = new kolab_storage_dav($url); $this->cal->register_action('push-freebusy', [$this, 'push_freebusy']); $this->cal->register_action('calendar-acl', [$this, 'calendar_acl']); // $this->freebusy_trigger = $this->rc->config->get('calendar_freebusy_trigger', false); if (!$this->rc->config->get('kolab_freebusy_server', false)) { $this->freebusy = false; } // TODO: get configuration for the Bonnie API // $this->bonnie_api = libkolab::get_bonnie_api(); } /** * Read available calendars from server */ protected function _read_calendars() { // already read sources if (isset($this->calendars)) { return $this->calendars; } // get all folders that support VEVENT, sorted by namespace/name $folders = $this->storage->get_folders('event'); // + $this->storage->get_user_folders('event', true); $this->calendars = []; foreach ($folders as $folder) { $calendar = $this->_to_calendar($folder); if ($calendar->ready) { $this->calendars[$calendar->id] = $calendar; if ($calendar->editable) { $this->has_writeable = true; } } } return $this->calendars; } /** * Convert kolab_storage_folder into caldav_calendar * * @return caldav_calendar|kolab_user_calendar */ protected function _to_calendar($folder) { if ($folder instanceof caldav_calendar) { return $folder; } if ($folder instanceof kolab_storage_folder_user) { $calendar = new kolab_user_calendar($folder, $this->cal); $calendar->subscriptions = count($folder->children) > 0; } else { $calendar = new caldav_calendar($folder, $this->cal); } return $calendar; } /** * Get a list of available calendars from this source. * - * @param int $filter Bitmask defining filter criterias - * @param object $tree Reference to hierarchical folder tree object + * @param int $filter Bitmask defining filter criterias + * @param ?kolab_storage_folder_virtual $tree Reference to hierarchical folder tree object * * @return array List of calendars */ public function list_calendars($filter = 0, &$tree = null) { $this->_read_calendars(); $folders = $this->filter_calendars($filter); $calendars = []; $prefs = $this->rc->config->get('kolab_calendars', []); // include virtual folders for a full folder tree /* - if (!is_null($tree)) { - $folders = $this->storage->folder_hierarchy($folders, $tree); - } + if (!is_null($tree)) { + $folders = $this->storage->folder_hierarchy($folders, $tree); + } */ $parents = array_keys($this->calendars); foreach ($folders as $id => $cal) { $parent_id = null; /* $path = explode('/', $cal->name); // find parent do { array_pop($path); $parent_id = $this->storage->folder_id(implode('/', $path)); } while (count($path) > 1 && !in_array($parent_id, $parents)); // restore "real" parent ID if ($parent_id && !in_array($parent_id, $parents)) { $parent_id = $this->storage->folder_id($cal->get_parent()); } $parents[] = $cal->id; if ($cal instanceof kolab_storage_folder_virtual) { $calendars[$cal->id] = [ 'id' => $cal->id, 'name' => $cal->get_name(), 'listname' => $cal->get_foldername(), 'editname' => $cal->get_foldername(), 'virtual' => true, 'editable' => false, 'group' => $cal->get_namespace(), ]; } else { */ // additional folders may come from kolab_storage_dav::folder_hierarchy() above // make sure we deal with caldav_calendar instances $cal = $this->_to_calendar($cal); $this->calendars[$cal->id] = $cal; $is_user = false; // ($cal instanceof caldav_user_calendar); $calendars[$cal->id] = [ 'id' => $cal->id, 'name' => $cal->get_name(), 'listname' => $cal->get_foldername(), 'editname' => $cal->get_foldername(), 'title' => '', // $cal->get_title(), 'color' => $cal->get_color(), 'editable' => $cal->editable, - 'group' => $is_user ? 'other user' : $cal->get_namespace(), + 'group' => $is_user ? 'other user' : $cal->get_namespace(), // @phpstan-ignore-line 'active' => !isset($prefs[$cal->id]['active']) || !empty($prefs[$cal->id]['active']), 'owner' => $cal->get_owner(), 'removable' => !$cal->default, // extras to hide some elements in the UI 'subscriptions' => $cal->subscriptions, 'driver' => 'caldav', ]; + // @phpstan-ignore-next-line if (!$is_user) { $calendars[$cal->id] += [ 'default' => $cal->default, 'rights' => $cal->rights, 'showalarms' => $cal->alarms, 'history' => !empty($this->bonnie_api), 'children' => true, // TODO: determine if that folder indeed has child folders 'parent' => $parent_id, 'subtype' => $cal->subtype, 'caldavurl' => '', // $cal->get_caldav_url(), ]; } /* } */ if ($cal->subscriptions) { $calendars[$cal->id]['subscribed'] = $cal->is_subscribed(); } } /* // list virtual calendars showing invitations if ($this->rc->config->get('kolab_invitation_calendars') && !($filter & self::FILTER_INSERTABLE)) { foreach ([self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED] as $id) { $cal = new caldav_invitation_calendar($id, $this->cal); if (!($filter & self::FILTER_ACTIVE) || $cal->is_active()) { $calendars[$id] = [ 'id' => $cal->id, 'name' => $cal->get_name(), 'listname' => $cal->get_name(), 'editname' => $cal->get_foldername(), 'title' => $cal->get_title(), 'color' => $cal->get_color(), 'editable' => $cal->editable, 'rights' => $cal->rights, 'showalarms' => $cal->alarms, 'history' => !empty($this->bonnie_api), 'group' => 'x-invitations', 'default' => false, 'active' => $cal->is_active(), 'owner' => $cal->get_owner(), 'children' => false, 'counts' => $id == self::INVITATIONS_CALENDAR_PENDING, ]; if (is_object($tree)) { $tree->children[] = $cal; } } } } */ // append the virtual birthdays calendar if ($this->rc->config->get('calendar_contact_birthdays', false) && !($filter & self::FILTER_INSERTABLE)) { $id = self::BIRTHDAY_CALENDAR_ID; $prefs = $this->rc->config->get('kolab_calendars', []); // read local prefs if (!($filter & self::FILTER_ACTIVE) || !empty($prefs[$id]['active'])) { $calendars[$id] = [ 'id' => $id, 'name' => $this->cal->gettext('birthdays'), 'listname' => $this->cal->gettext('birthdays'), 'color' => !empty($prefs[$id]['color']) ? $prefs[$id]['color'] : '87CEFA', 'active' => !empty($prefs[$id]['active']), 'showalarms' => (bool) $this->rc->config->get('calendar_birthdays_alarm_type'), 'group' => 'x-birthdays', 'editable' => false, 'default' => false, 'children' => false, 'history' => false, ]; } } return $calendars; } /** * Get the caldav_calendar instance for the given calendar ID * * @param string $id Calendar identifier * * @return caldav_calendar|caldav_invitation_calendar|null Object nor null if calendar doesn't exist */ public function get_calendar($id) { $this->_read_calendars(); // create calendar object if necessary if (empty($this->calendars[$id])) { if (in_array($id, [self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED])) { return new caldav_invitation_calendar($id, $this->cal); } // for unsubscribed calendar folders if ($id !== self::BIRTHDAY_CALENDAR_ID) { $calendar = caldav_calendar::factory($id, $this->cal); if ($calendar->ready) { $this->calendars[$calendar->id] = $calendar; } } } return !empty($this->calendars[$id]) ? $this->calendars[$id] : null; } /** * Create a new calendar assigned to the current user * * @param array $prop Hash array with calendar properties * name: Calendar name * color: The color of the calendar * * @return mixed ID of the calendar on success, False on error */ public function create_calendar($prop) { $prop['type'] = 'event'; $prop['alarms'] = !empty($prop['showalarms']); $id = $this->storage->folder_update($prop); if ($id === false) { return false; } $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []); $prefs['kolab_calendars'][$id]['active'] = true; $this->rc->user->save_prefs($prefs); return $id; } /** * Update properties of an existing calendar * * @see calendar_driver::edit_calendar() */ public function edit_calendar($prop) { $id = $prop['id']; if (!in_array($id, [self::BIRTHDAY_CALENDAR_ID, self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED])) { $prop['type'] = 'event'; $prop['alarms'] = !empty($prop['showalarms']); return $this->storage->folder_update($prop) !== false; } // fallback to local prefs for special calendars $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []); unset($prefs['kolab_calendars'][$id]['showalarms']); if (isset($prop['showalarms']) && $id == self::BIRTHDAY_CALENDAR_ID) { $prefs['calendar_birthdays_alarm_type'] = $prop['showalarms'] ? $this->alarm_types[0] : ''; } elseif (isset($prop['showalarms'])) { $prefs['kolab_calendars'][$id]['showalarms'] = !empty($prop['showalarms']); } if (!empty($prefs['kolab_calendars'][$id])) { $this->rc->user->save_prefs($prefs); } return true; } /** * Set active/subscribed state of a calendar * * @see calendar_driver::subscribe_calendar() */ public function subscribe_calendar($prop) { if (empty($prop['id'])) { return false; } // save state in local prefs if (isset($prop['active'])) { $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []); $prefs['kolab_calendars'][$prop['id']]['active'] = !empty($prop['active']); $this->rc->user->save_prefs($prefs); } return true; } /** * Delete the given calendar with all its contents * * @see calendar_driver::delete_calendar() */ public function delete_calendar($prop) { if (!empty($prop['id'])) { if ($this->storage->folder_delete($prop['id'], 'event')) { // remove folder from user prefs $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []); if (isset($prefs['kolab_calendars'][$prop['id']])) { unset($prefs['kolab_calendars'][$prop['id']]); $this->rc->user->save_prefs($prefs); } return true; } } return false; } /** * Search for shared or otherwise not listed calendars the user has access * * @param string $query Search string * @param string $source Section/source to search * * @return array List of calendars */ public function search_calendars($query, $source) { $this->calendars = []; $this->search_more_results = false; /* // find unsubscribed IMAP folders that have "event" type if ($source == 'folders') { foreach ((array) $this->storage->search_folders('event', $query, ['other']) as $folder) { $calendar = new kolab_calendar($folder->name, $this->cal); $this->calendars[$calendar->id] = $calendar; } } // find other user's virtual calendars else if ($source == 'users') { // we have slightly more space, so display twice the number $limit = $this->rc->config->get('autocomplete_max', 15) * 2; foreach ($this->storage->search_users($query, 0, [], $limit, $count) as $user) { $calendar = new caldav_user_calendar($user, $this->cal); $this->calendars[$calendar->id] = $calendar; // search for calendar folders shared by this user foreach ($this->storage->list_user_folders($user, 'event', false) as $foldername) { $cal = new caldav_calendar($foldername, $this->cal); $this->calendars[$cal->id] = $cal; $calendar->subscriptions = true; } } if ($count > $limit) { $this->search_more_results = true; } } // don't list the birthday calendar $this->rc->config->set('calendar_contact_birthdays', false); $this->rc->config->set('kolab_invitation_calendars', false); */ return $this->list_calendars(); } /** * Get events from source. * * @param int $start Event's new start (unix timestamp) * @param int $end Event's new end (unix timestamp) * @param string $search 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 events (optional) * @param int $modifiedsince Only list events modified since this time (unix timestamp) * * @return array A list of event records */ public function load_events($start, $end, $search = null, $calendars = null, $virtual = true, $modifiedsince = null) { if ($calendars && is_string($calendars)) { $calendars = explode(',', $calendars); } elseif (!$calendars) { $this->_read_calendars(); $calendars = array_keys($this->calendars); } $query = []; $events = []; $categories = []; if ($modifiedsince) { $query[] = ['changed', '>=', $modifiedsince]; } foreach ($calendars as $cid) { if ($storage = $this->get_calendar($cid)) { $events = array_merge($events, $storage->list_events($start, $end, $search, $virtual, $query)); $categories += $storage->categories; } } // add events from the address books birthday calendar if (in_array(self::BIRTHDAY_CALENDAR_ID, $calendars)) { $events = array_merge($events, $this->load_birthday_events($start, $end, $search, $modifiedsince)); } // add new categories to user prefs $old_categories = $this->rc->config->get('calendar_categories', $this->default_categories); $newcats = array_udiff( array_keys($categories), array_keys($old_categories), function ($a, $b) { return strcasecmp($a, $b); } ); if (!empty($newcats)) { foreach ($newcats as $category) { $old_categories[$category] = ''; // no color set yet } $this->rc->user->save_prefs(['calendar_categories' => $old_categories]); } array_walk($events, 'caldav_driver::to_rcube_event'); return $events; } /** * Create instances of a recurring event * * @param array $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) { $this->_read_calendars(); $storage = reset($this->calendars); return $storage->get_recurring_events($event, $start, $end); } /** * */ protected function get_recurrence_count($event, $dtstart) { // use libkolab to compute recurring events $recurrence = libcalendaring::get_recurrence($event); $count = 0; while (($next_event = $recurrence->next_instance()) && $next_event['start'] <= $dtstart && $count < 1000) { $count++; } return $count; } /** * Determine whether the current change affects scheduling and reset attendee status accordingly */ protected function check_scheduling(&$event, $old, $update = true) { // skip this check when importing iCal/iTip events if (isset($event['sequence']) || !empty($event['_method'])) { return false; } // iterate through the list of properties considered 'significant' for scheduling $reschedule = $this->is_rescheduling_needed($event, $old); // reset all attendee status to needs-action (#4360) if ($update && $reschedule && !empty($event['attendees'])) { $is_organizer = false; $emails = $this->cal->get_user_emails(); $attendees = $event['attendees']; foreach ($attendees as $i => $attendee) { if ($attendee['role'] == 'ORGANIZER' && !empty($attendee['email']) && in_array(strtolower($attendee['email']), $emails) ) { $is_organizer = true; } elseif ($attendee['role'] != 'ORGANIZER' && $attendee['role'] != 'NON-PARTICIPANT' && $attendee['status'] != 'DELEGATED' ) { $attendees[$i]['status'] = 'NEEDS-ACTION'; $attendees[$i]['rsvp'] = true; } } // update attendees only if I'm the organizer if ($is_organizer || (!empty($event['organizer']) && in_array(strtolower($event['organizer']['email']), $emails))) { $event['attendees'] = $attendees; } } return $reschedule; } /** * Identify changes considered relevant for scheduling * * @param array $object Hash array with NEW object properties * @param array $old Hash array with OLD object properties * * @return bool True if changes affect scheduling, False otherwise */ protected function is_rescheduling_needed($object, $old = null) { $reschedule = false; foreach ($this->scheduling_properties as $prop) { $a = $old[$prop] ?? null; $b = $object[$prop] ?? null; if (!empty($object['allday']) && ($prop == 'start' || $prop == 'end') && $a instanceof DateTimeInterface && $b instanceof DateTimeInterface ) { $a = $a->format('Y-m-d'); $b = $b->format('Y-m-d'); } if ($prop == 'recurrence' && is_array($a) && is_array($b)) { unset($a['EXCEPTIONS'], $b['EXCEPTIONS']); $a = array_filter($a); $b = array_filter($b); // advanced rrule comparison: no rescheduling if series was shortened if ($a['COUNT'] && $b['COUNT'] && $b['COUNT'] < $a['COUNT']) { unset($a['COUNT'], $b['COUNT']); } elseif ($a['UNTIL'] && $b['UNTIL'] && $b['UNTIL'] < $a['UNTIL']) { unset($a['UNTIL'], $b['UNTIL']); } } if ($a != $b) { $reschedule = true; break; } } return $reschedule; } /** * 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) { $special_calendars = [ self::BIRTHDAY_CALENDAR_ID, self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED, ]; // show default dialog for birthday calendar if (in_array($calendar['id'], $special_calendars)) { if ($calendar['id'] != self::BIRTHDAY_CALENDAR_ID) { unset($formfields['showalarms']); } // General tab $form['props'] = [ 'name' => $this->rc->gettext('properties'), 'fields' => $formfields, ]; return kolab_utils::folder_form($form, '', 'calendar'); } $form['props'] = [ 'name' => $this->rc->gettext('properties'), 'fields' => [ 'location' => $formfields['name'], 'color' => $formfields['color'], 'alarms' => $formfields['showalarms'], ], ]; return kolab_utils::folder_form($form, '', 'calendar', [], true); } } diff --git a/plugins/calendar/drivers/calendar_driver.php b/plugins/calendar/drivers/calendar_driver.php index f493fc41..0b7eea80 100644 --- a/plugins/calendar/drivers/calendar_driver.php +++ b/plugins/calendar/drivers/calendar_driver.php @@ -1,877 +1,877 @@ * @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 { public const FILTER_ALL = 0; public const FILTER_WRITEABLE = 1; public const FILTER_INSERTABLE = 2; public const FILTER_ACTIVE = 4; public const FILTER_PERSONAL = 8; public const FILTER_PRIVATE = 16; public const FILTER_CONFIDENTIAL = 32; public const FILTER_SHARED = 64; public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public function load_events($start, $end, $query = null, $calendars = null, $virtual = true, $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 public 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 public 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 public 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) { return []; } /** * Get attachment properties * * @param string $id Attachment identifier * @param array $event Hash array with event properties: * id: Event identifier * calendar: Calendar identifier * * @return array|false 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) { return false; } /** * Get attachment body * * @param string $id Attachment identifier * @param array $event Hash array with event properties: * id: Event identifier * calendar: Calendar identifier * * @return string|false Attachment body */ public function get_attachment_body($id, $event) { return false; } /** * 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 + * @param rcube_message_header|string $uri_or_headers An object 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|false 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|false 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'])) { $rcmail = rcmail::get_instance(); /** @var calendar $plugin */ $plugin = $rcmail->plugins->get_plugin('calendar'); $recurrence = new libcalendaring_recurrence($plugin->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'] . '-' . $next_event['_instance']; $next_event['recurrence_id'] = $event['uid']; $events[] = $next_event; } elseif ($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|false 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|false 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|false 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 bool 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) { $rcmail = rcmail::get_instance(); $table = new html_table(['cols' => 2, 'class' => 'propform']); foreach ($formfields as $col => $colprop) { $label = !empty($colprop['label']) ? $colprop['label'] : $rcmail->gettext("calendar.$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((string) $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 [, $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 null; } if (!empty($contact['birthday']) && is_array($contact['birthday'])) { $contact['birthday'] = reset($contact['birthday']); } if (empty($contact['birthday'])) { return null; } try { $bday = libcalendaring_datetime::createFromAny($contact['birthday'], true); } catch (Exception $e) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => 'Failed to parse contact birthday: ' . $e->getMessage(), ], true, false ); return null; } $rcmail = rcmail::get_instance(); $birthyear = $bday->format('Y'); $display_name = rcube_addressbook::compose_display_name($contact); $label = ['name' => 'birthdayeventtitle', 'vars' => ['name' => $display_name]]; $event_title = $rcmail->gettext($label, 'calendar'); $uid = rcube_ldap::dn_encode('bday:' . $source . ':' . $contact['ID'] . ':' . $birthyear); return [ 'id' => $uid, 'uid' => $uid, 'calendar' => self::BIRTHDAY_CALENDAR_ID, 'title' => $event_title, 'description' => '', 'allday' => true, 'start' => $bday, 'end' => clone $bday, 'recurrence' => ['FREQ' => 'YEARLY', 'INTERVAL' => 1], 'free_busy' => 'free', '_displayname' => $display_name, ]; } /** * Store alarm dismissal for birtual birthay events * * @param string $event_id Event identifier * @param int $snooze Suspend the alarm for this number of seconds */ public function dismiss_birthday_alarm($event_id, $snooze = 0) { $rcmail = rcmail::get_instance(); $cache = $rcmail->get_cache('calendar.birthdayalarms', 'db', 86400 * 30); $cache->remove($event_id); // compute new notification time or disable if not snoozed $notifyat = $snooze > 0 ? time() + $snooze : null; $cache->set($event_id, ['snooze' => $snooze, 'notifyat' => $notifyat]); return true; } /** * Handler for user_delete plugin hook * * @param array $args Hash array with hook arguments * * @return array Return arguments for plugin hooks */ public function user_delete($args) { // TO BE OVERRIDDEN return $args; } } diff --git a/plugins/calendar/drivers/kolab/kolab_driver.php b/plugins/calendar/drivers/kolab/kolab_driver.php index d7c45094..e3a72d4e 100644 --- a/plugins/calendar/drivers/kolab/kolab_driver.php +++ b/plugins/calendar/drivers/kolab/kolab_driver.php @@ -1,2653 +1,2653 @@ * @author Aleksander Machniak * * 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 kolab_driver extends calendar_driver { public const INVITATIONS_CALENDAR_PENDING = '--invitation--pending'; public const INVITATIONS_CALENDAR_DECLINED = '--invitation--declined'; // features this backend supports public $alarms = true; public $attendees = true; public $freebusy = true; public $attachments = true; public $undelete = true; public $alarm_types = ['DISPLAY', 'AUDIO']; public $categoriesimmutable = true; protected $rc; protected $cal; protected $calendars; protected $storage; protected $has_writeable = false; protected $freebusy_trigger = false; protected $bonnie_api = false; protected $search_more_results = false; /** * Default constructor */ public function __construct($cal) { $cal->require_plugin('libkolab'); // load helper classes *after* libkolab has been loaded (#3248) require_once(__DIR__ . '/kolab_calendar.php'); require_once(__DIR__ . '/kolab_user_calendar.php'); require_once(__DIR__ . '/kolab_invitation_calendar.php'); $this->cal = $cal; $this->rc = $cal->rc; $this->storage = new kolab_storage(); $this->cal->register_action('push-freebusy', [$this, 'push_freebusy']); $this->cal->register_action('calendar-acl', [$this, 'calendar_acl']); $this->freebusy_trigger = $this->rc->config->get('calendar_freebusy_trigger', false); if (!$this->rc->config->get('kolab_freebusy_server', false)) { $this->freebusy = false; } if (kolab_storage::$version == '2.0') { $this->alarm_types = ['DISPLAY']; $this->alarm_absolute = false; } // get configuration for the Bonnie API $this->bonnie_api = libkolab::get_bonnie_api(); // calendar uses fully encoded identifiers kolab_storage::$encode_ids = true; } /** * Read available calendars from server */ protected function _read_calendars() { // already read sources if (isset($this->calendars)) { return $this->calendars; } // get all folders that have "event" type, sorted by namespace/name $folders = $this->storage->sort_folders( $this->storage->get_folders('event') + kolab_storage::get_user_folders('event', true) ); $this->calendars = []; foreach ($folders as $folder) { $calendar = $this->_to_calendar($folder); if ($calendar->ready) { $this->calendars[$calendar->id] = $calendar; if ($calendar->editable) { $this->has_writeable = true; } } } return $this->calendars; } /** * Convert kolab_storage_folder into kolab_calendar * * @return kolab_calendar */ protected function _to_calendar($folder) { if ($folder instanceof kolab_calendar) { return $folder; } if ($folder instanceof kolab_storage_folder_user) { $calendar = new kolab_user_calendar($folder, $this->cal); $calendar->subscriptions = count($folder->children) > 0; } else { $calendar = new kolab_calendar($folder->name, $this->cal); } return $calendar; } /** * Get a list of available calendars from this source * - * @param int $filter Bitmask defining filter criterias - * @param object $tree Reference to hierarchical folder tree object + * @param int $filter Bitmask defining filter criterias + * @param ?kolab_storage_folder_virtual $tree Reference to hierarchical folder tree object * * @return array List of calendars */ public function list_calendars($filter = 0, &$tree = null) { $this->_read_calendars(); // attempt to create a default calendar for this user if (!$this->has_writeable) { if ($this->create_calendar(['name' => 'Calendar', 'color' => 'cc0000'])) { unset($this->calendars); $this->_read_calendars(); } } $delim = $this->rc->get_storage()->get_hierarchy_delimiter(); $folders = $this->filter_calendars($filter); $calendars = []; // include virtual folders for a full folder tree if (!is_null($tree)) { $folders = $this->storage->folder_hierarchy($folders, $tree); } $parents = array_keys($this->calendars); foreach ($folders as $id => $cal) { $imap_path = explode($delim, $cal->name); // find parent do { array_pop($imap_path); $parent_id = $this->storage->folder_id(implode($delim, $imap_path)); } while (count($imap_path) > 1 && !in_array($parent_id, $parents)); // restore "real" parent ID if ($parent_id && !in_array($parent_id, $parents)) { $parent_id = $this->storage->folder_id($cal->get_parent()); } $parents[] = $cal->id; if ($cal instanceof kolab_storage_folder_virtual) { $calendars[$cal->id] = [ 'id' => $cal->id, 'name' => $cal->get_name(), 'listname' => $cal->get_foldername(), 'editname' => $cal->get_foldername(), 'virtual' => true, 'editable' => false, 'group' => $cal->get_namespace(), ]; } else { // additional folders may come from kolab_storage::folder_hierarchy() above // make sure we deal with kolab_calendar instances $cal = $this->_to_calendar($cal); $this->calendars[$cal->id] = $cal; $is_user = ($cal instanceof kolab_user_calendar); $calendars[$cal->id] = [ 'id' => $cal->id, 'name' => $cal->get_name(), 'listname' => $cal->get_foldername(), 'editname' => $cal->get_foldername(), 'title' => $cal->get_title(), 'color' => $cal->get_color(), 'editable' => $cal->editable, 'group' => $is_user ? 'other user' : $cal->get_namespace(), 'active' => $cal->is_active(), 'owner' => $cal->get_owner(), 'removable' => !$cal->default, ]; if (!$is_user) { $calendars[$cal->id] += [ 'default' => $cal->default, 'rights' => $cal->rights, 'showalarms' => $cal->alarms, 'history' => !empty($this->bonnie_api), 'children' => true, // TODO: determine if that folder indeed has child folders 'parent' => $parent_id, 'subtype' => $cal->subtype, 'caldavurl' => $cal->get_caldav_url(), ]; } } if (!empty($cal->subscriptions)) { $calendars[$cal->id]['subscribed'] = $cal->is_subscribed(); } } // list virtual calendars showing invitations if ($this->rc->config->get('kolab_invitation_calendars') && !($filter & self::FILTER_INSERTABLE)) { foreach ([self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED] as $id) { $cal = new kolab_invitation_calendar($id, $this->cal); if (!($filter & self::FILTER_ACTIVE) || $cal->is_active()) { $calendars[$id] = [ 'id' => $cal->id, 'name' => $cal->get_name(), 'listname' => $cal->get_name(), 'editname' => $cal->get_foldername(), 'title' => $cal->get_title(), 'color' => $cal->get_color(), 'editable' => $cal->editable, 'rights' => $cal->rights, 'showalarms' => $cal->alarms, 'history' => !empty($this->bonnie_api), 'group' => 'x-invitations', 'default' => false, 'active' => $cal->is_active(), 'owner' => $cal->get_owner(), 'children' => false, 'counts' => $id == self::INVITATIONS_CALENDAR_PENDING, ]; if (is_object($tree)) { $tree->children[] = $cal; } } } } // append the virtual birthdays calendar if ($this->rc->config->get('calendar_contact_birthdays', false) && !($filter & self::FILTER_INSERTABLE)) { $id = self::BIRTHDAY_CALENDAR_ID; $prefs = $this->rc->config->get('kolab_calendars', []); // read local prefs if (!($filter & self::FILTER_ACTIVE) || !empty($prefs[$id]['active'])) { $calendars[$id] = [ 'id' => $id, 'name' => $this->cal->gettext('birthdays'), 'listname' => $this->cal->gettext('birthdays'), 'color' => !empty($prefs[$id]['color']) ? $prefs[$id]['color'] : '87CEFA', 'active' => !empty($prefs[$id]['active']), 'showalarms' => (bool) $this->rc->config->get('calendar_birthdays_alarm_type'), 'group' => 'x-birthdays', 'editable' => false, 'default' => false, 'children' => false, 'history' => false, ]; } } return $calendars; } /** * Get list of calendars according to specified filters * * @param int $filter Bitmask defining restrictions. See FILTER_* constants for possible values. * * @return array List of calendars */ protected function filter_calendars($filter) { $this->_read_calendars(); $calendars = []; $plugin = $this->rc->plugins->exec_hook('calendar_list_filter', [ 'list' => $this->calendars, 'calendars' => $calendars, 'filter' => $filter, ]); if ($plugin['abort']) { return $plugin['calendars']; } $personal = $filter & self::FILTER_PERSONAL; $shared = $filter & self::FILTER_SHARED; foreach ($this->calendars as $cal) { if (!$cal->ready) { continue; } if (($filter & self::FILTER_WRITEABLE) && !$cal->editable) { continue; } if (($filter & self::FILTER_INSERTABLE) && !$cal->editable) { continue; } if (($filter & self::FILTER_ACTIVE) && !$cal->is_active()) { continue; } if (($filter & self::FILTER_PRIVATE) && $cal->subtype != 'private') { continue; } if (($filter & self::FILTER_CONFIDENTIAL) && $cal->subtype != 'confidential') { continue; } if ($personal || $shared) { $ns = $cal->get_namespace(); if (!(($personal && $ns == 'personal') || ($shared && $ns == 'shared'))) { continue; } } $calendars[$cal->id] = $cal; } return $calendars; } /** * Get the kolab_calendar instance for the given calendar ID * * @param string $id Calendar identifier (encoded imap folder name) * * @return kolab_calendar|kolab_invitation_calendar|null Object nor null if calendar doesn't exist */ public function get_calendar($id) { $this->_read_calendars(); // create calendar object if necesary if (empty($this->calendars[$id])) { if (in_array($id, [self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED])) { return new kolab_invitation_calendar($id, $this->cal); } // for unsubscribed calendar folders if ($id !== self::BIRTHDAY_CALENDAR_ID) { $calendar = kolab_calendar::factory($id, $this->cal); if ($calendar->ready) { $this->calendars[$calendar->id] = $calendar; } } } return !empty($this->calendars[$id]) ? $this->calendars[$id] : null; } /** * Create a new calendar assigned to the current user * * @param array $prop Hash array with calendar properties * name: Calendar name * color: The color of the calendar * * @return mixed ID of the calendar on success, False on error */ public function create_calendar($prop) { $prop['type'] = 'event'; $prop['active'] = true; $prop['subscribed'] = true; $folder = $this->storage->folder_update($prop); if ($folder === false) { $this->last_error = $this->cal->gettext($this->storage->last_error); return false; } // create ID $id = $this->storage->folder_id($folder); // save color in user prefs (temp. solution) $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []); if (isset($prop['color'])) { $prefs['kolab_calendars'][$id]['color'] = $prop['color']; } if (isset($prop['showalarms'])) { $prefs['kolab_calendars'][$id]['showalarms'] = !empty($prop['showalarms']); } if (!empty($prefs['kolab_calendars'][$id])) { $this->rc->user->save_prefs($prefs); } return $id; } /** * Update properties of an existing calendar * * @see calendar_driver::edit_calendar() */ public function edit_calendar($prop) { if (!empty($prop['id']) && ($cal = $this->get_calendar($prop['id']))) { $id = $cal->update($prop); } else { $id = $prop['id']; } // fallback to local prefs $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []); unset($prefs['kolab_calendars'][$prop['id']]['color'], $prefs['kolab_calendars'][$prop['id']]['showalarms']); if (isset($prop['color'])) { $prefs['kolab_calendars'][$id]['color'] = $prop['color']; } if (isset($prop['showalarms']) && $id == self::BIRTHDAY_CALENDAR_ID) { $prefs['calendar_birthdays_alarm_type'] = $prop['showalarms'] ? $this->alarm_types[0] : ''; } elseif (isset($prop['showalarms'])) { $prefs['kolab_calendars'][$id]['showalarms'] = !empty($prop['showalarms']); } if (!empty($prefs['kolab_calendars'][$id])) { $this->rc->user->save_prefs($prefs); } return true; } /** * Set active/subscribed state of a calendar * * @see calendar_driver::subscribe_calendar() */ public function subscribe_calendar($prop) { if (!empty($prop['id']) && ($cal = $this->get_calendar($prop['id'])) && !empty($cal->storage)) { $ret = false; if (isset($prop['permanent'])) { $ret |= $cal->storage->subscribe(intval($prop['permanent'])); } if (isset($prop['active'])) { $ret |= $cal->storage->activate(intval($prop['active'])); } // apply to child folders, too if (!empty($prop['recursive'])) { foreach ((array) $this->storage->list_folders($cal->storage->name, '*', 'event') as $subfolder) { if (isset($prop['permanent'])) { if ($prop['permanent']) { $this->storage->folder_subscribe($subfolder); } else { $this->storage->folder_unsubscribe($subfolder); } } if (isset($prop['active'])) { if ($prop['active']) { $this->storage->folder_activate($subfolder); } else { $this->storage->folder_deactivate($subfolder); } } } } + return $ret; - } else { - // save state in local prefs - $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []); - $prefs['kolab_calendars'][$prop['id']]['active'] = !empty($prop['active']); - $this->rc->user->save_prefs($prefs); - return true; } - return false; + // save state in local prefs + $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []); + $prefs['kolab_calendars'][$prop['id']]['active'] = !empty($prop['active']); + $this->rc->user->save_prefs($prefs); + return true; } /** * Delete the given calendar with all its contents * * @see calendar_driver::delete_calendar() */ public function delete_calendar($prop) { if (!empty($prop['id']) && ($cal = $this->get_calendar($prop['id']))) { $folder = $cal->get_realname(); // TODO: unsubscribe if no admin rights if ($this->storage->folder_delete($folder)) { // remove color in user prefs (temp. solution) $prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []); unset($prefs['kolab_calendars'][$prop['id']]); $this->rc->user->save_prefs($prefs); return true; } else { $this->last_error = $this->storage->last_error; } } return false; } /** * Search for shared or otherwise not listed calendars the user has access * * @param string $query Search string * @param string $source Section/source to search * * @return array List of calendars */ public function search_calendars($query, $source) { if (!$this->storage->setup()) { return []; } $this->calendars = []; $this->search_more_results = false; // find unsubscribed IMAP folders that have "event" type if ($source == 'folders') { foreach ((array) $this->storage->search_folders('event', $query, ['other']) as $folder) { $calendar = new kolab_calendar($folder->name, $this->cal); $this->calendars[$calendar->id] = $calendar; } } // find other user's virtual calendars elseif ($source == 'users') { // we have slightly more space, so display twice the number $limit = $this->rc->config->get('autocomplete_max', 15) * 2; $count = 0; foreach ($this->storage->search_users($query, 0, [], $limit, $count) as $user) { $calendar = new kolab_user_calendar($user, $this->cal); $this->calendars[$calendar->id] = $calendar; // search for calendar folders shared by this user foreach ($this->storage->list_user_folders($user, 'event', false) as $foldername) { $cal = new kolab_calendar($foldername, $this->cal); $this->calendars[$cal->id] = $cal; $calendar->subscriptions = true; } } if ($count > $limit) { $this->search_more_results = true; } } // don't list the birthday calendar $this->rc->config->set('calendar_contact_birthdays', false); $this->rc->config->set('kolab_invitation_calendars', false); return $this->list_calendars(); } /** * Fetch a single event * * @see calendar_driver::get_event() * @return ?array Hash array with event properties, false if not found */ public function get_event($event, $scope = 0, $full = false) { if (is_array($event)) { $id = !empty($event['id']) ? $event['id'] : $event['uid']; $cal = $event['calendar'] ?? null; // we're looking for a recurring instance: expand the ID to our internal convention for recurring instances if (empty($event['id']) && !empty($event['_instance'])) { $id .= '-' . $event['_instance']; } } else { $id = $event; } if (!empty($cal)) { if ($storage = $this->get_calendar($cal)) { $result = $storage->get_event($id); return self::to_rcube_event($result); } // get event from the address books birthday calendar if ($cal == self::BIRTHDAY_CALENDAR_ID) { return $this->get_birthday_event($id); } } // iterate over all calendar folders and search for the event ID else { foreach ($this->filter_calendars($scope) as $calendar) { if ($result = $calendar->get_event($id)) { return self::to_rcube_event($result); } } } return null; } /** * Add a single event to the database * * @see calendar_driver::new_event() */ public function new_event($event) { if (!$this->validate($event)) { return false; } $event = self::from_rcube_event($event); if (!$event['calendar']) { $this->_read_calendars(); $cal_ids = array_keys($this->calendars); $event['calendar'] = reset($cal_ids); } if ($storage = $this->get_calendar($event['calendar'])) { // if this is a recurrence instance, append as exception to an already existing object for this UID if (!empty($event['recurrence_date']) && ($master = $storage->get_event($event['uid']))) { self::add_exception($master, $event); $success = $storage->update_event($master); } else { $success = $storage->insert_event($event); } if ($success && $this->freebusy_trigger) { $this->rc->output->command('plugin.ping_url', ['action' => 'calendar/push-freebusy', 'source' => $storage->id]); $this->freebusy_trigger = false; // disable after first execution (#2355) } return $success; } return false; } /** * Update an event entry with the given data * * @see calendar_driver::new_event() * @return bool True on success, False on error */ public function edit_event($event) { if (!($storage = $this->get_calendar($event['calendar']))) { return false; } return $this->update_event(self::from_rcube_event($event, $storage->get_event($event['id']))); } /** * Extended event editing with possible changes to the argument * * @param array $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) { $update_event = $event; // apply changes to master (and all exceptions) if ($event['_savemode'] == 'all' && !empty($event['recurrence_id'])) { if ($storage = $this->get_calendar($event['calendar'])) { $update_event = $storage->get_event($event['recurrence_id']); $update_event['_savemode'] = $event['_savemode']; $update_event['id'] = $update_event['uid']; unset($update_event['recurrence_id']); calendar::merge_attendee_data($update_event, $attendees); } } if ($ret = $this->update_attendees($update_event, $attendees)) { // replace with master event (for iTip reply) $event = self::to_rcube_event($update_event); // re-assign to the according (virtual) calendar if ($this->rc->config->get('kolab_invitation_calendars')) { if (strtoupper($status) == 'DECLINED') { $event['calendar'] = self::INVITATIONS_CALENDAR_DECLINED; } elseif (strtoupper($status) == 'NEEDS-ACTION') { $event['calendar'] = self::INVITATIONS_CALENDAR_PENDING; } elseif (!empty($event['_folder_id'])) { $event['calendar'] = $event['_folder_id']; } } } return $ret; } /** * Update the participant status for the given attendees * * @see calendar_driver::update_attendees() */ public function update_attendees(&$event, $attendees) { // for this-and-future updates, merge the updated attendees onto all exceptions in range if ( ($event['_savemode'] == 'future' && !empty($event['recurrence_id'])) || (!empty($event['recurrence']) && empty($event['recurrence_id'])) ) { if (!($storage = $this->get_calendar($event['calendar']))) { return false; } // load master event $master = !empty($event['recurrence_id']) ? $storage->get_event($event['recurrence_id']) : $event; // apply attendee update to each existing exception if (!empty($master['recurrence']) && !empty($master['recurrence']['EXCEPTIONS'])) { $saved = false; foreach ($master['recurrence']['EXCEPTIONS'] as $i => $exception) { // merge the new event properties onto future exceptions if ($exception['_instance'] >= strval($event['_instance'])) { calendar::merge_attendee_data($master['recurrence']['EXCEPTIONS'][$i], $attendees); } // update a specific instance if ($exception['_instance'] == $event['_instance'] && $exception['thisandfuture']) { $saved = true; } } // add the given event as new exception if (!$saved && $event['id'] != $master['id']) { $event['thisandfuture'] = true; $master['recurrence']['EXCEPTIONS'][] = $event; } // set link to top-level exceptions $master['exceptions'] = &$master['recurrence']['EXCEPTIONS']; return $this->update_event($master); } } // just update the given event (instance) return $this->update_event($event); } /** * Move a single event * * @see calendar_driver::move_event() * @return bool True on success, False on error */ public function move_event($event) { if (($storage = $this->get_calendar($event['calendar'])) && ($ev = $storage->get_event($event['id']))) { unset($ev['sequence']); self::clear_attandee_noreply($ev); return $this->update_event($event + $ev); } return false; } /** * Resize a single event * * @see calendar_driver::resize_event() * @return bool True on success, False on error */ public function resize_event($event) { if (($storage = $this->get_calendar($event['calendar'])) && ($ev = $storage->get_event($event['id']))) { unset($ev['sequence']); self::clear_attandee_noreply($ev); return $this->update_event($event + $ev); } return false; } /** * Remove a single event * * @param array $event Hash array with event properties: * - id: Event identifier * @param bool $force Remove record(s) irreversible (mark as deleted otherwise) * * @return bool True on success, False on error */ public function remove_event($event, $force = true) { $ret = true; $success = false; $savemode = $event['_savemode'] ?? null; if (!$force) { unset($event['attendees']); $this->rc->session->remove('calendar_event_undo'); $this->rc->session->remove('calendar_restore_event_data'); $sess_data = $event; } if (($storage = $this->get_calendar($event['calendar'])) && ($event = $storage->get_event($event['id']))) { $event['_savemode'] = $savemode; $decline = !empty($event['_decline']); $savemode = 'all'; $master = $event; // read master if deleting a recurring event if (!empty($event['recurrence']) || !empty($event['recurrence_id']) || !empty($event['isexception'])) { $master = $storage->get_event($event['uid']); if (!empty($event['_savemode'])) { $savemode = $event['_savemode']; } elseif (!empty($event['_instance']) || !empty($event['isexception'])) { $savemode = 'current'; } // force 'current' mode for single occurrences stored as exception if (empty($event['recurrence']) && empty($event['recurrence_id']) && !empty($event['isexception'])) { $savemode = 'current'; } } // removing an exception instance if ((!empty($event['recurrence_id']) || !empty($event['isexception'])) && !empty($master['exceptions'])) { foreach ($master['exceptions'] as $i => $exception) { if (libcalendaring::is_recurrence_exception($event, $exception)) { unset($master['exceptions'][$i]); // set event date back to the actual occurrence if (!empty($exception['recurrence_date'])) { $event['start'] = $exception['recurrence_date']; } } } if (!empty($master['recurrence'])) { $master['recurrence']['EXCEPTIONS'] = &$master['exceptions']; } } switch ($savemode) { case 'current': $_SESSION['calendar_restore_event_data'] = serialize(array_diff_key($master, ['_formatobj' => 1])); // remove the matching RDATE entry if (!empty($master['recurrence']['RDATE'])) { foreach ($master['recurrence']['RDATE'] as $j => $rdate) { if ($rdate->format('Ymd') == $event['start']->format('Ymd')) { unset($master['recurrence']['RDATE'][$j]); break; } } } // add exception to master event $master['recurrence']['EXDATE'][] = $event['start']; $success = $storage->update_event($master); break; case 'future': $master['_instance'] = libcalendaring::recurrence_instance_identifier($master); if ($master['_instance'] != $event['_instance']) { $_SESSION['calendar_restore_event_data'] = serialize(array_diff_key($master, ['_formatobj' => 1])); // set until-date on master event $master['recurrence']['UNTIL'] = clone $event['start']; $master['recurrence']['UNTIL']->sub(new DateInterval('P1D')); unset($master['recurrence']['COUNT']); // if all future instances are deleted, remove recurrence rule entirely (bug #1677) if ($master['recurrence']['UNTIL']->format('Ymd') == $master['start']->format('Ymd')) { $master['recurrence'] = []; } // remove matching RDATE entries elseif (!empty($master['recurrence']['RDATE'])) { foreach ($master['recurrence']['RDATE'] as $j => $rdate) { if ($rdate->format('Ymd') == $event['start']->format('Ymd')) { $master['recurrence']['RDATE'] = array_slice($master['recurrence']['RDATE'], 0, $j); break; } } } $success = $storage->update_event($master); $ret = $master['uid']; break; } // no break default: // 'all' is default // removing the master event with loose exceptions (not recurring though) if (!empty($event['recurrence_date']) && empty($master['recurrence']) && !empty($master['exceptions'])) { // make the first exception the new master $newmaster = array_shift($master['exceptions']); $newmaster['exceptions'] = $master['exceptions']; $newmaster['_attachments'] = $master['_attachments']; $newmaster['_mailbox'] = $master['_mailbox']; $newmaster['_msguid'] = $master['_msguid']; $success = $storage->update_event($newmaster); } elseif ($decline && $this->rc->config->get('kolab_invitation_calendars')) { // don't delete but set PARTSTAT=DECLINED if ($this->cal->lib->set_partstat($master, 'DECLINED')) { $success = $storage->update_event($master); } } if (!$success) { $success = $storage->delete_event($master, $force); } break; } } if ($success && !$force) { if (!empty($master['_folder_id'])) { $sess_data['_folder_id'] = $master['_folder_id']; } $_SESSION['calendar_event_undo'] = ['ts' => time(), 'data' => $sess_data]; } if ($success && $this->freebusy_trigger) { $this->rc->output->command('plugin.ping_url', [ 'action' => 'calendar/push-freebusy', // _folder_id may be set by invitations calendar 'source' => !empty($master['_folder_id']) ? $master['_folder_id'] : $storage->id, ]); } return $success ? $ret : false; } /** * Restore a single deleted event * * @param array $event Hash array with event properties: * - id: Event identifier * - calendar: Event calendar * * @return bool True on success, False on error */ public function restore_event($event) { if ($storage = $this->get_calendar($event['calendar'])) { if (!empty($_SESSION['calendar_restore_event_data'])) { $success = $storage->update_event($event = unserialize($_SESSION['calendar_restore_event_data'])); } else { $success = $storage->restore_event($event); } if ($success && $this->freebusy_trigger) { $this->rc->output->command('plugin.ping_url', [ 'action' => 'calendar/push-freebusy', // _folder_id may be set by invitations calendar 'source' => !empty($event['_folder_id']) ? $event['_folder_id'] : $storage->id, ]); } return $success; } return false; } /** * Wrapper to update an event object depending on the given savemode */ protected function update_event($event) { if (!($storage = $this->get_calendar($event['calendar']))) { return false; } // move event to another folder/calendar if (!empty($event['_fromcalendar']) && $event['_fromcalendar'] != $event['calendar']) { if (!($fromcalendar = $this->get_calendar($event['_fromcalendar']))) { return false; } $old = $fromcalendar->get_event($event['id']); if (empty($event['_savemode']) || $event['_savemode'] != 'new') { if (!$fromcalendar->storage->move($old['uid'], $storage->storage)) { return false; } } } $success = false; $savemode = 'all'; $old = $master = $storage->get_event($event['id']); if (!$old || empty($old['start'])) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Failed to load event object to update: id=" . $event['id'], ], true, false ); return false; } // modify a recurring event, check submitted savemode to do the right things if (!empty($old['recurrence']) || !empty($old['recurrence_id']) || !empty($old['isexception'])) { $master = $storage->get_event($old['uid']); if (!empty($event['_savemode'])) { $savemode = $event['_savemode']; } else { $savemode = (!empty($old['recurrence_id']) || !empty($old['isexception'])) ? 'current' : 'all'; } // this-and-future on the first instance equals to 'all' if ($savemode == 'future' && !empty($master['start']) && $old['_instance'] == libcalendaring::recurrence_instance_identifier($master) ) { $savemode = 'all'; } // force 'current' mode for single occurrences stored as exception elseif (empty($old['recurrence']) && empty($old['recurrence_id']) && !empty($old['isexception'])) { $savemode = 'current'; } // Stick to the master timezone for all occurrences (Bifrost#T104637) if (empty($master['allday']) || !empty($event['allday'])) { $master_tz = $master['start']->getTimezone(); $event_tz = $event['start']->getTimezone(); if ($master_tz->getName() != $event_tz->getName()) { $event['start']->setTimezone($master_tz); $event['end']->setTimezone($master_tz); } } } // check if update affects scheduling and update attendee status accordingly $reschedule = $this->check_scheduling($event, $old, true); // keep saved exceptions (not submitted by the client) if (!empty($old['recurrence']['EXDATE']) && !isset($event['recurrence']['EXDATE'])) { $event['recurrence']['EXDATE'] = $old['recurrence']['EXDATE']; } if (isset($event['recurrence']['EXCEPTIONS'])) { // exceptions already provided (e.g. from iCal import) $with_exceptions = true; } elseif (!empty($old['recurrence']['EXCEPTIONS'])) { $event['recurrence']['EXCEPTIONS'] = $old['recurrence']['EXCEPTIONS']; } elseif (!empty($old['exceptions'])) { $event['exceptions'] = $old['exceptions']; } // remove some internal properties which should not be saved unset($event['_savemode'], $event['_fromcalendar'], $event['_identity'], $event['_owner'], $event['_notify'], $event['_method'], $event['_sender'], $event['_sender_utf'], $event['_size'] ); switch ($savemode) { case 'new': // save submitted data as new (non-recurring) event $event['recurrence'] = []; $event['_copyfrom'] = $master['_msguid']; $event['_mailbox'] = $master['_mailbox']; $event['uid'] = $this->cal->generate_uid(); unset($event['recurrence_id'], $event['recurrence_date'], $event['_instance'], $event['id']); // copy attachment metadata to new event $event = self::from_rcube_event($event, $master); self::clear_attandee_noreply($event); if ($success = $storage->insert_event($event)) { $success = $event['uid']; } break; case 'future': // create a new recurring event $event['_copyfrom'] = $master['_msguid']; $event['_mailbox'] = $master['_mailbox']; $event['uid'] = $this->cal->generate_uid(); unset($event['recurrence_id'], $event['recurrence_date'], $event['_instance'], $event['id']); // copy attachment metadata to new event $event = self::from_rcube_event($event, $master); // remove recurrence exceptions on re-scheduling if ($reschedule) { unset($event['recurrence']['EXCEPTIONS'], $event['exceptions'], $master['recurrence']['EXDATE']); } else { if (isset($event['recurrence']['EXCEPTIONS']) && is_array($event['recurrence']['EXCEPTIONS'])) { // only keep relevant exceptions $event['recurrence']['EXCEPTIONS'] = array_filter( $event['recurrence']['EXCEPTIONS'], function ($exception) use ($event) { return $exception['start'] > $event['start']; } ); // set link to top-level exceptions $event['exceptions'] = &$event['recurrence']['EXCEPTIONS']; } if (isset($event['recurrence']['EXDATE']) && is_array($event['recurrence']['EXDATE'])) { $event['recurrence']['EXDATE'] = array_filter( $event['recurrence']['EXDATE'], function ($exdate) use ($event) { return $exdate > $event['start']; } ); } } // compute remaining occurrences if ($event['recurrence']['COUNT']) { if (empty($old['_count'])) { $old['_count'] = $this->get_recurrence_count($master, $old['start']); } $event['recurrence']['COUNT'] -= intval($old['_count']); } // remove fixed weekday when date changed if ($old['start']->format('Y-m-d') != $event['start']->format('Y-m-d')) { if (!empty($event['recurrence']['BYDAY']) && strlen($event['recurrence']['BYDAY']) == 2) { unset($event['recurrence']['BYDAY']); } if (!empty($old['recurrence']['BYMONTH']) && $old['recurrence']['BYMONTH'] == $old['start']->format('n')) { unset($event['recurrence']['BYMONTH']); } } // set until-date on master event $master['recurrence']['UNTIL'] = clone $old['start']; $master['recurrence']['UNTIL']->sub(new DateInterval('P1D')); unset($master['recurrence']['COUNT']); // remove all exceptions after $event['start'] if (isset($master['recurrence']['EXCEPTIONS']) && is_array($master['recurrence']['EXCEPTIONS'])) { $master['recurrence']['EXCEPTIONS'] = array_filter( $master['recurrence']['EXCEPTIONS'], function ($exception) use ($event) { return $exception['start'] < $event['start']; } ); // set link to top-level exceptions $master['exceptions'] = &$master['recurrence']['EXCEPTIONS']; } if (isset($master['recurrence']['EXDATE']) && is_array($master['recurrence']['EXDATE'])) { $master['recurrence']['EXDATE'] = array_filter( $master['recurrence']['EXDATE'], function ($exdate) use ($event) { return $exdate < $event['start']; } ); } // save new event if ($success = $storage->insert_event($event)) { $success = $event['uid']; // update master event (no rescheduling!) self::clear_attandee_noreply($master); $storage->update_event($master); } break; case 'current': // recurring instances shall not store recurrence rules and attachments $event['recurrence'] = []; $event['thisandfuture'] = $savemode == 'future'; unset($event['attachments'], $event['id']); // increment sequence of this instance if scheduling is affected if ($reschedule) { $event['sequence'] = max($old['sequence'] ?? 0, $master['sequence'] ?? 0) + 1; } elseif (!isset($event['sequence'])) { $event['sequence'] = !empty($old['sequence']) ? $old['sequence'] : $master['sequence'] ?? 1; } // save properties to a recurrence exception instance if (!empty($old['_instance']) && isset($master['recurrence']['EXCEPTIONS'])) { if ($this->update_recurrence_exceptions($master, $event, $old, $savemode)) { $success = $storage->update_event($master, $old['id'] ?? null); break; } } $add_exception = true; // adjust matching RDATE entry if dates changed if ( !empty($master['recurrence']['RDATE']) && ($old_date = $old['start']->format('Ymd')) != $event['start']->format('Ymd') ) { foreach ($master['recurrence']['RDATE'] as $j => $rdate) { if ($rdate->format('Ymd') == $old_date) { $master['recurrence']['RDATE'][$j] = $event['start']; sort($master['recurrence']['RDATE']); $add_exception = false; break; } } } // save as new exception to master event if ($add_exception) { self::add_exception($master, $event, $old); } $success = $storage->update_event($master); break; default: // 'all' is the default $event['id'] = $master['uid']; $event['uid'] = $master['uid']; // use start date from master but try to be smart on time or duration changes $old_start_date = $old['start']->format('Y-m-d'); $old_start_time = !empty($old['allday']) ? '' : $old['start']->format('H:i'); $old_duration = self::event_duration($old['start'], $old['end'], !empty($old['allday'])); $new_start_date = $event['start']->format('Y-m-d'); $new_start_time = !empty($event['allday']) ? '' : $event['start']->format('H:i'); $new_duration = self::event_duration($event['start'], $event['end'], !empty($event['allday'])); $diff = $old_start_date != $new_start_date || $old_start_time != $new_start_time || $old_duration != $new_duration; $date_shift = $old['start']->diff($event['start']); // shifted or resized if ($diff && ($old_start_date == $new_start_date || $old_duration == $new_duration)) { $event['start'] = $master['start']->add($date_shift); $event['end'] = clone $event['start']; $event['end']->add(new DateInterval($new_duration)); // remove fixed weekday, will be re-set to the new weekday in kolab_calendar::update_event() if ($old_start_date != $new_start_date && !empty($event['recurrence'])) { if (!empty($event['recurrence']['BYDAY']) && strlen($event['recurrence']['BYDAY']) == 2) { unset($event['recurrence']['BYDAY']); } if (!empty($old['recurrence']['BYMONTH']) && $old['recurrence']['BYMONTH'] == $old['start']->format('n')) { unset($event['recurrence']['BYMONTH']); } } } // dates did not change, use the ones from master elseif ($new_start_date . $new_start_time == $old_start_date . $old_start_time) { $event['start'] = $master['start']; $event['end'] = $master['end']; } // when saving an instance in 'all' mode, copy recurrence exceptions over if (!empty($old['recurrence_id'])) { $event['recurrence']['EXCEPTIONS'] = $master['recurrence']['EXCEPTIONS'] ?? []; $event['recurrence']['EXDATE'] = $master['recurrence']['EXDATE'] ?? []; } elseif (!empty($master['_instance'])) { $event['_instance'] = $master['_instance']; $event['recurrence_date'] = $master['recurrence_date']; } // TODO: forward changes to exceptions (which do not yet have differing values stored) if (!empty($event['recurrence']) && !empty($event['recurrence']['EXCEPTIONS']) && empty($with_exceptions)) { // determine added and removed attendees $old_attendees = $current_attendees = $added_attendees = []; if (!empty($old['attendees'])) { foreach ((array) $old['attendees'] as $attendee) { $old_attendees[] = $attendee['email']; } } if (!empty($event['attendees'])) { foreach ((array) $event['attendees'] as $attendee) { $current_attendees[] = $attendee['email']; if (!in_array($attendee['email'], $old_attendees)) { $added_attendees[] = $attendee; } } } $removed_attendees = array_diff($old_attendees, $current_attendees); foreach ($event['recurrence']['EXCEPTIONS'] as $i => $exception) { calendar::merge_attendee_data($event['recurrence']['EXCEPTIONS'][$i], $added_attendees, $removed_attendees); } // adjust recurrence-id when start changed and therefore the entire recurrence chain changes if ($old_start_date != $new_start_date || $old_start_time != $new_start_time) { $recurrence_id_format = libcalendaring::recurrence_id_format($event); foreach ($event['recurrence']['EXCEPTIONS'] as $i => $exception) { if (isset($exception['recurrence_date']) && $exception['recurrence_date'] instanceof DateTimeInterface) { $recurrence_id = $exception['recurrence_date']; } else { $recurrence_id = rcube_utils::anytodatetime($exception['_instance'], $old['start']->getTimezone()); } if ($recurrence_id instanceof DateTime || $recurrence_id instanceof DateTimeImmutable) { $recurrence_id->add($date_shift); $event['recurrence']['EXCEPTIONS'][$i]['recurrence_date'] = $recurrence_id; $event['recurrence']['EXCEPTIONS'][$i]['_instance'] = $recurrence_id->format($recurrence_id_format); } } } // set link to top-level exceptions $event['exceptions'] = &$event['recurrence']['EXCEPTIONS']; } // unset _dateonly flags in (cached) date objects unset($event['start']->_dateonly, $event['end']->_dateonly); $success = $storage->update_event($event) ? $event['id'] : false; // return master UID break; } if ($success && $this->freebusy_trigger) { $this->rc->output->command('plugin.ping_url', [ 'action' => 'calendar/push-freebusy', 'source' => $storage->id, ]); } return $success; } /** * Calculate event duration, returns string in DateInterval format */ protected static function event_duration($start, $end, $allday = false) { if ($allday) { $diff = $start->diff($end); return 'P' . $diff->days . 'D'; } return 'PT' . ($end->format('U') - $start->format('U')) . 'S'; } /** * Determine whether the current change affects scheduling and reset attendee status accordingly */ protected function check_scheduling(&$event, $old, $update = true) { // skip this check when importing iCal/iTip events if (isset($event['sequence']) || !empty($event['_method'])) { return false; } // iterate through the list of properties considered 'significant' for scheduling $kolab_event = !empty($old['_formatobj']) ? $old['_formatobj'] : new kolab_format_event(); $reschedule = $kolab_event->check_rescheduling($event, $old); // reset all attendee status to needs-action (#4360) if ($update && $reschedule && !empty($event['attendees'])) { $is_organizer = false; $emails = $this->cal->get_user_emails(); $attendees = $event['attendees']; foreach ($attendees as $i => $attendee) { if ($attendee['role'] == 'ORGANIZER' && !empty($attendee['email']) && in_array(strtolower($attendee['email']), $emails) ) { $is_organizer = true; } elseif ($attendee['role'] != 'ORGANIZER' && $attendee['role'] != 'NON-PARTICIPANT' && $attendee['status'] != 'DELEGATED' ) { $attendees[$i]['status'] = 'NEEDS-ACTION'; $attendees[$i]['rsvp'] = true; } } // update attendees only if I'm the organizer if ($is_organizer || (!empty($event['organizer']) && in_array(strtolower($event['organizer']['email']), $emails))) { $event['attendees'] = $attendees; } } return $reschedule; } /** * Apply the given changes to already existing exceptions */ protected function update_recurrence_exceptions(&$master, $event, $old, $savemode) { $saved = false; $existing = null; // determine added and removed attendees $added_attendees = $removed_attendees = []; if ($savemode == 'future') { $old_attendees = $current_attendees = []; if (!empty($old['attendees'])) { foreach ((array) $old['attendees'] as $attendee) { $old_attendees[] = $attendee['email']; } } if (!empty($event['attendees'])) { foreach ((array) $event['attendees'] as $attendee) { $current_attendees[] = $attendee['email']; if (!in_array($attendee['email'], $old_attendees)) { $added_attendees[] = $attendee; } } } $removed_attendees = array_diff($old_attendees, $current_attendees); } foreach ($master['recurrence']['EXCEPTIONS'] as $i => $exception) { // update a specific instance if (libcalendaring::is_recurrence_exception($old, $exception)) { $existing = $i; // check savemode against existing exception mode. // if matches, we can update this existing exception $thisandfuture = !empty($exception['thisandfuture']); if ($thisandfuture === ($savemode == 'future')) { $event['_instance'] = $old['_instance']; $event['thisandfuture'] = !empty($old['thisandfuture']); $event['recurrence_date'] = $old['recurrence_date']; $master['recurrence']['EXCEPTIONS'][$i] = $event; $saved = true; } } // merge the new event properties onto future exceptions if ($savemode == 'future') { $exception_instance = libcalendaring::recurrence_instance_identifier($exception, true); $old_instance = libcalendaring::recurrence_instance_identifier($old, true); if ($exception_instance >= $old_instance) { unset($event['thisandfuture']); self::merge_exception_data($master['recurrence']['EXCEPTIONS'][$i], $event, ['attendees']); if (!empty($added_attendees) || !empty($removed_attendees)) { calendar::merge_attendee_data($master['recurrence']['EXCEPTIONS'][$i], $added_attendees, $removed_attendees); } } } } /* // we could not update the existing exception due to savemode mismatch... if (!$saved && isset($existing) && !empty($master['recurrence']['EXCEPTIONS'][$existing]['thisandfuture'])) { // ... try to move the existing this-and-future exception to the next occurrence foreach ($this->get_recurring_events($master, $existing['start']) as $candidate) { // our old this-and-future exception is obsolete if (!empty($candidate['thisandfuture'])) { unset($master['recurrence']['EXCEPTIONS'][$existing]); $saved = true; break; } // this occurrence doesn't yet have an exception else if (empty($candidate['isexception'])) { $event['_instance'] = $candidate['_instance']; $event['recurrence_date'] = $candidate['recurrence_date']; $master['recurrence']['EXCEPTIONS'][$i] = $event; $saved = true; break; } } } */ // set link to top-level exceptions $master['exceptions'] = &$master['recurrence']['EXCEPTIONS']; // returning false here will add a new exception return $saved; } /** * Add or update the given event as an exception to $master */ public static function add_exception(&$master, $event, $old = null) { if ($old) { $event['_instance'] = $old['_instance'] ?? null; if (empty($event['recurrence_date'])) { $event['recurrence_date'] = !empty($old['recurrence_date']) ? $old['recurrence_date'] : $old['start']; } } elseif (empty($event['recurrence_date'])) { $event['recurrence_date'] = $event['start']; } if (!isset($master['exceptions'])) { if (isset($master['recurrence']['EXCEPTIONS'])) { $master['exceptions'] = &$master['recurrence']['EXCEPTIONS']; } else { $master['exceptions'] = []; } } $existing = false; foreach ($master['exceptions'] as $i => $exception) { if (libcalendaring::is_recurrence_exception($event, $exception)) { $master['exceptions'][$i] = $event; $existing = true; } } if (!$existing) { $master['exceptions'][] = $event; } return true; } /** * Remove the noreply flags from attendees */ public static function clear_attandee_noreply(&$event) { if (!empty($event['attendees'])) { foreach ((array) $event['attendees'] as $i => $attendee) { unset($event['attendees'][$i]['noreply']); } } } /** * Merge certain properties from the overlay event to the base event object * * @param array $event The event object to be altered * @param array $overlay The overlay event object to be merged over $event * @param ?array $blacklist List of properties not allowed to be overwritten */ public static function merge_exception_data(&$event, $overlay, $blacklist = null) { $forbidden = ['id','uid','recurrence','recurrence_date','thisandfuture','organizer','_attachments']; if (is_array($blacklist)) { $forbidden = array_merge($forbidden, $blacklist); } foreach ($overlay as $prop => $value) { if ($prop == 'start' || $prop == 'end') { // handled by merge_exception_dates() below } elseif ($prop == 'thisandfuture' && $overlay['_instance'] == $event['_instance']) { $event[$prop] = $value; } elseif ($prop[0] != '_' && !in_array($prop, $forbidden)) { $event[$prop] = $value; } } self::merge_exception_dates($event, $overlay); } /** * Merge start/end date from the overlay event to the base event object * * @param array $event The event object to be altered * @param array $overlay The overlay event object to be merged over $event */ public static function merge_exception_dates(&$event, $overlay) { // compute date offset from the exception if ($overlay['start'] instanceof DateTimeInterface && $overlay['recurrence_date'] instanceof DateTimeInterface) { $date_offset = $overlay['recurrence_date']->diff($overlay['start']); } foreach (['start', 'end'] as $prop) { $value = $overlay[$prop]; if (isset($event[$prop]) && ($event[$prop] instanceof DateTime || $event[$prop] instanceof DateTimeImmutable)) { // set date value if overlay is an exception of the current instance if (substr($overlay['_instance'], 0, 8) == substr($event['_instance'], 0, 8)) { $event[$prop]->setDate(intval($value->format('Y')), intval($value->format('n')), intval($value->format('j'))); } // apply date offset elseif (!empty($date_offset)) { $event[$prop]->add($date_offset); } // adjust time of the recurring event instance $event[$prop]->setTime($value->format('G'), intval($value->format('i')), intval($value->format('s'))); } } } /** * Get events from source. * * @param int $start Event's new start (unix timestamp) * @param int $end Event's new end (unix timestamp) * @param string $search 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 events (optional) * @param int $modifiedsince Only list events modified since this time (unix timestamp) * * @return array A list of event records */ public function load_events($start, $end, $search = null, $calendars = null, $virtual = true, $modifiedsince = null) { if ($calendars && is_string($calendars)) { $calendars = explode(',', $calendars); } elseif (!$calendars) { $this->_read_calendars(); $calendars = array_keys($this->calendars); } $query = []; $events = []; $categories = []; if ($modifiedsince) { $query[] = ['changed', '>=', $modifiedsince]; } foreach ($calendars as $cid) { if ($storage = $this->get_calendar($cid)) { $events = array_merge($events, $storage->list_events($start, $end, $search, $virtual, $query)); $categories += $storage->categories; } } // add events from the address books birthday calendar if (in_array(self::BIRTHDAY_CALENDAR_ID, $calendars)) { $events = array_merge($events, $this->load_birthday_events($start, $end, $search, $modifiedsince)); } // add new categories to user prefs $old_categories = $this->rc->config->get('calendar_categories', $this->default_categories); $newcats = array_udiff( array_keys($categories), array_keys($old_categories), function ($a, $b) { return strcasecmp($a, $b); } ); if (!empty($newcats)) { foreach ($newcats as $category) { $old_categories[$category] = ''; // no color set yet } $this->rc->user->save_prefs(['calendar_categories' => $old_categories]); } array_walk($events, 'kolab_driver::to_rcube_event'); return $events; } /** * Get number of events in the given calendar * * @param mixed $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 */ public function count_events($calendars, $start, $end = null) { $counts = []; if ($calendars && is_string($calendars)) { $calendars = explode(',', $calendars); } elseif (!$calendars) { $this->_read_calendars(); $calendars = array_keys($this->calendars); } foreach ($calendars as $cid) { if ($storage = $this->get_calendar($cid)) { $counts[$cid] = $storage->count_events($start, $end); } } return $counts; } /** * Get a list of pending alarms to be displayed to the user * * @see calendar_driver::pending_alarms() */ public function pending_alarms($time, $calendars = null) { $interval = 300; $time -= $time % 60; $slot = $time; $slot -= $slot % $interval; $last = $time - max(60, $this->rc->config->get('refresh_interval', 0)); $last -= $last % $interval; // only check for alerts once in 5 minutes if ($last == $slot) { return []; } if ($calendars && is_string($calendars)) { $calendars = explode(',', $calendars); } $time = $slot + $interval; $alarms = []; $candidates = []; $query = [['tags', '=', 'x-has-alarms']]; $this->_read_calendars(); foreach ($this->calendars as $cid => $calendar) { // skip calendars with alarms disabled if (!$calendar->alarms || ($calendars && !in_array($cid, $calendars))) { continue; } foreach ($calendar->list_events($time, $time + 86400 * 365, null, 1, $query) as $e) { // add to list if alarm is set $alarm = libcalendaring::get_next_alarm($e); if ($alarm && !empty($alarm['time']) && $alarm['time'] >= $last && in_array($alarm['action'], $this->alarm_types) ) { $id = $alarm['id']; // use alarm-id as primary identifier $candidates[$id] = [ 'id' => $id, 'title' => $e['title'], 'location' => $e['location'], 'start' => $e['start'], 'end' => $e['end'], 'notifyat' => $alarm['time'], 'action' => $alarm['action'], ]; } } } // get alarm information stored in local database if (!empty($candidates)) { $dbdata = []; $alarm_ids = array_map([$this->rc->db, 'quote'], array_keys($candidates)); $result = $this->rc->db->query( "SELECT *" . " FROM " . $this->rc->db->table_name('kolab_alarms', true) . " WHERE `alarm_id` IN (" . implode(',', $alarm_ids) . ")" . " AND `user_id` = ?", $this->rc->user->ID ); while ($result && ($e = $this->rc->db->fetch_assoc($result))) { $dbdata[$e['alarm_id']] = $e; } foreach ($candidates as $id => $alarm) { if (!array_key_exists($id, $dbdata)) { continue; } // skip dismissed alarms if (!empty($dbdata[$id]['dismissed'])) { continue; } // snooze function may have shifted alarm time $notifyat = !empty($dbdata[$id]['notifyat']) ? strtotime($dbdata[$id]['notifyat']) : $alarm['notifyat']; if ($notifyat <= $time) { $alarms[] = $alarm; } } } return $alarms; } /** * Feedback after showing/sending an alarm notification * * @see calendar_driver::dismiss_alarm() */ public function dismiss_alarm($alarm_id, $snooze = 0) { $alarms_table = $this->rc->db->table_name('kolab_alarms', true); // delete old alarm entry $this->rc->db->query( "DELETE FROM $alarms_table" . " WHERE `alarm_id` = ? AND `user_id` = ?", $alarm_id, $this->rc->user->ID ); // set new notifyat time or unset if not snoozed $notifyat = $snooze > 0 ? date('Y-m-d H:i:s', time() + $snooze) : null; $query = $this->rc->db->query( "INSERT INTO $alarms_table" . " (`alarm_id`, `user_id`, `dismissed`, `notifyat`)" . " VALUES (?, ?, ?, ?)", $alarm_id, $this->rc->user->ID, $snooze > 0 ? 0 : 1, $notifyat ); return $this->rc->db->affected_rows($query); } /** * List attachments from the given event */ public function list_attachments($event) { if (!($storage = $this->get_calendar($event['calendar']))) { return []; } $event = $storage->get_event($event['id']); return $event['attachments']; } /** * Get attachment properties */ public function get_attachment($id, $event) { if (!($storage = $this->get_calendar($event['calendar']))) { return false; } // get old revision of event if (!empty($event['rev'])) { $event = $this->get_event_revison($event, $event['rev'], true); } else { $event = $storage->get_event($event['id']); } if ($event) { $attachments = $event['_attachments'] ?? $event['attachments']; foreach ((array) $attachments as $idx => $att) { if ((isset($att['id']) && $att['id'] == $id) || (!isset($att['id']) && $idx == $id)) { return $att; } } } return false; } /** * Get attachment body * @see calendar_driver::get_attachment_body() */ public function get_attachment_body($id, $event) { if (!($cal = $this->get_calendar($event['calendar']))) { return false; } // get old revision of event if (!empty($event['rev'])) { if (empty($this->bonnie_api)) { return false; } $cid = substr($id, 4); // call Bonnie API and get the raw mime message [$uid, $mailbox, $msguid] = $this->_resolve_event_identity($event); if ($msg_raw = $this->bonnie_api->rawdata('event', $uid, $event['rev'], $mailbox, $msguid)) { // parse the message and find the part with the matching content-id $message = rcube_mime::parse_message($msg_raw); foreach ((array) $message->parts as $part) { if (!empty($part->headers['content-id']) && trim($part->headers['content-id'], '<>') == $cid) { return $part->body; } } } return false; } return $cal->get_attachment_body($id, $event); } /** * Build a struct representing the given message reference * * @see calendar_driver::get_message_reference() */ public function get_message_reference($uri_or_headers, $folder = null) { if (is_object($uri_or_headers)) { $uri_or_headers = kolab_storage_config::get_message_uri($uri_or_headers, $folder); } if (is_string($uri_or_headers)) { return kolab_storage_config::get_message_reference($uri_or_headers, 'event'); } return false; } /** * List availabale categories * The default implementation reads them from config/user prefs */ public function list_categories() { // FIXME: complete list with categories saved in config objects (KEP:12) return $this->rc->config->get('calendar_categories', $this->default_categories); } /** * Create instances of a recurring event * * @param array $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) { // load the given event data into a libkolabxml container if (empty($event['_formatobj'])) { $event_xml = new kolab_format_event(); $event_xml->set($event); $event['_formatobj'] = $event_xml; } $this->_read_calendars(); $storage = reset($this->calendars); return $storage->get_recurring_events($event, $start, $end); } /** * */ protected function get_recurrence_count($event, $dtstart) { // load the given event data into a libkolabxml container if (empty($event['_formatobj'])) { $event_xml = new kolab_format_event(); $event_xml->set($event); $event['_formatobj'] = $event_xml; } // use libkolab to compute recurring events $recurrence = new kolab_date_recurrence($event['_formatobj']); $count = 0; while (($next_event = $recurrence->next_instance()) && $next_event['start'] <= $dtstart && $count < 1000) { $count++; } return $count; } /** * Fetch free/busy information from a person within the given range */ public function get_freebusy_list($email, $start, $end) { if (empty($email)/* || $end < time()*/) { return false; } $url = $this->storage->get_freebusy_url($email); if (empty($url)) { return false; } // map vcalendar fbtypes to internal values $fbtypemap = [ 'FREE' => calendar::FREEBUSY_FREE, 'BUSY-TENTATIVE' => calendar::FREEBUSY_TENTATIVE, 'X-OUT-OF-OFFICE' => calendar::FREEBUSY_OOF, 'OOF' => calendar::FREEBUSY_OOF, ]; // ask kolab server first try { $request_config = [ 'store_body' => true, 'follow_redirects' => true, ]; $request = libkolab::http_request($url, 'GET', $request_config); $response = $request->send(); // authentication required if ($response->getStatus() == 401) { $request->setAuth($this->rc->user->get_username(), $this->rc->decrypt($_SESSION['password'])); $response = $request->send(); } if ($response->getStatus() == 200) { $fbdata = $response->getBody(); } unset($request, $response); } catch (Exception $e) { - PEAR::raiseError("Error fetching free/busy information: " . $e->getMessage()); + rcube::raise_error($e); + return false; } // get free-busy url from contacts if (empty($fbdata)) { $fburl = null; foreach ((array) $this->rc->config->get('autocomplete_addressbooks', 'sql') as $book) { $abook = $this->rc->get_address_book($book); if ($result = $abook->search(['email'], $email, true, true, true/*, 'freebusyurl'*/)) { while ($contact = $result->iterate()) { if (!empty($contact['freebusyurl'])) { $fbdata = @file_get_contents($contact['freebusyurl']); break; } } } if (!empty($fbdata)) { break; } } } // parse free-busy information using Horde classes if (!empty($fbdata)) { $ical = $this->cal->get_ical(); $ical->import($fbdata); if ($fb = $ical->freebusy) { $result = []; foreach ($fb['periods'] as $tuple) { [$from, $to, $type] = $tuple; $result[] = [ $from->format('U'), $to->format('U'), $fbtypemap[$type] ?? calendar::FREEBUSY_BUSY, ]; } // we take 'dummy' free-busy lists as "unknown" if (empty($result) && !empty($fb['comment']) && stripos($fb['comment'], 'dummy')) { return false; } // set period from $start till the begin of the free-busy information as 'unknown' if (!empty($fb['start']) && ($fbstart = $fb['start']->format('U')) && $start < $fbstart) { array_unshift($result, [$start, $fbstart, calendar::FREEBUSY_UNKNOWN]); } // pad period till $end with status 'unknown' if (!empty($fb['end']) && ($fbend = $fb['end']->format('U')) && $fbend < $end) { $result[] = [$fbend, $end, calendar::FREEBUSY_UNKNOWN]; } return $result; } } return false; } /** * Handler to push folder triggers when sent from client. * Used to push free-busy changes asynchronously after updating an event */ public function push_freebusy() { // make shure triggering completes set_time_limit(0); ignore_user_abort(true); $cal = rcube_utils::get_input_value('source', rcube_utils::INPUT_GPC); if (!($cal = $this->get_calendar($cal))) { return false; } // trigger updates on folder $trigger = $cal->storage->trigger(); if (is_object($trigger) && is_a($trigger, 'PEAR_Error')) { rcube::raise_error( [ 'code' => 900, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Failed triggering folder. Error was " . $trigger->getMessage(), ], true, false ); } exit; } /** * Convert from driver format to external caledar app data */ public static function to_rcube_event(&$record) { if (!is_array($record)) { return $record; } $record['id'] = $record['uid'] ?? null; if (!empty($record['_instance'])) { $record['id'] .= '-' . $record['_instance']; if (empty($record['recurrence_id']) && !empty($record['recurrence'])) { $record['recurrence_id'] = $record['uid']; } } // all-day events go from 12:00 - 13:00 if (($record['start'] instanceof DateTime || $record['start'] instanceof DateTimeImmutable) && $record['end'] <= $record['start'] && !empty($record['allday']) ) { $record['end'] = clone $record['start']; $record['end']->add(new DateInterval('PT1H')); } // translate internal '_attachments' to external 'attachments' list if (!empty($record['_attachments'])) { $attachments = []; foreach ($record['_attachments'] as $key => $attachment) { if ($attachment !== false) { if (empty($attachment['name'])) { $attachment['name'] = $key; } unset($attachment['path'], $attachment['content']); $attachments[] = $attachment; } } $record['attachments'] = $attachments; } if (!empty($record['attendees'])) { foreach ((array) $record['attendees'] as $i => $attendee) { if (isset($attendee['delegated-from']) && is_array($attendee['delegated-from'])) { $record['attendees'][$i]['delegated-from'] = implode(', ', $attendee['delegated-from']); } if (isset($attendee['delegated-to']) && is_array($attendee['delegated-to'])) { $record['attendees'][$i]['delegated-to'] = implode(', ', $attendee['delegated-to']); } } } // Roundcube only supports one category assignment if (!empty($record['categories']) && is_array($record['categories'])) { $record['categories'] = $record['categories'][0]; } // the cancelled flag transltes into status=CANCELLED if (!empty($record['cancelled'])) { $record['status'] = 'CANCELLED'; } // The web client only supports DISPLAY type of alarms if (!empty($record['alarms'])) { $record['alarms'] = preg_replace('/:[A-Z]+$/', ':DISPLAY', $record['alarms']); } // remove empty recurrence array if (empty($record['recurrence'])) { unset($record['recurrence']); } // clean up exception data elseif (!empty($record['recurrence']['EXCEPTIONS'])) { array_walk($record['recurrence']['EXCEPTIONS'], function (&$exception) { unset($exception['_mailbox'], $exception['_msguid'], $exception['_formatobj'], $exception['_attachments'] ); }); } unset($record['_mailbox'], $record['_msguid'], $record['_type'], $record['_size'], $record['_formatobj'], $record['_attachments'], $record['exceptions'], $record['x-custom'] ); return $record; } /** * */ public static function from_rcube_event($event, $old = []) { kolab_format::merge_attachments($event, $old); return $event; } /** * Set CSS class according to the event's attendde partstat */ public static function add_partstat_class($event, $partstats, $user = null) { // set classes according to PARTSTAT if (!empty($event['attendees'])) { $user_emails = libcalendaring::get_instance()->get_user_emails($user); $partstat = 'UNKNOWN'; foreach ($event['attendees'] as $attendee) { if (in_array($attendee['email'], $user_emails)) { if (!empty($attendee['status'])) { $partstat = $attendee['status']; } break; } } if (in_array($partstat, $partstats)) { $event['className'] = trim(($event['className'] ?? '') . ' fc-invitation-' . strtolower($partstat)); } } return $event; } /** * Provide a list of revisions for the given event * * @param array $event Hash array with event properties * * @return array|false List of changes, each as a hash array * @see calendar_driver::get_event_changelog() */ public function get_event_changelog($event) { if (empty($this->bonnie_api)) { return false; } [$uid, $mailbox, $msguid] = $this->_resolve_event_identity($event); $result = $this->bonnie_api->changelog('event', $uid, $mailbox, $msguid); if (is_array($result) && $result['uid'] == $uid) { return $result['changes']; } return false; } /** * Get a list of property changes beteen two revisions of an event * * @param array $event Hash array with event properties * @param mixed $rev1 Old Revision * @param mixed $rev2 New Revision * * @return array|false List of property changes, each as a hash array * @see calendar_driver::get_event_diff() */ public function get_event_diff($event, $rev1, $rev2) { if (empty($this->bonnie_api)) { return false; } [$uid, $mailbox, $msguid] = $this->_resolve_event_identity($event); // get diff for the requested recurrence instance $instance_id = $event['id'] != $uid ? substr($event['id'], strlen($uid) + 1) : null; // call Bonnie API $result = $this->bonnie_api->diff('event', $uid, $rev1, $rev2, $mailbox, $msguid, $instance_id); if (is_array($result) && $result['uid'] == $uid) { $result['rev1'] = $rev1; $result['rev2'] = $rev2; $keymap = [ 'dtstart' => 'start', 'dtend' => 'end', 'dstamp' => 'changed', 'summary' => 'title', 'alarm' => 'alarms', 'attendee' => 'attendees', 'attach' => 'attachments', 'rrule' => 'recurrence', 'transparency' => 'free_busy', 'lastmodified-date' => 'changed', ]; $prop_keymaps = [ 'attachments' => ['fmttype' => 'mimetype', 'label' => 'name'], 'attendees' => ['partstat' => 'status'], ]; $special_changes = []; // map kolab event properties to keys the client expects - array_walk($result['changes'], function (&$change, $i) use ($keymap, $prop_keymaps, $special_changes) { + array_walk($result['changes'], function (&$change, $i) use ($keymap, $prop_keymaps, &$special_changes) { if (array_key_exists($change['property'], $keymap)) { $change['property'] = $keymap[$change['property']]; } // translate free_busy values if ($change['property'] == 'free_busy') { $change['old'] = !empty($change['old']) ? 'free' : 'busy'; $change['new'] = !empty($change['new']) ? 'free' : 'busy'; } // map alarms trigger value if ($change['property'] == 'alarms') { if (!empty($change['old']['trigger'])) { $change['old']['trigger'] = $change['old']['trigger']['value']; } if (!empty($change['new']['trigger'])) { $change['new']['trigger'] = $change['new']['trigger']['value']; } } // make all property keys uppercase if ($change['property'] == 'recurrence') { $special_changes['recurrence'] = $i; foreach (['old', 'new'] as $m) { if (!empty($change[$m])) { $props = []; foreach ($change[$m] as $k => $v) { $props[strtoupper($k)] = $v; } $change[$m] = $props; } } } // map property keys names if (!empty($prop_keymaps[$change['property']])) { foreach ($prop_keymaps[$change['property']] as $k => $dest) { if (!empty($change['old']) && array_key_exists($k, $change['old'])) { $change['old'][$dest] = $change['old'][$k]; unset($change['old'][$k]); } if (!empty($change['new']) && array_key_exists($k, $change['new'])) { $change['new'][$dest] = $change['new'][$k]; unset($change['new'][$k]); } } } if ($change['property'] == 'exdate') { $special_changes['exdate'] = $i; } elseif ($change['property'] == 'rdate') { $special_changes['rdate'] = $i; } }); // merge some recurrence changes foreach (['exdate', 'rdate'] as $prop) { if (array_key_exists($prop, $special_changes)) { $exdate = $result['changes'][$special_changes[$prop]]; if (array_key_exists('recurrence', $special_changes)) { $recurrence = &$result['changes'][$special_changes['recurrence']]; } else { $i = count($result['changes']); $result['changes'][$i] = ['property' => 'recurrence', 'old' => [], 'new' => []]; $recurrence = &$result['changes'][$i]['recurrence']; } $key = strtoupper($prop); $recurrence['old'][$key] = $exdate['old']; $recurrence['new'][$key] = $exdate['new']; unset($result['changes'][$special_changes[$prop]]); } } return $result; } return false; } /** * Return full data of a specific revision of an event * * @param array $event Hash array with event properties * @param mixed $rev Revision number * * @return array|false Event object as hash array * @see calendar_driver::get_event_revison() */ public function get_event_revison($event, $rev, $internal = false) { if (empty($this->bonnie_api)) { return false; } $eventid = $event['id']; $calid = $event['calendar']; [$uid, $mailbox, $msguid] = $this->_resolve_event_identity($event); // call Bonnie API $result = $this->bonnie_api->get('event', $uid, $rev, $mailbox, $msguid); if (is_array($result) && $result['uid'] == $uid && !empty($result['xml'])) { /** @var kolab_format_event $format */ $format = kolab_format::factory('event'); $format->load($result['xml']); $event = $format->to_array(); $format->get_attachments($event, true); // get the right instance from a recurring event if ($eventid != $event['uid']) { $instance_id = substr($eventid, strlen($event['uid']) + 1); // check for recurrence exception first if ($instance = $format->get_instance($instance_id)) { $event = $instance; } else { // not a exception, compute recurrence... $event['_formatobj'] = $format; $recurrence_date = rcube_utils::anytodatetime($instance_id, $event['start']->getTimezone()); foreach ($this->get_recurring_events($event, $event['start'], $recurrence_date) as $instance) { if ($instance['id'] == $eventid) { $event = $instance; break; } } } } if ($format->is_valid()) { $event['calendar'] = $calid; $event['rev'] = $result['rev']; return $internal ? $event : self::to_rcube_event($event); } } return false; } /** * Command the backend to restore a certain revision of an event. * This shall replace the current event with an older version. * * @param mixed $event UID string or hash array with event properties: * id: Event identifier * calendar: Calendar identifier * @param mixed $rev Revision number * * @return bool True on success, False on failure */ public function restore_event_revision($event, $rev) { if (empty($this->bonnie_api)) { return false; } [$uid, $mailbox, $msguid] = $this->_resolve_event_identity($event); $calendar = $this->get_calendar($event['calendar']); $success = false; if ($calendar && $calendar->storage && $calendar->editable) { if ($raw_msg = $this->bonnie_api->rawdata('event', $uid, $rev, $mailbox)) { $imap = $this->rc->get_storage(); // insert $raw_msg as new message if ($imap->save_message($calendar->storage->name, $raw_msg, null, false)) { $success = true; // delete old revision from imap and cache $imap->delete_message($msguid, $calendar->storage->name); $calendar->storage->cache->set($msguid, false); } } } return $success; } /** * Helper method to resolved the given event identifier into uid and folder * * @return array (uid,folder,msguid) tuple */ protected function _resolve_event_identity($event) { $mailbox = $msguid = null; if (is_array($event)) { $uid = !empty($event['uid']) ? $event['uid'] : $event['id']; if (($cal = $this->get_calendar($event['calendar'])) && !($cal instanceof kolab_invitation_calendar)) { $mailbox = $cal->get_mailbox_id(); // get event object from storage in order to get the real object uid an msguid if ($ev = $cal->get_event($event['id'])) { $msguid = $ev['_msguid']; $uid = $ev['uid']; } } } else { $uid = $event; // get event object from storage in order to get the real object uid an msguid if ($ev = $this->get_event($event)) { $mailbox = $ev['_mailbox']; $msguid = $ev['_msguid']; $uid = $ev['uid']; } } return [$uid, $mailbox, $msguid]; } /** * 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) { $special_calendars = [ self::BIRTHDAY_CALENDAR_ID, self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED, ]; // show default dialog for birthday calendar if (in_array($calendar['id'], $special_calendars)) { if ($calendar['id'] != self::BIRTHDAY_CALENDAR_ID) { unset($formfields['showalarms']); } // General tab $form['props'] = [ 'name' => $this->rc->gettext('properties'), 'fields' => $formfields, ]; return kolab_utils::folder_form($form, '', 'calendar'); } $this->_read_calendars(); if (!empty($calendar['id']) && ($cal = $this->calendars[$calendar['id']])) { $folder = $cal->get_realname(); // UTF7 $color = $cal->get_color(); } else { $folder = ''; $color = ''; } $hidden_fields[] = ['name' => 'oldname', 'value' => $folder]; $storage = $this->rc->get_storage(); $delim = $storage->get_hierarchy_delimiter(); $form = []; if (strlen($folder)) { $path_imap = explode($delim, $folder); array_pop($path_imap); // pop off name part $path_imap = implode($delim, $path_imap); $options = $storage->folder_info($folder); } else { $path_imap = ''; } // General tab $form['props'] = [ 'name' => $this->rc->gettext('properties'), 'fields' => [], ]; $protected = !empty($options) && (!empty($options['norename']) || !empty($options['protected'])); // Disable folder name input if ($protected) { $input_name = new html_hiddenfield(['name' => 'name', 'id' => 'calendar-name', 'value' => $folder]); $formfields['name']['value'] = $this->storage->object_name($folder) . $input_name->show(); } // calendar name (default field) $form['props']['fields']['location'] = $formfields['name']; if ($protected) { // prevent user from moving folder $hidden_fields[] = ['name' => 'parent', 'value' => $path_imap]; } else { $select = $this->storage->folder_selector('event', ['name' => 'parent', 'id' => 'calendar-parent'], $folder); $form['props']['fields']['path'] = [ 'id' => 'calendar-parent', 'label' => $this->cal->gettext('parentcalendar'), 'value' => $select->show(strlen($folder) ? $path_imap : ''), ]; } // calendar color (default field) $form['props']['fields']['color'] = $formfields['color']; $form['props']['fields']['alarms'] = $formfields['showalarms']; return kolab_utils::folder_form($form, $folder, 'calendar', $hidden_fields); } /** * Handler for user_delete plugin hook */ public function user_delete($args) { $db = $this->rc->get_dbh(); foreach (['kolab_alarms', 'itipinvitations'] as $table) { $db->query("DELETE FROM " . $this->rc->db->table_name($table, true) . " WHERE `user_id` = ?", $args['user']->ID); } return $args; } } diff --git a/plugins/calendar/lib/calendar_ui.php b/plugins/calendar/lib/calendar_ui.php index 68f987a3..476f5572 100644 --- a/plugins/calendar/lib/calendar_ui.php +++ b/plugins/calendar/lib/calendar_ui.php @@ -1,1072 +1,1073 @@ * @author Thomas Bruederli * * Copyright (C) 2010, Lazlo Westerhof * Copyright (C) 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_ui { public $screen; public $action; public $calendar; /** @var rcmail */ private $rc; /** @var calendar Calendar plugin */ private $cal; /** @var bool */ private $ready = false; /** * Object constructor * * @param calendar $cal Calendar plugin */ public function __construct($cal) { $this->cal = $cal; $this->rc = $cal->rc; $this->screen = $this->rc->task == 'calendar' ? ($this->rc->action ?: 'calendar') : 'other'; } /** * Calendar UI initialization and requests handlers */ public function init() { if ($this->ready) { // already done return; } // add taskbar button $this->cal->add_button( [ 'command' => 'calendar', 'class' => 'button-calendar', 'classsel' => 'button-calendar button-selected', 'innerclass' => 'button-inner', 'label' => 'calendar.calendar', 'type' => 'link', ], 'taskbar' ); // load basic client script if ($this->rc->action != 'print') { $this->cal->include_script('calendar_base.js'); } $this->addCSS(); $this->ready = true; } /** * Register handler methods for the template engine */ public function init_templates() { $this->cal->register_handler('plugin.calendar_css', [$this, 'calendar_css']); $this->cal->register_handler('plugin.calendar_list', [$this, 'calendar_list']); $this->cal->register_handler('plugin.calendar_select', [$this, 'calendar_select']); $this->cal->register_handler('plugin.identity_select', [$this, 'identity_select']); $this->cal->register_handler('plugin.category_select', [$this, 'category_select']); $this->cal->register_handler('plugin.status_select', [$this, 'status_select']); $this->cal->register_handler('plugin.freebusy_select', [$this, 'freebusy_select']); $this->cal->register_handler('plugin.priority_select', [$this, 'priority_select']); $this->cal->register_handler('plugin.alarm_select', [$this, 'alarm_select']); $this->cal->register_handler('plugin.recurrence_form', [$this->cal->lib, 'recurrence_form']); $this->cal->register_handler('plugin.attendees_list', [$this, 'attendees_list']); $this->cal->register_handler('plugin.attendees_form', [$this, 'attendees_form']); $this->cal->register_handler('plugin.resources_form', [$this, 'resources_form']); $this->cal->register_handler('plugin.resources_list', [$this, 'resources_list']); $this->cal->register_handler('plugin.resources_searchform', [$this, 'resources_search_form']); $this->cal->register_handler('plugin.resource_info', [$this, 'resource_info']); $this->cal->register_handler('plugin.resource_calendar', [$this, 'resource_calendar']); $this->cal->register_handler('plugin.attendees_freebusy_table', [$this, 'attendees_freebusy_table']); $this->cal->register_handler('plugin.edit_attendees_notify', [$this, 'edit_attendees_notify']); $this->cal->register_handler('plugin.edit_recurrence_sync', [$this, 'edit_recurrence_sync']); $this->cal->register_handler('plugin.edit_recurring_warning', [$this, 'recurring_event_warning']); $this->cal->register_handler('plugin.event_rsvp_buttons', [$this, 'event_rsvp_buttons']); $this->cal->register_handler('plugin.agenda_options', [$this, 'agenda_options']); $this->cal->register_handler('plugin.events_import_form', [$this, 'events_import_form']); $this->cal->register_handler('plugin.events_export_form', [$this, 'events_export_form']); $this->cal->register_handler('plugin.object_changelog_table', ['libkolab', 'object_changelog_table']); $this->cal->register_handler('plugin.searchform', [$this->rc->output, 'search_form']); kolab_attachments_handler::ui(); } /** * Adds CSS stylesheets to the page header */ public function addCSS() { $skin_path = $this->cal->local_skin_path(); if ( $this->rc->task == 'calendar' && (!$this->rc->action || in_array($this->rc->action, ['index', 'print'])) ) { // Include fullCalendar style before skin file for simpler style overriding $this->cal->include_stylesheet($skin_path . '/fullcalendar.css'); } $this->cal->include_stylesheet($skin_path . '/calendar.css'); if ($this->rc->task == 'calendar' && $this->rc->action == 'print') { $this->cal->include_stylesheet($skin_path . '/print.css'); } } /** * Adds JS files to the page header */ public function addJS() { $this->cal->include_script('lib/js/moment.js'); $this->cal->include_script('lib/js/fullcalendar.js'); if ($this->rc->task == 'calendar' && $this->rc->action == 'print') { $this->cal->include_script('print.js'); } else { $this->rc->output->include_script('treelist.js'); $this->cal->api->include_script('libkolab/libkolab.js'); $this->cal->include_script('calendar_ui.js'); jqueryui::miniColors(); } } /** * Add custom style for the calendar UI */ public function calendar_css($attrib = []) { $categories = $this->cal->driver->list_categories(); $calendars = $this->cal->driver->list_calendars(); $js_categories = []; $mode = $this->rc->config->get('calendar_event_coloring', $this->cal->defaults['calendar_event_coloring']); $css = "\n"; foreach ((array) $categories as $class => $color) { if (!empty($color)) { $js_categories[$class] = $color; $color = ltrim($color, '#'); $class = 'cat-' . asciiwords(strtolower($class), true); $css .= ".$class { color: #$color; }\n"; } } $this->rc->output->set_env('calendar_categories', $js_categories); foreach ((array) $calendars as $id => $prop) { if (!empty($prop['color'])) { $css .= $this->calendar_css_classes($id, $prop, $mode, $attrib); } } return html::tag('style', ['type' => 'text/css'], $css); } /** * Calendar folder specific CSS classes */ public function calendar_css_classes($id, $prop, $mode, $attrib = []) { $color = $folder_color = $prop['color']; // replace white with skin-defined color if (!empty($attrib['folder-fallback-color']) && preg_match('/^f+$/i', $folder_color)) { $folder_color = ltrim($attrib['folder-fallback-color'], '#'); } $class = 'cal-' . asciiwords($id, true); $css = "li .$class"; if (!empty($attrib['folder-class'])) { $css = str_replace('$class', $class, $attrib['folder-class']); } $css .= " { color: #$folder_color; }\n"; return $css . ".$class .handle { background-color: #$color; }\n"; } /** * Generate HTML content of the calendars list (or metadata only) */ public function calendar_list($attrib = [], $js_only = false) { $html = ''; $jsenv = []; $tree = true; $calendars = $this->cal->driver->list_calendars(0, $tree); // walk folder tree + // @phpstan-ignore-next-line if (is_object($tree)) { $html = $this->list_tree_html($tree, $calendars, $jsenv, $attrib); // append birthdays calendar which isn't part of $tree if (!empty($calendars[calendar_driver::BIRTHDAY_CALENDAR_ID])) { $bdaycal = $calendars[calendar_driver::BIRTHDAY_CALENDAR_ID]; $calendars = [calendar_driver::BIRTHDAY_CALENDAR_ID => $bdaycal]; } else { $calendars = []; // clear array for flat listing } } elseif (isset($attrib['class'])) { // fall-back to flat folder listing $attrib['class'] .= ' flat'; } foreach ((array) $calendars as $id => $prop) { if (!empty($attrib['activeonly']) && empty($prop['active'])) { continue; } $li_content = $this->calendar_list_item($id, $prop, $jsenv, !empty($attrib['activeonly'])); $li_attr = [ 'id' => 'rcmlical' . $id, 'class' => $prop['group'] ?? null, ]; $html .= html::tag('li', $li_attr, $li_content); } $this->rc->output->set_env('calendars', $jsenv); if ($js_only) { return; } $this->rc->output->set_env('source', rcube_utils::get_input_value('source', rcube_utils::INPUT_GET)); $this->rc->output->add_gui_object('calendarslist', !empty($attrib['id']) ? $attrib['id'] : 'rccalendarlist'); return html::tag('ul', $attrib, $html, html::$common_attrib); } /** * Return html for a structured list
    for the folder tree */ public function list_tree_html($node, $data, &$jsenv, $attrib) { $out = ''; foreach ($node->children as $folder) { $id = $folder->id; $prop = $data[$id]; $is_collapsed = false; // TODO: determine this somehow? $content = $this->calendar_list_item($id, $prop, $jsenv, !empty($attrib['activeonly'])); if (!empty($folder->children)) { $content .= html::tag( 'ul', - ['style' => $is_collapsed ? "display:none;" : null], + ['style' => $is_collapsed ? "display:none;" : null], // @phpstan-ignore-line $this->list_tree_html($folder, $data, $jsenv, $attrib) ); } if (strlen($content)) { $li_attr = [ 'id' => 'rcmlical' . rcube_utils::html_identifier($id), 'class' => $prop['group'] . (!empty($prop['virtual']) ? ' virtual' : ''), ]; $out .= html::tag('li', $li_attr, $content); } } return $out; } /** * Helper method to build a calendar list item (HTML content and js data) */ public function calendar_list_item($id, $prop, &$jsenv, $activeonly = false) { // enrich calendar properties with settings from the driver if (empty($prop['virtual'])) { unset($prop['user_id']); $prop['alarms'] = $this->cal->driver->alarms; $prop['attendees'] = $this->cal->driver->attendees; $prop['freebusy'] = $this->cal->driver->freebusy; $prop['attachments'] = $this->cal->driver->attachments; $prop['undelete'] = $this->cal->driver->undelete; $prop['feedurl'] = $this->cal->get_url( [ '_cal' => $this->cal->ical_feed_hash($id) . '.ics', 'action' => 'feed', ] ); $jsenv[$id] = $prop; } if (!empty($prop['title'])) { $title = $prop['title']; } elseif ($prop['name'] != $prop['listname'] || strlen($prop['name']) > 25) { $title = html_entity_decode($prop['name'], ENT_COMPAT, RCUBE_CHARSET); } else { $title = ''; } $classes = ['calendar', 'cal-' . asciiwords($id, true)]; if (!empty($prop['virtual'])) { $classes[] = 'virtual'; } elseif (empty($prop['editable'])) { $classes[] = 'readonly'; } if (!empty($prop['subscribed'])) { $classes[] = 'subscribed'; if ($prop['subscribed'] === 2) { $classes[] = 'partial'; } } if (!empty($prop['class'])) { $classes[] = $prop['class']; } $content = ''; if (!$activeonly || !empty($prop['active'])) { $label_id = 'cl:' . $id; $content = html::a( ['class' => 'calname', 'id' => $label_id, 'title' => $title, 'href' => '#'], rcube::Q(!empty($prop['editname']) ? $prop['editname'] : $prop['listname']) ); if (empty($prop['virtual'])) { $color = !empty($prop['color']) ? $prop['color'] : 'f00'; $actions = ''; if (!empty($prop['removable'])) { $actions .= html::a( [ 'href' => '#', 'class' => 'remove', 'title' => $this->cal->gettext('removelist'), ], ' ' ); } $actions .= html::a( [ 'href' => '#', 'class' => 'quickview', 'title' => $this->cal->gettext('quickview'), 'role' => 'checkbox', 'aria-checked' => 'false', ], '' ); if (!isset($prop['subscriptions']) || $prop['subscriptions'] !== false) { if (!empty($prop['subscribed'])) { $actions .= html::a( [ 'href' => '#', 'class' => 'subscribed', 'title' => $this->cal->gettext('calendarsubscribe'), 'role' => 'checkbox', 'aria-checked' => !empty($prop['subscribed']) ? 'true' : 'false', ], ' ' ); } } $content .= html::tag('input', [ 'type' => 'checkbox', 'name' => '_cal[]', 'value' => $id, 'checked' => !empty($prop['active']), 'aria-labelledby' => $label_id, ]) . html::span('actions', $actions) . html::span(['class' => 'handle', 'style' => "background-color: #$color"], ' '); } $content = html::div(implode(' ', $classes), $content); } return $content; } /** * Render a HTML for agenda options form */ public function agenda_options($attrib = []) { $attrib += ['id' => 'agendaoptions']; $attrib['style'] = 'display:none'; $select_range = new html_select(['name' => 'listrange', 'id' => 'agenda-listrange', 'class' => 'form-control custom-select']); $select_range->add(1 . ' ' . preg_replace('/\(.+\)/', '', $this->cal->lib->gettext('days')), ''); foreach ([2,5,7,14,30,60,90,180,365] as $days) { $select_range->add($days . ' ' . preg_replace('/\(|\)/', '', $this->cal->lib->gettext('days')), $days); } $html = html::span( 'input-group', html::label( ['for' => 'agenda-listrange', 'class' => 'input-group-prepend'], html::span('input-group-text', $this->cal->gettext('listrange')) ) . $select_range->show($this->rc->config->get('calendar_agenda_range', $this->cal->defaults['calendar_agenda_range'])) ); return html::div($attrib, $html); } /** * Render a HTML select box for calendar selection */ public function calendar_select($attrib = []) { $attrib['name'] = 'calendar'; $attrib['is_escaped'] = true; $select = new html_select($attrib); foreach ((array) $this->cal->driver->list_calendars() as $id => $prop) { if ( !empty($prop['editable']) || (!empty($prop['rights']) && strpos($prop['rights'], 'i') !== false) ) { $select->add($prop['name'], $id); } } return $select->show(null); } /** * Render a HTML select box for user identity selection */ public function identity_select($attrib = []) { $attrib['name'] = 'identity'; $select = new html_select($attrib); $identities = $this->rc->user->list_emails(); foreach ($identities as $ident) { $select->add(format_email_recipient($ident['email'], $ident['name']), $ident['identity_id']); } return $select->show(null); } /** * Render a HTML select box to select an event category */ public function category_select($attrib = []) { $attrib['name'] = 'categories'; $select = new html_select($attrib); $select->add('---', ''); foreach (array_keys((array) $this->cal->driver->list_categories()) as $cat) { $select->add($cat, $cat); } return $select->show(null); } /** * Render a HTML select box for status property */ public function status_select($attrib = []) { $attrib['name'] = 'status'; $select = new html_select($attrib); $select->add('---', ''); $select->add($this->cal->gettext('status-confirmed'), 'CONFIRMED'); $select->add($this->cal->gettext('status-cancelled'), 'CANCELLED'); $select->add($this->cal->gettext('status-tentative'), 'TENTATIVE'); return $select->show(null); } /** * Render a HTML select box for free/busy/out-of-office property */ public function freebusy_select($attrib = []) { $attrib['name'] = 'freebusy'; $select = new html_select($attrib); $select->add($this->cal->gettext('free'), 'free'); $select->add($this->cal->gettext('busy'), 'busy'); // out-of-office is not supported by libkolabxml (#3220) // $select->add($this->cal->gettext('outofoffice'), 'outofoffice'); $select->add($this->cal->gettext('tentative'), 'tentative'); return $select->show(null); } /** * Render a HTML select for event priorities */ public function priority_select($attrib = []) { $attrib['name'] = 'priority'; $select = new html_select($attrib); $select->add('---', '0'); $select->add('1 ' . $this->cal->gettext('highest'), '1'); $select->add('2 ' . $this->cal->gettext('high'), '2'); $select->add('3 ', '3'); $select->add('4 ', '4'); $select->add('5 ' . $this->cal->gettext('normal'), '5'); $select->add('6 ', '6'); $select->add('7 ', '7'); $select->add('8 ' . $this->cal->gettext('low'), '8'); $select->add('9 ' . $this->cal->gettext('lowest'), '9'); return $select->show(null); } /** * Render HTML form for alarm configuration */ public function alarm_select($attrib = []) { return $this->cal->lib->alarm_select($attrib, $this->cal->driver->alarm_types, $this->cal->driver->alarm_absolute); } /** * Render HTML for attendee notification warning */ public function edit_attendees_notify($attrib = []) { $checkbox = new html_checkbox(['name' => '_notify', 'id' => 'edit-attendees-donotify', 'value' => 1, 'class' => 'pretty-checkbox']); return html::div($attrib, html::label(null, $checkbox->show(1) . ' ' . $this->cal->gettext('sendnotifications'))); } /** * Render HTML for recurrence option to align start date with the recurrence rule */ public function edit_recurrence_sync($attrib = []) { $checkbox = new html_checkbox(['name' => '_start_sync', 'value' => 1, 'class' => 'pretty-checkbox']); return html::div($attrib, html::label(null, $checkbox->show(1) . ' ' . $this->cal->gettext('eventstartsync'))); } /** * Generate the form for recurrence settings */ public function recurring_event_warning($attrib = []) { $attrib['id'] = 'edit-recurring-warning'; $radio = new html_radiobutton(['name' => '_savemode', 'class' => 'edit-recurring-savemode']); $form = html::label(null, $radio->show('', ['value' => 'current']) . $this->cal->gettext('currentevent')) . ' ' . html::label(null, $radio->show('', ['value' => 'future']) . $this->cal->gettext('futurevents')) . ' ' . html::label(null, $radio->show('all', ['value' => 'all']) . $this->cal->gettext('allevents')) . ' ' . html::label(null, $radio->show('', ['value' => 'new']) . $this->cal->gettext('saveasnew')); return html::div( $attrib, html::div('message', $this->cal->gettext('changerecurringeventwarning')) . html::div('savemode', $form) ); } /** * Form for uploading and importing events */ public function events_import_form($attrib = []) { if (empty($attrib['id'])) { $attrib['id'] = 'rcmImportForm'; } // Get max filesize, enable upload progress bar $max_filesize = $this->rc->upload_init(); $accept = '.ics, text/calendar, text/x-vcalendar, application/ics'; if (class_exists('ZipArchive', false)) { $accept .= ', .zip, application/zip'; } $input = new html_inputfield([ 'id' => 'importfile', 'type' => 'file', 'name' => '_data', 'size' => !empty($attrib['uploadfieldsize']) ? $attrib['uploadfieldsize'] : null, 'accept' => $accept, ]); $select = new html_select(['name' => '_range', 'id' => 'event-import-range']); $select->add( [ $this->cal->gettext('onemonthback'), $this->cal->gettext(['name' => 'nmonthsback', 'vars' => ['nr' => 2]]), $this->cal->gettext(['name' => 'nmonthsback', 'vars' => ['nr' => 3]]), $this->cal->gettext(['name' => 'nmonthsback', 'vars' => ['nr' => 6]]), $this->cal->gettext(['name' => 'nmonthsback', 'vars' => ['nr' => 12]]), $this->cal->gettext('all'), ], ['1','2','3','6','12',0] ); $html = html::div( 'form-section form-group row', html::label( ['class' => 'col-sm-4 col-form-label', 'for' => 'importfile'], rcube::Q($this->rc->gettext('importfromfile')) ) . html::div( 'col-sm-8', $input->show() . html::div('hint', $this->rc->gettext(['name' => 'maxuploadsize', 'vars' => ['size' => $max_filesize]])) ) ); $html .= html::div( 'form-section form-group row', html::label( ['for' => 'event-import-calendar', 'class' => 'col-form-label col-sm-4'], $this->cal->gettext('calendar') ) . html::div('col-sm-8', $this->calendar_select(['name' => 'calendar', 'id' => 'event-import-calendar'])) ); $html .= html::div( 'form-section form-group row', html::label( ['for' => 'event-import-range', 'class' => 'col-form-label col-sm-4'], $this->cal->gettext('importrange') ) . html::div('col-sm-8', $select->show(1)) ); $this->rc->output->add_gui_object('importform', $attrib['id']); $this->rc->output->add_label('import'); return html::tag('p', null, $this->cal->gettext('importtext')) . html::tag( 'form', [ 'action' => $this->rc->url(['task' => 'calendar', 'action' => 'import_events']), 'method' => 'post', 'enctype' => 'multipart/form-data', 'id' => $attrib['id'], ], $html ); } /** * Form to select options for exporting events */ public function events_export_form($attrib = []) { if (empty($attrib['id'])) { $attrib['id'] = 'rcmExportForm'; } $html = html::div( 'form-section form-group row', html::label( ['for' => 'event-export-calendar', 'class' => 'col-sm-4 col-form-label'], $this->cal->gettext('calendar') ) . html::div('col-sm-8', $this->calendar_select(['name' => 'calendar', 'id' => 'event-export-calendar', 'class' => 'form-control custom-select'])) ); $select = new html_select([ 'name' => 'range', 'id' => 'event-export-range', 'class' => 'form-control custom-select rounded-right', ]); $select->add( [ $this->cal->gettext('all'), $this->cal->gettext('onemonthback'), $this->cal->gettext(['name' => 'nmonthsback', 'vars' => ['nr' => 2]]), $this->cal->gettext(['name' => 'nmonthsback', 'vars' => ['nr' => 3]]), $this->cal->gettext(['name' => 'nmonthsback', 'vars' => ['nr' => 6]]), $this->cal->gettext(['name' => 'nmonthsback', 'vars' => ['nr' => 12]]), $this->cal->gettext('customdate'), ], [0,'1','2','3','6','12','custom'] ); $startdate = new html_inputfield([ 'name' => 'start', 'size' => 11, 'id' => 'event-export-startdate', 'style' => 'display:none', ]); $html .= html::div( 'form-section form-group row', html::label( ['for' => 'event-export-range', 'class' => 'col-sm-4 col-form-label'], $this->cal->gettext('exportrange') ) . html::div('col-sm-8 input-group', $select->show(0) . $startdate->show()) ); $checkbox = new html_checkbox([ 'name' => 'attachments', 'id' => 'event-export-attachments', 'value' => 1, 'class' => 'form-check-input pretty-checkbox', ]); $html .= html::div( 'form-section form-check row', html::label( ['for' => 'event-export-attachments', 'class' => 'col-sm-4 col-form-label'], $this->cal->gettext('exportattachments') ) . html::div('col-sm-8', $checkbox->show(1)) ); $this->rc->output->add_gui_object('exportform', $attrib['id']); return html::tag( 'form', $attrib + [ 'action' => $this->rc->url(['task' => 'calendar', 'action' => 'export_events']), 'method' => 'post', 'id' => $attrib['id'], ], $html ); } /** * Handler for calendar form template. * The form content could be overriden by the driver */ public function calendar_editform($action, $calendar = []) { $this->action = $action; $this->calendar = $calendar; // load miniColors js/css files jqueryui::miniColors(); $this->rc->output->set_env('pagetitle', $this->cal->gettext('calendarprops')); $this->rc->output->add_handler('folderform', [$this, 'calendarform']); $this->rc->output->send('libkolab.folderform'); } /** * Handler for calendar form template. * The form content could be overriden by the driver */ public function calendarform($attrib) { // compose default calendar form fields $input_name = new html_inputfield(['name' => 'name', 'id' => 'calendar-name', 'size' => 20]); $input_color = new html_inputfield(['name' => 'color', 'id' => 'calendar-color', 'size' => 7, 'class' => 'colors']); $formfields = [ 'name' => [ 'label' => $this->cal->gettext('name'), 'value' => $input_name->show($this->calendar['name'] ?? ''), 'id' => 'calendar-name', ], 'color' => [ 'label' => $this->cal->gettext('color'), 'value' => $input_color->show($this->calendar['color'] ?? ''), 'id' => 'calendar-color', ], ]; if (!empty($this->cal->driver->alarms)) { $checkbox = new html_checkbox(['name' => 'showalarms', 'id' => 'calendar-showalarms', 'value' => 1]); $formfields['showalarms'] = [ 'label' => $this->cal->gettext('showalarms'), 'value' => $checkbox->show(!empty($this->calendar['showalarms']) ? 1 : 0), 'id' => 'calendar-showalarms', ]; } // allow driver to extend or replace the form content return html::tag( 'form', $attrib + ['action' => '#', 'method' => 'get', 'id' => 'calendarpropform'], $this->cal->driver->calendar_form($this->action, $this->calendar, $formfields) ); } /** * Render HTML for attendees table */ public function attendees_list($attrib = []) { // add "noreply" checkbox to attendees table only $invitations = strpos($attrib['id'], 'attend') !== false; $invite = new html_checkbox(['value' => 1, 'id' => 'edit-attendees-invite']); $table = new html_table(['cols' => 5 + intval($invitations), 'border' => 0, 'cellpadding' => 0, 'class' => 'rectable']); $table->add_header('role', $this->cal->gettext('role')); $table->add_header('name', $this->cal->gettext(!empty($attrib['coltitle']) ? $attrib['coltitle'] : 'attendee')); $table->add_header('availability', $this->cal->gettext('availability')); $table->add_header('confirmstate', $this->cal->gettext('confirmstate')); if ($invitations) { $table->add_header( ['class' => 'invite', 'title' => $this->cal->gettext('sendinvitations')], $invite->show(1) . html::label('edit-attendees-invite', html::span('inner', $this->cal->gettext('sendinvitations'))) ); } $table->add_header('options', ''); // hide invite column if disabled by config $itip_notify = (int)$this->rc->config->get('calendar_itip_send_option', $this->cal->defaults['calendar_itip_send_option']); if ($invitations && !($itip_notify & 2)) { $css = sprintf('#%s td.invite, #%s th.invite { display:none !important }', $attrib['id'], $attrib['id']); $this->rc->output->add_footer(html::tag('style', ['type' => 'text/css'], $css)); } return $table->show($attrib); } /** * Render HTML for attendees adding form */ public function attendees_form($attrib = []) { $input = new html_inputfield([ 'name' => 'participant', 'id' => 'edit-attendee-name', 'class' => 'form-control', ]); $textarea = new html_textarea([ 'name' => 'comment', 'id' => 'edit-attendees-comment', 'class' => 'form-control', 'rows' => 4, 'cols' => 55, 'title' => $this->cal->gettext('itipcommenttitle'), ]); return html::div( $attrib, html::div( 'form-searchbar', $input->show() . ' ' . html::tag('input', [ 'type' => 'button', 'class' => 'button', 'id' => 'edit-attendee-add', 'value' => $this->cal->gettext('addattendee'), ]) . ' ' . html::tag('input', [ 'type' => 'button', 'class' => 'button', 'id' => 'edit-attendee-schedule', 'value' => $this->cal->gettext('scheduletime') . '...', ]) ) . html::p('attendees-commentbox', html::label('edit-attendees-comment', $this->cal->gettext('itipcomment')) . $textarea->show()) ); } /** * Render HTML for resources adding form */ public function resources_form($attrib = []) { $input = new html_inputfield(['name' => 'resource', 'id' => 'edit-resource-name', 'class' => 'form-control']); return html::div( $attrib, html::div( 'form-searchbar', $input->show() . ' ' . html::tag('input', [ 'type' => 'button', 'class' => 'button', 'id' => 'edit-resource-add', 'value' => $this->cal->gettext('addresource'), ]) . ' ' . html::tag('input', [ 'type' => 'button', 'class' => 'button', 'id' => 'edit-resource-find', 'value' => $this->cal->gettext('findresources') . '...', ]) ) ); } /** * Render HTML for resources list */ public function resources_list($attrib = []) { $attrib += ['id' => 'calendar-resources-list']; $this->rc->output->add_gui_object('resourceslist', $attrib['id']); return html::tag('ul', $attrib, '', html::$common_attrib); } /** * */ public function resource_info($attrib = []) { $attrib += ['id' => 'calendar-resources-info']; $this->rc->output->add_gui_object('resourceinfo', $attrib['id']); $this->rc->output->add_gui_object('resourceownerinfo', $attrib['id'] . '-owner'); // copy address book labels for owner details to client $this->rc->output->add_label('name', 'firstname', 'surname', 'department', 'jobtitle', 'email', 'phone', 'address'); $table_attrib = ['id','class','style','width','summary','cellpadding','cellspacing','border']; return html::tag('table', $attrib, html::tag('tbody', null, ''), $table_attrib) . html::tag( 'table', ['id' => $attrib['id'] . '-owner', 'style' => 'display:none'] + $attrib, html::tag( 'thead', null, html::tag( 'tr', null, html::tag('td', ['colspan' => 2], rcube::Q($this->cal->gettext('resourceowner'))) ) ) . html::tag('tbody', null, ''), $table_attrib ); } /** * */ public function resource_calendar($attrib = []) { $attrib += ['id' => 'calendar-resources-calendar']; $this->rc->output->add_gui_object('resourceinfocalendar', $attrib['id']); return html::div($attrib, ''); } /** * GUI object 'searchform' for the resource finder dialog * * @param array $attrib Named parameters * * @return string HTML code for the gui object */ public function resources_search_form($attrib) { $attrib += [ 'command' => 'search-resource', 'reset-command' => 'reset-resource-search', 'id' => 'rcmcalresqsearchbox', 'autocomplete' => 'off', 'form-name' => 'rcmcalresoursqsearchform', 'gui-object' => 'resourcesearchform', ]; // add form tag around text field return $this->rc->output->search_form($attrib); } /** * */ public function attendees_freebusy_table($attrib = []) { $table = new html_table(['cols' => 2, 'border' => 0, 'cellspacing' => 0]); $table->add( 'attendees', html::tag('h3', 'boxtitle', $this->cal->gettext('tabattendees')) . html::div('timesheader', ' ') . html::div(['id' => 'schedule-attendees-list', 'class' => 'attendees-list'], '') ); $table->add( 'times', html::div( 'scroll', html::tag( 'table', ['id' => 'schedule-freebusy-times', 'border' => 0, 'cellspacing' => 0], html::tag('thead') . html::tag('tbody') ) . html::div(['id' => 'schedule-event-time', 'style' => 'display:none'], ' ') ) ); return $table->show($attrib); } /** * */ public function event_invitebox($attrib = []) { if (!empty($this->cal->event)) { return html::div( $attrib, $this->cal->itip->itip_object_details_table($this->cal->event, $this->cal->itip->gettext('itipinvitation')) . $this->cal->invitestatus ); } return ''; } public function event_rsvp_buttons($attrib = []) { $actions = ['accepted', 'tentative', 'declined']; if (empty($attrib['delegate']) || $attrib['delegate'] !== 'false') { $actions[] = 'delegated'; } return $this->cal->itip->itip_rsvp_buttons($attrib, $actions); } } diff --git a/plugins/kolab_2fa/lib/Kolab2FA/Storage/LDAP.php b/plugins/kolab_2fa/lib/Kolab2FA/Storage/LDAP.php index dbc09ed9..36727f11 100644 --- a/plugins/kolab_2fa/lib/Kolab2FA/Storage/LDAP.php +++ b/plugins/kolab_2fa/lib/Kolab2FA/Storage/LDAP.php @@ -1,346 +1,345 @@ * * Copyright (C) 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 . */ namespace Kolab2FA\Storage; use Net_LDAP3; use Kolab2FA\Log\Logger; class LDAP extends Base { public $userdn; private $cache = []; private $ldapcache = []; private $conn; - private $error; private $ready = false; public function init(array $config) { parent::init($config); $this->conn = new Net_LDAP3($config); $this->conn->config_set('log_hook', [$this, 'log']); $this->conn->connect(); $bind_pass = $this->config['bind_pass']; $bind_user = $this->config['bind_user']; $bind_dn = $this->config['bind_dn']; $this->ready = $this->conn->bind($bind_dn, $bind_pass); if (!$this->ready) { - throw new Exception("LDAP storage not ready: " . $this->error); + throw new Exception("LDAP storage not ready"); } } /** * List/set methods activated for this user */ public function enumerate($active = true) { $filter = $this->parse_vars($this->config['filter'], '*'); $base_dn = $this->parse_vars($this->config['base_dn'], '*'); $scope = $this->config['scope'] ?: 'sub'; $ids = []; if ($this->ready && ($result = $this->conn->search($base_dn, $filter, $scope, [$this->config['fieldmap']['id'], $this->config['fieldmap']['active']]))) { foreach ($result as $dn => $entry) { $rec = $this->field_mapping($dn, Net_LDAP3::normalize_entry($entry, true)); if (!empty($rec['id']) && ($active === null || $active == $rec['active'])) { $ids[] = $rec['id']; } } } // TODO: cache this in memory return $ids; } /** * Read data for the given key */ public function read($key) { if (!isset($this->cache[$key])) { $this->cache[$key] = $this->get_ldap_record($this->username, $key); } return $this->cache[$key]; } /** * Save data for the given key */ public function write($key, $value) { $success = false; $ldap_attrs = []; if (is_array($value)) { // add some default values $value += (array)$this->config['defaults'] + ['active' => false, 'username' => $this->username, 'userdn' => $this->userdn]; foreach ($value as $k => $val) { if ($attr = $this->config['fieldmap'][$k]) { $ldap_attrs[$attr] = $this->value_mapping($k, $val, false); } } } else { // invalid data structure return false; } // update existing record if ($rec = $this->get_ldap_record($this->username, $key)) { $old_attrs = $rec['_raw']; $new_attrs = array_merge($old_attrs, $ldap_attrs); $result = $this->conn->modify_entry($rec['_dn'], $old_attrs, $new_attrs); $success = !empty($result); } // insert new record elseif ($this->ready) { $entry_dn = $this->get_entry_dn($this->username, $key); // add object class attribute $me = $this; $ldap_attrs['objectclass'] = array_map(function ($cls) use ($me, $key) { return $me->parse_vars($cls, $key); }, (array)$this->config['objectclass']); $success = $this->conn->add_entry($entry_dn, $ldap_attrs); } if ($success) { $this->cache[$key] = $value; $this->ldapcache = []; // cleanup: remove disabled/inactive/temporary entries if ($value['active']) { foreach ($this->enumerate(false) as $id) { if ($id != $key) { $this->remove($id); } } // set user roles according to active factors $this->set_user_roles(); } } return $success; } /** * Remove the data stored for the given key */ public function remove($key) { if ($this->ready) { $entry_dn = $this->get_entry_dn($this->username, $key); $success = $this->conn->delete_entry($entry_dn); // set user roles according to active factors if ($success) { $this->set_user_roles(); } return $success; } return false; } /** * Set username to store data for */ public function set_username($username) { parent::set_username($username); // reset cached values $this->cache = []; $this->ldapcache = []; } /** * */ protected function set_user_roles() { if (!$this->ready || !$this->userdn || empty($this->config['user_roles'])) { return false; } $auth_roles = []; foreach ($this->enumerate(true) as $id) { foreach ($this->config['user_roles'] as $prefix => $role) { if (strpos($id, $prefix) === 0) { $auth_roles[] = $role; } } } $role_attr = $this->config['fieldmap']['roles'] ?: 'nsroledn'; if ($user_attrs = $this->conn->get_entry($this->userdn, [$role_attr])) { $internals = array_values($this->config['user_roles']); $new_attrs = $old_attrs = Net_LDAP3::normalize_entry($user_attrs); $new_attrs[$role_attr] = array_merge( array_unique($auth_roles), array_filter((array)$old_attrs[$role_attr], function ($f) use ($internals) { return !in_array($f, $internals); }) ); $result = $this->conn->modify_entry($this->userdn, $old_attrs, $new_attrs); return !empty($result); } return false; } /** * Fetches user data from LDAP addressbook */ protected function get_ldap_record($user, $key) { $entry_dn = $this->get_entry_dn($user, $key); if (!isset($this->ldapcache[$entry_dn])) { $this->ldapcache[$entry_dn] = []; if ($this->ready && ($entry = $this->conn->get_entry($entry_dn, array_values($this->config['fieldmap'])))) { $this->ldapcache[$entry_dn] = $this->field_mapping($entry_dn, Net_LDAP3::normalize_entry($entry, true)); } } return $this->ldapcache[$entry_dn]; } /** * Compose a full DN for the given record identifier */ protected function get_entry_dn($user, $key) { $base_dn = $this->parse_vars($this->config['base_dn'], $key); return sprintf('%s=%s,%s', $this->config['rdn'], Net_LDAP3::quote_string($key, true), $base_dn); } /** * Maps LDAP attributes to defined fields */ protected function field_mapping($dn, $entry) { $entry['_dn'] = $dn; $entry['_raw'] = $entry; // fields mapping foreach ($this->config['fieldmap'] as $field => $attr) { $attr_lc = strtolower($attr); if (isset($entry[$attr_lc])) { $entry[$field] = $this->value_mapping($field, $entry[$attr_lc], true); } elseif (isset($entry[$attr])) { $entry[$field] = $this->value_mapping($field, $entry[$attr], true); } } return $entry; } /** * */ protected function value_mapping($attr, $value, $reverse = false) { if ($map = $this->config['valuemap'][$attr]) { if ($reverse) { $map = array_flip($map); } if (is_array($value)) { $value = array_filter(array_map(function ($val) use ($map) { return $map[$val]; }, $value)); } else { $value = $map[$value]; } } // convert (date) type switch ($this->config['attrtypes'][$attr]) { case 'datetime': $ts = is_numeric($value) ? $value : strtotime($value); if ($ts) { $value = gmdate($reverse ? 'U' : 'YmdHi\Z', $ts); } break; case 'integer': $value = intval($value); break; } return $value; } /** * Prepares filter query for LDAP search */ protected function parse_vars($str, $key) { $user = $this->username; if (strpos($user, '@') > 0) { [$u, $d] = explode('@', $user); } elseif ($this->userdn) { $u = $this->userdn; $d = trim(str_replace(',dc=', '.', substr($u, strpos($u, ',dc='))), '.'); } if ($this->userdn) { $user = $this->userdn; } // build hierarchal domain string $dc = isset($d) ? $this->conn->domain_root_dn($d) : ''; $class = $this->config['classmap'] ? $this->config['classmap']['*'] : '*'; // map key to objectclass if (is_array($this->config['classmap'])) { foreach ($this->config['classmap'] as $k => $c) { if (strpos($key, $k) === 0) { $class = $c; break; } } } $replaces = ['%dc' => $dc, '%d' => $d ?? '', '%fu' => $user, '%u' => $u ?? '', '%c' => $class]; return strtr($str, $replaces); } } diff --git a/plugins/kolab_addressbook/drivers/carddav/carddav_contacts.php b/plugins/kolab_addressbook/drivers/carddav/carddav_contacts.php index a2dbbad5..879ac859 100644 --- a/plugins/kolab_addressbook/drivers/carddav/carddav_contacts.php +++ b/plugins/kolab_addressbook/drivers/carddav/carddav_contacts.php @@ -1,1280 +1,1277 @@ * @author Aleksander Machniak * * Copyright (C) 2011-2022, 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 . * * @see rcube_addressbook */ class carddav_contacts extends rcube_addressbook { public $primary_key = 'ID'; public $rights = 'lrs'; public $readonly = true; public $undelete = false; public $groups = true; public $coltypes = [ 'name' => ['limit' => 1], 'firstname' => ['limit' => 1], 'surname' => ['limit' => 1], 'middlename' => ['limit' => 1], 'prefix' => ['limit' => 1], 'suffix' => ['limit' => 1], 'nickname' => ['limit' => 1], 'jobtitle' => ['limit' => 1], 'organization' => ['limit' => 1], 'department' => ['limit' => 1], 'email' => ['subtypes' => ['home','work','other']], 'phone' => [], 'address' => ['subtypes' => ['home','work','office']], 'website' => ['subtypes' => ['homepage','blog']], 'im' => ['subtypes' => null], 'gender' => ['limit' => 1], 'birthday' => ['limit' => 1], 'anniversary' => ['limit' => 1], 'manager' => ['limit' => null], 'assistant' => ['limit' => null], 'spouse' => ['limit' => 1], 'notes' => ['limit' => 1], 'photo' => ['limit' => 1], ]; public $vcard_map = [ // 'profession' => 'X-PROFESSION', // 'officelocation' => 'X-OFFICE-LOCATION', // 'initials' => 'X-INITIALS', // 'children' => 'X-CHILDREN', // 'freebusyurl' => 'X-FREEBUSY-URL', // 'pgppublickey' => 'KEY', 'uid' => 'UID', ]; /** * List of date type fields */ public $date_cols = ['birthday', 'anniversary']; public $fulltext_cols = ['name', 'firstname', 'surname', 'middlename', 'email']; private $gid; private $storage; private $dataset; private $sortindex; private $contacts; private $distlists; private $groupmembers; private $filter; private $result; private $namespace; - private $action; // list of fields used for searching in "All fields" mode private $search_fields = [ 'name', 'firstname', 'surname', 'middlename', 'prefix', 'suffix', 'nickname', 'jobtitle', 'organization', 'department', 'email', 'phone', 'address', // 'profession', 'manager', 'assistant', 'spouse', // 'children', 'notes', ]; /** * Object constructor */ public function __construct($dav_folder = null) { $this->storage = $dav_folder; $this->ready = !empty($this->storage); // Set readonly and rights flags according to folder permissions if ($this->ready) { if ($this->storage->get_owner() == $_SESSION['username']) { $this->readonly = false; $this->rights = 'lrswikxtea'; } else { $rights = $this->storage->get_myrights(); if ($rights && !PEAR::isError($rights)) { $this->rights = $rights; if (strpos($rights, 'i') !== false && strpos($rights, 't') !== false) { $this->readonly = false; } } } } - - $this->action = rcmail::get_instance()->action; } /** * Getter for the address book name to be displayed * * @return string Name of this address book */ public function get_name() { return $this->storage->get_name(); } /** * Wrapper for kolab_storage_folder::get_foldername() */ public function get_foldername() { return $this->storage->get_foldername(); } /** * Getter for the folder name * * @return string Name of the folder */ public function get_realname() { return $this->get_name(); } /** * Getter for the name of the namespace to which the IMAP folder belongs * * @return string Name of the namespace (personal, other, shared) */ public function get_namespace() { if ($this->namespace === null && $this->ready) { $this->namespace = $this->storage->get_namespace(); } return $this->namespace; } /** * Getter for parent folder path * * @return string Full path to parent folder */ public function get_parent() { return $this->storage->get_parent(); } /** * Check subscription status of this folder * * @return boolean True if subscribed, false if not */ public function is_subscribed() { return true; } /** * Compose an URL for CardDAV access to this address book (if configured) */ public function get_carddav_url() { /* $rcmail = rcmail::get_instance(); if ($template = $rcmail->config->get('kolab_addressbook_carddav_url', null)) { return strtr($template, [ '%h' => $_SERVER['HTTP_HOST'], '%u' => urlencode($rcmail->get_user_name()), '%i' => urlencode($this->storage->get_uid()), '%n' => urlencode($this->imap_folder), ]); } */ return false; } /** * Setter for the current group */ public function set_group($gid) { $this->gid = $gid; } /** * Save a search string for future listings * * @param mixed $filter Search params to use in listing method, obtained by get_search_set() */ public function set_search_set($filter): void { $this->filter = $filter; } /** * Getter for saved search properties * * @return mixed Search properties used by this class */ public function get_search_set() { return $this->filter; } /** * Reset saved results and search parameters */ public function reset(): void { $this->result = null; $this->filter = null; } /** * List all active contact groups of this source * * @param string $search Optional search string to match group name * @param int $mode Search mode. Sum of self::SEARCH_* * * @return array Indexed list of contact groups, each a hash array */ public function list_groups($search = null, $mode = 0) { $this->_fetch_groups(); $groups = []; foreach ((array)$this->distlists as $group) { if (!$search || strstr(mb_strtolower($group['name']), mb_strtolower($search))) { $groups[$group['ID']] = ['ID' => $group['ID'], 'name' => $group['name']]; } } // sort groups by name uasort($groups, function ($a, $b) { return strcoll($a['name'], $b['name']); }); return array_values($groups); } /** * List the current set of contact records * * @param array $cols List of cols to show * @param int $subset Only return this number of records, use negative values for tail * @param bool $nocount True to skip the count query (select only) * * @return rcube_result_set Indexed list of contact records, each a hash array */ public function list_records($cols = null, $subset = 0, $nocount = false) { $this->result = new rcube_result_set(0, ($this->list_page - 1) * $this->page_size); $fetch_all = false; $fast_mode = !empty($cols) && is_array($cols); // list member of the selected group if ($this->gid) { $this->_fetch_groups(); $this->sortindex = []; $this->contacts = []; $local_sortindex = []; $uids = []; // get members with email specified foreach ((array)$this->distlists[$this->gid]['member'] as $member) { // skip member that don't match the search filter if (!empty($this->filter['ids']) && array_search($member['ID'], $this->filter['ids']) === false) { continue; } if (!empty($member['uid'])) { $uids[] = $member['uid']; } elseif (!empty($member['email'])) { $this->contacts[$member['ID']] = $member; $local_sortindex[$member['ID']] = $this->_sort_string($member); $fetch_all = true; } } // get members by UID if (!empty($uids)) { $this->_fetch_contacts($query = [['uid', '=', $uids]], $fetch_all ? false : count($uids), $fast_mode); $this->sortindex = array_merge($this->sortindex, $local_sortindex); } } elseif (isset($this->filter['ids']) && is_array($this->filter['ids'])) { $ids = $this->filter['ids']; if (count($ids)) { $uids = array_map([$this, 'id2uid'], $this->filter['ids']); $this->_fetch_contacts($query = [['uid', '=', $uids]], count($ids), $fast_mode); } } else { $this->_fetch_contacts($query = 'contact', true, $fast_mode); } if ($fetch_all) { // sort results (index only) asort($this->sortindex, SORT_LOCALE_STRING); $ids = array_keys($this->sortindex); // fill contact data into the current result set $this->result->count = count($ids); $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first; $last_row = min($subset != 0 ? $start_row + abs($subset) : $this->result->first + $this->page_size, $this->result->count); for ($i = $start_row; $i < $last_row; $i++) { if (array_key_exists($i, $ids)) { $idx = $ids[$i]; $this->result->add($this->contacts[$idx] ?: $this->_to_rcube_contact($this->dataset[$idx])); } } } elseif (!empty($this->dataset)) { // get all records count, skip the query if possible if (!isset($query) || count($this->dataset) < $this->page_size) { $this->result->count = count($this->dataset) + $this->page_size * ($this->list_page - 1); } else { $this->result->count = $this->storage->count($query); } $start_row = $subset < 0 ? $this->page_size + $subset : 0; $last_row = min($subset != 0 ? $start_row + abs($subset) : $this->page_size, $this->result->count); for ($i = $start_row; $i < $last_row; $i++) { $this->result->add($this->_to_rcube_contact($this->dataset[$i])); } } return $this->result; } /** * Search records * * @param mixed $fields The field name of array of field names to search in * @param mixed $value Search value (or array of values when $fields is array) * @param int $mode Matching mode: * 0 - partial (*abc*), * 1 - strict (=), * 2 - prefix (abc*) * 4 - include groups (if supported) * @param bool $select True if results are requested, False if count only * @param bool $nocount True to skip the count query (select only) * @param array $required List of fields that cannot be empty * * @return rcube_result_set List of contact records and 'count' value */ public function search($fields, $value, $mode = 0, $select = true, $nocount = false, $required = []) { // search by ID if ($fields == $this->primary_key) { $ids = !is_array($value) ? explode(',', $value) : $value; $result = new rcube_result_set(); foreach ($ids as $id) { if ($rec = $this->get_record($id, true)) { $result->add($rec); $result->count++; } } return $result; } elseif ($fields == '*') { $fields = $this->search_fields; } if (!is_array($fields)) { $fields = [$fields]; } if (!is_array($required) && !empty($required)) { $required = [$required]; } // advanced search if (is_array($value)) { $advanced = true; $value = array_map('mb_strtolower', $value); } else { $value = mb_strtolower($value); } $scount = count($fields); // build key name regexp $regexp = '/^(' . implode('|', $fields) . ')(?:.*)$/'; // pass query to storage if only indexed cols are involved // NOTE: this is only some rough pre-filtering but probably includes false positives $squery = $this->_search_query($fields, $value, $mode); // add magic selector to select contacts with birthday dates only if (in_array('birthday', $required)) { $squery[] = ['tags', '=', 'x-has-birthday']; } $squery[] = ['type', '=', 'contact']; // get all/matching records $this->_fetch_contacts($squery); // save searching conditions $this->filter = ['fields' => $fields, 'value' => $value, 'mode' => $mode, 'ids' => []]; // search by iterating over all records in dataset foreach ($this->dataset as $record) { $contact = $this->_to_rcube_contact($record); $id = $contact['ID']; // check if current contact has required values, otherwise skip it if ($required) { foreach ($required as $f) { // required field might be 'email', but contact might contain 'email:home' $v = rcube_addressbook::get_col_values($f, $contact, true); if (count($v) === 0) { continue 2; } } } $found = []; $contents = ''; foreach (preg_grep($regexp, array_keys($contact)) as $col) { $pos = strpos($col, ':'); $colname = $pos ? substr($col, 0, $pos) : $col; foreach ((array)$contact[$col] as $val) { if (!empty($advanced)) { $found[$colname] = $this->compare_search_value($colname, $val, $value[array_search($colname, $fields)], $mode); } else { $contents .= ' ' . implode(' ', (array)$val); } } } // compare matches if ((!empty($advanced) && count($found) >= $scount) || (empty($advanced) && rcube_utils::words_match(mb_strtolower($contents), $value)) ) { $this->filter['ids'][] = $id; } } // dummy result with contacts count if (!$select) { return new rcube_result_set(count($this->filter['ids']), ($this->list_page - 1) * $this->page_size); } // list records (now limited by $this->filter) return $this->list_records(); } /** * Refresh saved search results after data has changed */ public function refresh_search() { if ($this->filter) { $this->search($this->filter['fields'], $this->filter['value'], $this->filter['mode']); } return $this->get_search_set(); } /** * Count number of available contacts in database * * @return rcube_result_set Result set with values for 'count' and 'first' */ public function count() { if ($this->gid) { $this->_fetch_groups(); $count = count($this->distlists[$this->gid]['member']); } elseif (isset($this->filter['ids']) && is_array($this->filter['ids'])) { $count = count($this->filter['ids']); } else { $count = $this->storage->count('contact'); } return new rcube_result_set($count, ($this->list_page - 1) * $this->page_size); } /** * Return the last result set * * @return ?rcube_result_set Current result set or NULL if nothing selected yet */ public function get_result() { return $this->result; } /** * Get a specific contact record * * @param mixed $id Record identifier(s) * @param bool $assoc True to return record as associative array, otherwise a result set is returned * * @return rcube_result_set|array|false Result object with all record fields or False if not found */ public function get_record($id, $assoc = false) { $rec = null; $uid = $this->id2uid($id); $rev = rcube_utils::get_input_value('_rev', rcube_utils::INPUT_GPC); if (strpos($uid, 'mailto:') === 0) { $this->_fetch_groups(true); $rec = $this->contacts[$id]; $this->readonly = true; // set source to read-only } /* else if (!empty($rev)) { $rcmail = rcube::get_instance(); $plugin = $rcmail->plugins->get_plugin('kolab_addressbook'); if ($plugin && ($object = $plugin->get_revision($id, kolab_storage::id_encode($this->imap_folder), $rev))) { $rec = $this->_to_rcube_contact($object); $rec['rev'] = $rev; } $this->readonly = true; // set source to read-only } */ elseif ($object = $this->storage->get_object($uid)) { $rec = $this->_to_rcube_contact($object); } if ($rec) { $this->result = new rcube_result_set(1); $this->result->add($rec); return $assoc ? $rec : $this->result; } return false; } /** * Get group assignments of a specific contact record * * @param mixed $id Record identifier * * @return array List of assigned groups as ID=>Name pairs */ public function get_record_groups($id) { $out = []; $this->_fetch_groups(); if (!empty($this->groupmembers[$id])) { foreach ((array) $this->groupmembers[$id] as $gid) { if (!empty($this->distlists[$gid])) { $group = $this->distlists[$gid]; $out[$gid] = $group['name']; } } } return $out; } /** * Create a new contact record * * @param array $save_data Associative array with save data * Keys: Field name with optional section in the form FIELD:SECTION * Values: Field value. Can be either a string or an array of strings for multiple values * @param bool $check True to check for duplicates first * * @return mixed The created record ID on success, False on error */ public function insert($save_data, $check = false) { if (!is_array($save_data)) { return false; } $insert_id = $existing = false; // check for existing records by e-mail comparison if ($check) { foreach ($this->get_col_values('email', $save_data, true) as $email) { if (($res = $this->search('email', $email, true, false)) && $res->count) { $existing = true; break; } } } if (!$existing) { // Unset contact ID (e.g. when copying/moving from another addressbook) unset($save_data['ID'], $save_data['uid'], $save_data['_type']); // generate new Kolab contact item $object = $this->_from_rcube_contact($save_data); $saved = $this->storage->save($object, 'contact'); if (!$saved) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving contact object to CardDAV server", ], true, false ); } else { $insert_id = $object['uid']; } } return $insert_id; } /** * Update a specific contact record * * @param mixed $id Record identifier * @param array $save_data Associative array with save data * Keys: Field name with optional section in the form FIELD:SECTION * Values: Field value. Can be either a string or an array of strings for multiple values * * @return bool True on success, False on error */ public function update($id, $save_data) { $updated = false; if ($old = $this->storage->get_object($this->id2uid($id))) { $object = $this->_from_rcube_contact($save_data, $old); if (!$this->storage->save($object, 'contact', $old['uid'])) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving contact object to CardDAV server", ], true, false ); } else { $updated = true; // TODO: update data in groups this contact is member of } } return $updated; } /** * Mark one or more contact records as deleted * * @param array $ids Record identifiers * @param bool $force Remove record(s) irreversible (mark as deleted otherwise) * * @return int Number of records deleted */ public function delete($ids, $force = true) { $this->_fetch_groups(); if (!is_array($ids)) { $ids = explode(',', $ids); } $count = 0; foreach ($ids as $id) { if ($uid = $this->id2uid($id)) { $is_mailto = strpos($uid, 'mailto:') === 0; $deleted = $is_mailto || $this->storage->delete($uid, $force); if (!$deleted) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error deleting a contact object $uid from the CardDAV server", ], true, false ); } else { // remove from distribution lists if (isset($this->groupmembers[$id])) { foreach ((array) $this->groupmembers[$id] as $gid) { if (!$is_mailto || $gid == $this->gid) { $this->remove_from_group($gid, $id); } } // clear internal cache unset($this->groupmembers[$id]); } $count++; } } } return $count; } /** * Undelete one or more contact records. * Only possible just after delete (see 2nd argument of delete() method). * * @param array $ids Record identifiers * * @return int Number of records restored */ public function undelete($ids) { if (!is_array($ids)) { $ids = explode(',', $ids); } $count = 0; foreach ($ids as $id) { $uid = $this->id2uid($id); if ($this->storage->undelete($uid)) { $count++; } else { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error undeleting a contact object $uid from the CardDav server", ], true, false ); } } return $count; } /** * Remove all records from the database * * @param bool $with_groups Remove also groups */ public function delete_all($with_groups = false) { if ($this->storage->delete_all()) { $this->contacts = []; $this->sortindex = []; $this->dataset = null; $this->result = null; } } /** * Close connection to source * Called on script shutdown */ public function close() { // NOP } /** * Create a contact group with the given name * * @param string $name The group name * * @return mixed False on error, array with record props in success */ public function create_group($name) { $this->_fetch_groups(); $rcube = rcube::get_instance(); $list = [ 'uid' => strtoupper(md5(time() . uniqid(rand())) . '-' . substr(md5($rcube->user->get_username()), 0, 16)), 'name' => $name, 'kind' => 'group', 'member' => [], ]; $saved = $this->storage->save($list, 'contact'); if (!$saved) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving a contact group to CardDAV server", ], true, false ); return false; } $id = $this->uid2id($list['uid']); $this->distlists[$id] = $list; return ['id' => $id, 'name' => $name]; } /** * Delete the given group and all linked group members * * @param string $gid Group identifier * * @return bool True on success, false if no data was changed */ public function delete_group($gid) { $this->_fetch_groups(); $list = $this->distlists[$gid]; if (!$list) { return false; } $deleted = $this->storage->delete($list['uid']); if (!$deleted) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error deleting a contact group from the CardDAV server", ], true, false ); } return $deleted; } /** * Rename a specific contact group * * @param string $gid Group identifier * @param string $newname New name to set for this group * @param string $newid New group identifier (if changed, otherwise don't set) * * @return string|false New name on success, false if no data was changed */ public function rename_group($gid, $newname, &$newid) { $this->_fetch_groups(); $list = $this->distlists[$gid]; if (!$list) { return false; } if ($newname === $list['name']) { return $newname; } $list['name'] = $newname; $saved = $this->storage->save($list, 'contact', $list['uid']); if (!$saved) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving a contact group to CardDAV server", ], true, false ); return false; } return $newname; } /** * Add the given contact records the a certain group * * @param string $gid Group identifier * @param array $ids List of contact identifiers to be added * * @return int Number of contacts added */ public function add_to_group($gid, $ids) { if (!is_array($ids)) { $ids = explode(',', $ids); } $this->_fetch_groups(true); $list = $this->distlists[$gid]; if (!$list) { return 0; } $added = 0; $uids = []; $exists = []; foreach ((array) $list['member'] as $member) { $exists[] = $member['ID']; } // substract existing assignments from list $ids = array_unique(array_diff($ids, $exists)); // add mailto: members foreach ($ids as $contact_id) { $uid = $this->id2uid($contact_id); if (strpos($uid, 'mailto:') === 0 && ($contact = $this->contacts[$contact_id])) { $list['member'][] = [ 'email' => $contact['email'], 'name' => $contact['name'], ]; $this->groupmembers[$contact_id][] = $gid; $added++; } else { $uids[$uid] = $contact_id; } } // add members with UID if (!empty($uids)) { foreach ($uids as $uid => $contact_id) { $list['member'][] = ['uid' => $uid]; $this->groupmembers[$contact_id][] = $gid; $added++; } } if ($added) { $saved = $this->storage->save($list, 'contact', $list['uid']); } else { $saved = true; } if (!$saved) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving a contact-group to CardDAV server", ], true, false ); $added = false; $this->set_error(self::ERROR_SAVING, 'errorsaving'); } else { $this->distlists[$gid] = $list; } return $added; } /** * Remove the given contact records from a certain group * * @param string $gid Group identifier * @param array $ids List of contact identifiers to be removed * * @return int Numer of removed contacts */ public function remove_from_group($gid, $ids) { $this->_fetch_groups(); $list = $this->distlists[$gid]; if (!$list) { return 0; } if (!is_array($ids)) { $ids = explode(',', $ids); } $new_member = []; $removed = 0; foreach ((array) $list['member'] as $member) { if (!in_array($member['ID'], $ids)) { $new_member[] = $member; } else { $removed++; } } // write distribution list back to server $list['member'] = $new_member; $saved = $this->storage->save($list, 'contact', $list['uid']); if (!$saved) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving a contact group to CardDAV server", ], true, false ); return 0; } // remove group assigments in local cache foreach ($ids as $id) { $j = array_search($gid, $this->groupmembers[$id]); unset($this->groupmembers[$id][$j]); } $this->distlists[$gid] = $list; return $removed; } /** * Check the given data before saving. * If input not valid, the message to display can be fetched using get_error() * * @param array $save_data Associative array with contact data to save * @param bool $autofix Attempt to fix/complete data automatically * * @return bool True if input is valid, False if not. */ public function validate(&$save_data, $autofix = false) { // validate e-mail addresses $valid = parent::validate($save_data); // require at least one e-mail address if there's no name // (syntax check is already done) if ($valid) { if (!strlen($save_data['name']) && !strlen($save_data['organization']) && !array_filter($this->get_col_values('email', $save_data, true)) ) { $this->set_error('warning', 'kolab_addressbook.noemailnamewarning'); $valid = false; } } return $valid; } /** * Query storage layer and store records in private member var */ private function _fetch_contacts($query = [], $limit = false, $fast_mode = false) { if (!isset($this->dataset) || !empty($query)) { if ($limit) { $size = is_int($limit) && $limit < $this->page_size ? $limit : $this->page_size; $this->storage->set_order_and_limit($this->_sort_columns(), $size, ($this->list_page - 1) * $this->page_size); } $this->sortindex = []; $this->dataset = $this->storage->select($query, $fast_mode); foreach ($this->dataset as $idx => $record) { $contact = $this->_to_rcube_contact($record); $this->sortindex[$idx] = $this->_sort_string($contact); } } } /** * Extract a string for sorting from the given contact record */ private function _sort_string($rec) { $str = ''; switch ($this->sort_col) { case 'name': $str = ($rec['name'] ?? '') . ($rec['prefix'] ?? ''); // no break case 'firstname': $str .= ($rec['firstname'] ?? '') . ($rec['middlename'] ?? '') . ($rec['surname'] ?? ''); break; case 'surname': $str = ($rec['surname'] ?? '') . ($rec['firstname'] ?? '') . ($rec['middlename'] ?? ''); break; default: $str = $rec[$this->sort_col] ?? ''; break; } if (!empty($rec['email'])) { $str .= is_array($rec['email']) ? $rec['email'][0] : $rec['email']; } return mb_strtolower($str); } /** * Return the cache table columns to order by */ private function _sort_columns() { $sortcols = []; switch ($this->sort_col) { case 'name': $sortcols[] = 'name'; // no break case 'firstname': $sortcols[] = 'firstname'; break; case 'surname': $sortcols[] = 'surname'; break; } $sortcols[] = 'email'; return $sortcols; } /** * Read contact groups from server */ private function _fetch_groups($with_contacts = false) { if (!isset($this->distlists)) { $this->distlists = $this->groupmembers = []; // Set order (and LIMIT to skip the count(*) select) $this->storage->set_order_and_limit(['name'], 200, 0); foreach ($this->storage->select('group', true) as $record) { $record['ID'] = $this->uid2id($record['uid']); foreach ((array)$record['member'] as $i => $member) { $mid = $this->uid2id($member['uid'] ? $member['uid'] : 'mailto:' . $member['email']); $record['member'][$i]['ID'] = $mid; $record['member'][$i]['readonly'] = empty($member['uid']); $this->groupmembers[$mid][] = $record['ID']; if ($with_contacts && empty($member['uid'])) { $this->contacts[$mid] = $record['member'][$i]; } } $this->distlists[$record['ID']] = $record; } $this->storage->set_order_and_limit($this->_sort_columns(), null, 0); } } /** * Encode object UID into a safe identifier */ public function uid2id($uid) { return rtrim(strtr(base64_encode($uid), '+/', '-_'), '='); } /** * Convert Roundcube object identifier back into the original UID */ public function id2uid($id) { return base64_decode(str_pad(strtr($id, '-_', '+/'), strlen($id) % 4, '=', STR_PAD_RIGHT)); } /** * Build SQL query for fulltext matches */ private function _search_query($fields, $value, $mode) { $query = []; $cols = []; $cols = array_intersect($fields, $this->fulltext_cols); if (count($cols)) { if ($mode & rcube_addressbook::SEARCH_STRICT) { $prefix = '^'; $suffix = '$'; } elseif ($mode & rcube_addressbook::SEARCH_PREFIX) { $prefix = '^'; $suffix = ''; } else { $prefix = ''; $suffix = ''; } $search_string = is_array($value) ? implode(' ', $value) : $value; foreach (rcube_utils::normalize_string($search_string, true) as $word) { $query[] = ['words', 'LIKE', $prefix . $word . $suffix]; } } return $query; } /** * Map fields from internal Kolab_Format to Roundcube contact format */ private function _to_rcube_contact($record) { $record['ID'] = $this->uid2id($record['uid']); // remove empty fields $record = array_filter($record); // Set _type for proper icon on the list $record['_type'] = 'person'; return $record; } /** * Map fields from Roundcube format to internal kolab_format_contact properties */ private function _from_rcube_contact($contact, $old = []) { if (empty($contact['uid']) && !empty($contact['ID'])) { $contact['uid'] = $this->id2uid($contact['ID']); } elseif (empty($contact['uid']) && !empty($old['uid'])) { $contact['uid'] = $old['uid']; } elseif (empty($contact['uid'])) { $rcube = rcube::get_instance(); $contact['uid'] = strtoupper(md5(time() . uniqid(rand())) . '-' . substr(md5($rcube->user->get_username()), 0, 16)); } // When importing contacts 'vcard' data might be added, we don't need it (Bug #1711) unset($contact['vcard']); return $contact; } } diff --git a/plugins/kolab_chat/drivers/mattermost.php b/plugins/kolab_chat/drivers/mattermost.php index 8bac1f1d..f1a2644b 100644 --- a/plugins/kolab_chat/drivers/mattermost.php +++ b/plugins/kolab_chat/drivers/mattermost.php @@ -1,354 +1,354 @@ * * Copyright (C) 2014-2018, 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_chat_mattermost { private $rc; private $plugin; private $token_valid = false; /** * Object constructor * * @param rcube_plugin $plugin Kolab_chat plugin object */ public function __construct($plugin) { $this->rc = rcube::get_instance(); $this->plugin = $plugin; } /** * Returns location of the chat app * * @param bool $websocket Return websocket URL * * @return string The chat app location */ public function url($websocket = false) { $url = rtrim($this->rc->config->get('kolab_chat_url'), '/'); if ($websocket) { $url = str_replace(['http://', 'https://'], ['ws://', 'wss://'], $url); $url .= '/api/v4/websocket'; } elseif ($this->rc->action == 'index' && $this->rc->task == 'kolab-chat') { $channel = rcube_utils::get_input_value('_channel', rcube_utils::INPUT_GET); if (empty($channel)) { $channel = $this->rc->config->get('kolab_chat_channel'); } if ($channel) { $team = rcube_utils::get_input_value('_team', rcube_utils::INPUT_GET); if (empty($team) && ($_channel = $this->get_channel($channel, true))) { $team = $_channel['team_name']; } - if ($channel && $team) { + if ($team) { $url .= '/' . urlencode($team) . '/channels/' . urlencode($channel); } } } return $url; } /** * Add/register UI elements */ public function ui() { if ($this->rc->task != 'kolab-chat') { $this->plugin->include_script("js/mattermost.js"); $this->plugin->add_label('openchat', 'directmessage', 'mentionmessage'); } elseif ($this->get_token()) { $this->setcookie('MMUSERID', $_SESSION['mattermost'][0]); $this->setcookie('MMAUTHTOKEN', $_SESSION['mattermost'][1]); } } /** * Driver specific actions handler */ public function action() { $result = [ 'url' => $this->url(true), 'token' => $this->get_token(), 'user_id' => $this->get_user_id(), ]; echo rcube_output::json_serialize($result); exit; } /** * Handler for preferences_list hook. * Adds options blocks into Chat settings sections in Preferences. * * @param array &$p Hook parameters */ public function preferences_list(&$p) { $no_override = array_flip((array) $this->rc->config->get('dont_override')); if (!isset($no_override['kolab_chat_channel'])) { $field_id = 'rcmfd_kolab_chat_channel'; $select = new html_select(['name' => '_kolab_chat_channel', 'id' => $field_id]); $select->add('---', ''); if ($channels = $this->get_channels_list()) { foreach ($channels as $channel) { if ($channel['name'] && $channel['display_name']) { $select->add($channel['display_name'], $channel['id']); } } } $p['blocks']['main']['options']['kolab_chat_channel'] = [ 'title' => html::label($field_id, rcube::Q($this->plugin->gettext('defaultchannel'))), 'content' => $select->show($this->rc->config->get('kolab_chat_channel')), ]; } } /** * Handler for preferences_save hook. * Executed on Chat settings form submit. * * @param array &$p Hook parameters */ public function preferences_save(&$p) { if (isset($_POST['_kolab_chat_channel'])) { $p['prefs']['kolab_chat_channel'] = rcube_utils::get_input_value('_kolab_chat_channel', rcube_utils::INPUT_POST); } } /** * Returns the Mattermost session token * Note: This works only if the user/pass is the same in Kolab and Mattermost * * @return string|null Session token */ protected function get_token() { $user = $_SESSION['username']; $pass = $this->rc->decrypt($_SESSION['password']); // Use existing token if still valid if (!empty($_SESSION['mattermost'])) { $user_id = $_SESSION['mattermost'][0]; $token = $_SESSION['mattermost'][1]; if ($this->token_valid) { return $token; } try { $request = $this->get_api_request('GET', '/users/me'); $request->setHeader('Authorization', "Bearer $token"); $response = $request->send(); $status = $response->getStatus(); if ($status != 200) { $token = null; } } catch (Exception $e) { rcube::raise_error($e, true, false); $token = null; } } // Request a new session token if (empty($token)) { $request = $this->get_api_request('POST', '/users/login'); $request->setBody(json_encode([ 'login_id' => $user, 'password' => $pass, ])); // send request to the API, get token and user ID try { $response = $request->send(); $status = $response->getStatus(); $token = $response->getHeader('Token'); $body = json_decode($response->getBody(), true); if ($status == 200) { $user_id = $body['id']; } elseif (is_array($body) && $body['message']) { throw new Exception($body['message']); } else { throw new Exception("Failed to authenticate the chat user ($user). Status: $status"); } } catch (Exception $e) { rcube::raise_error($e, true, false); } } if (!empty($user_id) && !empty($token)) { $this->token_valid = true; $_SESSION['mattermost'] = [$user_id, $token]; return $token; } return null; } /** * Returns the Mattermost user ID * Note: This works only if the user/pass is the same in Kolab and Mattermost * * @return string|null User ID */ protected function get_user_id() { if ($token = $this->get_token()) { return $_SESSION['mattermost'][0]; } return null; } /** * Returns the Mattermost channel info * * @param string $channel_id Channel ID * @param bool $extended Return extended information (i.e. team information) * * @return array Channel information */ protected function get_channel($channel_id, $extended = false) { $channel = $this->api_get('/channels/' . urlencode($channel_id)); if ($extended && is_array($channel)) { if (!empty($channel['team_id'])) { $team = $this->api_get('/teams/' . urlencode($channel['team_id'])); } elseif ($teams = $this->get_user_teams()) { // if there's no team assigned to the channel, we'll get the user's team // so we can build proper channel URL, there's no other way in the API $team = $teams[0]; } if (!empty($team)) { $channel['team_id'] = $team['id']; $channel['team_name'] = $team['name']; } } return $channel; } /** * Returns the Mattermost channels list for the user * * @return array|false Channels list (id, name, display_name, etc.) */ protected function get_channels_list() { // FIXME: Should we list only public channels here? // FIXME: SHould we check all user teams? $user_id = $this->get_user_id(); $teams = $this->get_user_teams(); if (!empty($teams) && ($team = $teams[0])) { // FIXME: Why it does return channels not assigned to the specified team? return $this->api_get(sprintf('/users/%s/teams/%s/channels', urlencode($user_id), urlencode($team['id']))); } return false; } /** * Returns the Mattermost teams of the user * * @return array List of teams */ protected function get_user_teams() { return $this->api_get('/users/' . urlencode($this->get_user_id()) . '/teams'); } /** * Return HTTP/Request2 instance for Mattermost API connection */ protected function get_api_request($type, $path) { $url = rtrim($this->rc->config->get('kolab_chat_url'), '/'); $defaults = [ 'store_body' => true, 'follow_redirects' => true, ]; $config = array_merge($defaults, (array) $this->rc->config->get('kolab_chat_http_request')); return libkolab::http_request($url . '/api/v4' . $path, $type, $config); } /** * Call API GET command */ protected function api_get($path) { if ($token = $this->get_token()) { try { $request = $this->get_api_request('GET', $path); $request->setHeader('Authorization', "Bearer $token"); $response = $request->send(); $status = $response->getStatus(); $body = $response->getBody(); if ($status == 200) { return json_decode($body, true); } } catch (Exception $e) { rcube::raise_error($e, true, false); } } } /** * Set mattermost session cookies */ protected function setcookie($name, $value) { if (headers_sent()) { return; } $cookie = session_get_cookie_params(); $secure = $cookie['secure'] || rcube_utils::https_check(); if ($domain = $this->rc->config->get('kolab_chat_session_domain')) { $cookie['domain'] = $domain; } setcookie($name, $value, 0, $cookie['path'], $cookie['domain'], $secure, false); } } diff --git a/plugins/kolab_files/kolab_files.php b/plugins/kolab_files/kolab_files.php index c8b32d54..a0edfa74 100644 --- a/plugins/kolab_files/kolab_files.php +++ b/plugins/kolab_files/kolab_files.php @@ -1,174 +1,174 @@ * * Copyright (C) 2013, 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_files extends rcube_plugin { // all task excluding 'login' and 'logout' public $task = '?(?!login|logout).*'; public $allowed_prefs = ['kolab_files_collapsed_folders']; public $rc; public $home; private $engine; public function init() { $this->rc = rcube::get_instance(); // Register hooks $this->add_hook('refresh', [$this, 'refresh']); // Plugin actions for other tasks $this->register_action('plugin.kolab_files', [$this, 'actions']); // Register task $this->register_task('files'); // Register plugin task actions $this->register_action('index', [$this, 'actions']); $this->register_action('prefs', [$this, 'actions']); $this->register_action('open', [$this, 'actions']); $this->register_action('edit', [$this, 'actions']); $this->register_action('share', [$this, 'actions']); $this->register_action('reset', [$this, 'actions']); $this->register_action('autocomplete', [$this, 'autocomplete']); // we use libkolab::http_request() from libkolab with its configuration $this->require_plugin('libkolab'); // Load UI from startup hook $this->add_hook('startup', [$this, 'startup']); $this->add_hook('preferences_save', [$this, 'preferences_save']); } /** * Creates kolab_files_engine instance */ private function engine() { if ($this->engine === null) { // the files module can be enabled/disabled by the kolab_auth plugin if ($this->rc->config->get('kolab_files_disabled') || !$this->rc->config->get('kolab_files_enabled', true)) { return $this->engine = false; } $this->load_config(); $client_url = $this->rc->config->get('kolab_files_url'); $server_url = $this->rc->config->get('kolab_files_server_url'); if (!$client_url) { return $this->engine = false; } require_once $this->home . '/lib/kolab_files_engine.php'; $this->engine = new kolab_files_engine($this, $client_url, $server_url); } return $this->engine; } /** * Startup hook handler, initializes/enables Files UI */ public function startup($args) { // call this from startup to give a chance to set // kolab_files_enabled/disabled in kolab_auth plugin $this->ui(); } /** * Adds elements of files API user interface */ private function ui() { if ($this->rc->output->type != 'html') { return; } if ($engine = $this->engine()) { $engine->ui(); } } /** * Refresh hook handler */ public function refresh($args) { // Here we are refreshing API session, so when we need it // the session will be active if ($engine = $this->engine()) { $this->rc->output->set_env('files_token', $engine->get_api_token()); } return $args; } /** * Engine actions handler */ public function actions() { if ($engine = $this->engine()) { $engine->actions(); } } /** * Handler for user autocomplete request */ public function autocomplete() { $this->load_config(); require_once $this->home . '/lib/kolab_files_autocomplete.php'; - new kolab_files_autocomplete($this); + new kolab_files_autocomplete(); } /** * Update chwala config on user preferences change */ public function preferences_save($props) { if ($props['section'] == 'general') { $dont_override = (array) $this->rc->config->get('dont_override'); $prefs = []; foreach (['timezone', 'date_long'] as $idx) { if (isset($props['prefs'][$idx]) && !in_array($idx, $dont_override)) { $prefs[$idx] = $props['prefs'][$idx]; } } if (!empty($prefs) && ($engine = $this->engine())) { $engine->configure(false, $prefs); } } } } diff --git a/plugins/kolab_files/lib/kolab_files_autocomplete.php b/plugins/kolab_files/lib/kolab_files_autocomplete.php index be60d514..55fbb032 100644 --- a/plugins/kolab_files/lib/kolab_files_autocomplete.php +++ b/plugins/kolab_files/lib/kolab_files_autocomplete.php @@ -1,170 +1,168 @@ * * 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 . */ class kolab_files_autocomplete { private $ldap; - private $plugin; private $rc; /** * Class constructor */ - public function __construct($plugin) + public function __construct() { - $this->plugin = $plugin; - $this->rc = rcmail::get_instance(); + $this->rc = rcmail::get_instance(); $search = rcube_utils::get_input_value('_search', rcube_utils::INPUT_GPC, true); $reqid = rcube_utils::get_input_value('_reqid', rcube_utils::INPUT_GPC); $users = []; $keys = []; if ($this->init_ldap()) { $max = (int) $this->rc->config->get('autocomplete_max', 15); $mode = (int) $this->rc->config->get('addressbook_search_mode'); $me = $this->rc->get_user_name(); $this->ldap->set_pagesize($max); $result = $this->ldap->search('*', $search, $mode); foreach ($result->records as $record) { $user = $record['uid']; if (is_array($user)) { $user = array_filter($user); $user = $user[0]; } if (in_array($me, rcube_addressbook::get_col_values('email', $record, true))) { continue; } if ($user) { $display = rcube_addressbook::compose_search_name($record); $user = ['name' => $user, 'display' => $display]; $users[] = $user; $keys[] = $display ?: $user['name']; } } /* if ($this->rc->config->get('kolab_files_groups')) { $prefix = $this->rc->config->get('kolab_files_group_prefix'); $group_field = $this->rc->config->get('kolab_files_group_field', 'name'); $result = $this->ldap->list_groups($search, $mode); foreach ($result as $record) { $group = $record['name']; $group_id = is_array($record[$group_field]) ? $record[$group_field][0] : $record[$group_field]; if ($group) { $users[] = array('name' => ($prefix ? $prefix : '') . $group_id, 'display' => $group, 'type' => 'group'); $keys[] = $group; } } } */ } if (count($users)) { // sort users index asort($keys, SORT_LOCALE_STRING); // re-sort users according to index foreach ($keys as $idx => $val) { $keys[$idx] = $users[$idx]; } $users = array_values($keys); } $this->rc->output->command('ksearch_query_results', $users, $search, $reqid); $this->rc->output->send(); } /** * Initializes autocomplete LDAP backend */ private function init_ldap() { if ($this->ldap) { return $this->ldap->ready; } // get LDAP config $config = $this->rc->config->get('kolab_files_users_source'); if (empty($config)) { return false; } // not an array, use configured ldap_public source if (!is_array($config)) { $ldap_config = (array) $this->rc->config->get('ldap_public'); $config = $ldap_config[$config]; } $uid_field = $this->rc->config->get('kolab_files_users_field', 'mail'); $filter = $this->rc->config->get('kolab_files_users_filter'); $debug = $this->rc->config->get('ldap_debug'); $domain = $this->rc->config->mail_domain($_SESSION['imap_host']); if (empty($uid_field) || empty($config)) { return false; } // get name attribute if (!empty($config['fieldmap'])) { $name_field = $config['fieldmap']['name']; } // ... no fieldmap, use the old method if (empty($name_field)) { $name_field = $config['name_field']; } // add UID field to fieldmap, so it will be returned in a record with name $config['fieldmap']['name'] = $name_field; $config['fieldmap']['uid'] = $uid_field; // search in UID and name fields // $name_field can be in a form of : (#1490591) $name_field = preg_replace('/:.*$/', '', $name_field); $search = array_unique([$name_field, $uid_field]); $config['search_fields'] = $search; $config['required_fields'] = [$uid_field]; // set search filter if ($filter) { $config['filter'] = $filter; } // disable vlv $config['vlv'] = false; // Initialize LDAP connection $this->ldap = new rcube_ldap($config, $debug, $domain); return $this->ldap->ready; } } diff --git a/plugins/kolab_folders/kolab_folders.php b/plugins/kolab_folders/kolab_folders.php index a79e9ee8..0a8ce533 100644 --- a/plugins/kolab_folders/kolab_folders.php +++ b/plugins/kolab_folders/kolab_folders.php @@ -1,854 +1,854 @@ * * Copyright (C) 2011-2017, 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_folders extends rcube_plugin { public $task = '?(?!login).*'; public $types = ['mail', 'event', 'journal', 'task', 'note', 'contact', 'configuration', 'file', 'freebusy']; public $subtypes = [ 'mail' => ['inbox', 'drafts', 'sentitems', 'outbox', 'wastebasket', 'junkemail'], 'event' => ['default'], 'task' => ['default'], 'journal' => ['default'], 'note' => ['default'], 'contact' => ['default'], 'configuration' => ['default'], 'file' => ['default'], 'freebusy' => ['default'], ]; public $act_types = ['event', 'task']; private $rc; private static $instance; private $expire_annotation = '/shared/vendor/cmu/cyrus-imapd/expire'; private $is_processing = false; /** * Plugin initialization. */ public function init() { self::$instance = $this; $this->rc = rcube::get_instance(); // load required plugin $this->require_plugin('libkolab'); // Folder listing hooks $this->add_hook('storage_folders', [$this, 'mailboxes_list']); // Folder manager hooks $this->add_hook('folder_form', [$this, 'folder_form']); $this->add_hook('folder_update', [$this, 'folder_save']); $this->add_hook('folder_create', [$this, 'folder_save']); $this->add_hook('folder_delete', [$this, 'folder_save']); $this->add_hook('folder_rename', [$this, 'folder_save']); $this->add_hook('folders_list', [$this, 'folders_list']); // Special folders setting $this->add_hook('preferences_save', [$this, 'prefs_save']); // ACL plugin hooks $this->add_hook('acl_rights_simple', [$this, 'acl_rights_simple']); $this->add_hook('acl_rights_supported', [$this, 'acl_rights_supported']); // Resolving other user folder names $this->add_hook('render_mailboxlist', [$this, 'render_folderlist']); $this->add_hook('render_folder_selector', [$this, 'render_folderlist']); $this->add_hook('folders_list', [$this, 'render_folderlist']); } /** * Handler for mailboxes_list hook. Enables type-aware lists filtering. */ public function mailboxes_list($args) { // infinite loop prevention if ($this->is_processing) { return $args; } if (!$this->metadata_support()) { return $args; } $this->is_processing = true; // get folders $folders = kolab_storage::list_folders($args['root'], $args['name'], $args['filter'], $args['mode'] == 'LSUB', $folderdata); $this->is_processing = false; if (!is_array($folders)) { return $args; } // Create default folders - if ($args['root'] == '' && $args['name'] = '*') { + if ($args['root'] == '' && $args['name'] == '*') { $this->create_default_folders($folders, $args['filter'], $folderdata, $args['mode'] == 'LSUB'); } $args['folders'] = $folders; return $args; } /** * Handler for folders_list hook. Add css classes to folder rows. */ public function folders_list($args) { if (!$this->metadata_support()) { return $args; } // load translations $this->add_texts('localization/', false); // Add javascript script to the client $this->include_script('kolab_folders.js'); $this->add_label('folderctype'); foreach ($this->types as $type) { $this->add_label('foldertype' . $type); } $skip_namespace = $this->rc->config->get('kolab_skip_namespace'); $skip_roots = []; if (!empty($skip_namespace)) { $storage = $this->rc->get_storage(); foreach ((array)$skip_namespace as $ns) { foreach((array)$storage->get_namespace($ns) as $root) { $skip_roots[] = rtrim($root[0], $root[1]); } } } $this->rc->output->set_env('skip_roots', $skip_roots); $this->rc->output->set_env('foldertypes', $this->types); // get folders types $folderdata = kolab_storage::folders_typedata(); if (!is_array($folderdata)) { return $args; } // Add type-based style for table rows // See kolab_folders::folder_class_name() if (!empty($args['table'])) { $table = $args['table']; for ($i = 1, $cnt = $table->size(); $i <= $cnt; $i++) { $attrib = $table->get_row_attribs($i); $folder = $attrib['foldername']; // UTF7-IMAP $type = $folderdata[$folder]; if (!$type) { $type = 'mail'; } $class_name = self::folder_class_name($type); $attrib['class'] = trim($attrib['class'] . ' ' . $class_name); $table->set_row_attribs($attrib, $i); } } // Add type-based class for list items if (!empty($args['list']) && is_array($args['list'])) { foreach ($args['list'] as $k => $item) { $folder = $item['folder_imap']; // UTF7-IMAP $type = $folderdata[$folder] ?? null; if (!$type) { $type = 'mail'; } $class_name = self::folder_class_name($type); $args['list'][$k]['class'] = trim($item['class'] . ' ' . $class_name); } } return $args; } /** * Handler for folder info/edit form (folder_form hook). * Adds folder type selector. */ public function folder_form($args) { if (!$this->metadata_support()) { return $args; } // load translations $this->add_texts('localization/', false); // INBOX folder is of type mail.inbox and this cannot be changed if ($args['name'] == 'INBOX') { $args['form']['props']['fieldsets']['settings']['content']['foldertype'] = [ 'label' => $this->gettext('folderctype'), 'value' => sprintf('%s (%s)', $this->gettext('foldertypemail'), $this->gettext('inbox')), ]; $this->add_expire_input($args['form'], 'INBOX'); return $args; } if (!empty($args['options']['is_root'])) { return $args; } $mbox = strlen($args['name']) ? $args['name'] : $args['parent_name']; if (isset($_POST['_ctype'])) { $new_ctype = trim(rcube_utils::get_input_value('_ctype', rcube_utils::INPUT_POST)); $new_subtype = trim(rcube_utils::get_input_value('_subtype', rcube_utils::INPUT_POST)); } // Get type of the folder or the parent $subtype = ''; if (strlen($mbox)) { [$ctype, $subtype] = $this->get_folder_type($mbox); if (isset($args['parent_name']) && strlen($args['parent_name']) && $subtype == 'default') { $subtype = ''; // there can be only one } } if (empty($ctype)) { $ctype = 'mail'; } $storage = $this->rc->get_storage(); // Don't allow changing type of shared folder, according to ACL if (strlen($mbox)) { $options = $storage->folder_info($mbox); if ($options['namespace'] != 'personal' && !in_array('a', (array)$options['rights'])) { if (in_array($ctype, $this->types)) { $value = $this->gettext('foldertype' . $ctype); } else { $value = $ctype; } if ($subtype) { $value .= ' (' . ($subtype == 'default' ? $this->gettext('default') : $subtype) . ')'; } $args['form']['props']['fieldsets']['settings']['content']['foldertype'] = [ 'label' => $this->gettext('folderctype'), 'value' => $value, ]; return $args; } } // Add javascript script to the client $this->include_script('kolab_folders.js'); // build type SELECT fields $type_select = new html_select(['name' => '_ctype', 'id' => '_folderctype', 'onchange' => "\$('[name=\"_expire\"]').attr('disabled', \$(this).val() != 'mail')", ]); $sub_select = new html_select(['name' => '_subtype', 'id' => '_subtype']); $sub_select->add('', ''); foreach ($this->types as $type) { $type_select->add($this->gettext('foldertype' . $type), $type); } // add non-supported type if (!in_array($ctype, $this->types)) { $type_select->add($ctype, $ctype); } $sub_types = []; foreach ($this->subtypes as $ftype => $subtypes) { $sub_types[$ftype] = array_combine($subtypes, array_map([$this, 'gettext'], $subtypes)); // fill options for the current folder type if ($ftype == $ctype || (isset($new_ctype) && $ftype == $new_ctype)) { $sub_select->add(array_values($sub_types[$ftype]), $subtypes); } } $args['form']['props']['fieldsets']['settings']['content']['folderctype'] = [ 'label' => $this->gettext('folderctype'), 'value' => html::div( 'input-group', $type_select->show($new_ctype ?? $ctype) . $sub_select->show($new_subtype ?? $subtype) ), ]; $this->rc->output->set_env('kolab_folder_subtypes', $sub_types); $this->rc->output->set_env('kolab_folder_subtype', $new_subtype ?? $subtype); $this->add_expire_input($args['form'], $args['name'], $ctype); return $args; } /** * Handler for folder update/create action (folder_update/folder_create hook). */ public function folder_save($args) { // Folder actions from folders list if (empty($args['record'])) { return $args; } // Folder create/update with form $ctype = trim(rcube_utils::get_input_value('_ctype', rcube_utils::INPUT_POST)); $subtype = trim(rcube_utils::get_input_value('_subtype', rcube_utils::INPUT_POST)); $mbox = $args['record']['name']; $old_mbox = $args['record']['oldname'] ?? null; $subscribe = $args['record']['subscribe'] ?? true; if (empty($ctype)) { return $args; } // load translations $this->add_texts('localization/', false); // Skip folder creation/rename in core // @TODO: Maybe we should provide folder_create_after and folder_update_after hooks? // Using create_mailbox/rename_mailbox here looks bad $args['abort'] = true; // There can be only one default folder of specified type if ($subtype == 'default') { $default = $this->get_default_folder($ctype); if ($default !== null && $old_mbox != $default) { $args['result'] = false; $args['message'] = $this->gettext('defaultfolderexists'); return $args; } } // Subtype sanity-checks elseif ($subtype && (!($subtypes = $this->subtypes[$ctype]) || !in_array($subtype, $subtypes))) { $subtype = ''; } $ctype .= $subtype ? '.' . $subtype : ''; $storage = $this->rc->get_storage(); // Create folder if (!strlen($old_mbox)) { $result = $storage->create_folder($mbox, $subscribe); // Set folder type if ($result) { $this->set_folder_type($mbox, $ctype); } } // Rename folder else { if ($old_mbox != $mbox) { $result = $storage->rename_folder($old_mbox, $mbox); } else { $result = true; } if ($result) { [$oldtype, $oldsubtype] = $this->get_folder_type($mbox); $oldtype .= $oldsubtype ? '.' . $oldsubtype : ''; if ($ctype != $oldtype) { $this->set_folder_type($mbox, $ctype); } } } // Set messages expiration in days if ($result && isset($_POST['_expire'])) { $expire = trim(rcube_utils::get_input_value('_expire', rcube_utils::INPUT_POST)); $expire = intval($expire) && preg_match('/^mail/', $ctype) ? intval($expire) : null; $storage->set_metadata($mbox, [$this->expire_annotation => $expire]); } $args['record']['class'] = self::folder_class_name($ctype); $args['record']['subscribe'] = $subscribe; $args['result'] = $result; return $args; } /** * Handler for user preferences save (preferences_save hook) * * @param array $args Hash array with hook parameters * * @return array Hash array with modified hook parameters */ public function prefs_save($args) { if ($args['section'] != 'folders') { return $args; } $dont_override = (array) $this->rc->config->get('dont_override', []); // map config option name to kolab folder type annotation $opts = [ 'drafts_mbox' => 'mail.drafts', 'sent_mbox' => 'mail.sentitems', 'junk_mbox' => 'mail.junkemail', 'trash_mbox' => 'mail.wastebasket', ]; // check if any of special folders has been changed foreach ($opts as $opt_name => $type) { $new = $args['prefs'][$opt_name]; $old = $this->rc->config->get($opt_name); if (!strlen($new) || $new === $old || in_array($opt_name, $dont_override)) { unset($opts[$opt_name]); } } if (empty($opts)) { return $args; } $folderdata = kolab_storage::folders_typedata(); if (!is_array($folderdata)) { return $args; } foreach ($opts as $opt_name => $type) { $foldername = $args['prefs'][$opt_name]; // get all folders of specified type $folders = array_intersect($folderdata, [$type]); // folder already annotated with specified type if (!empty($folders[$foldername])) { continue; } // set type to the new folder $this->set_folder_type($foldername, $type); // unset old folder(s) type annotation [$maintype, $subtype] = explode('.', $type); foreach (array_keys($folders) as $folder) { $this->set_folder_type($folder, $maintype); } } return $args; } /** * Handler for ACL permissions listing (acl_rights_simple hook) * * This shall combine the write and delete permissions into one item for * groupware folders as updating groupware objects is an insert + delete operation. * * @param array $args Hash array with hook parameters * * @return array Hash array with modified hook parameters */ public function acl_rights_simple($args) { if ($args['folder']) { [$type, ] = $this->get_folder_type($args['folder']); // we're dealing with a groupware folder here... if ($type && $type !== 'mail') { if ($args['rights']['write'] && $args['rights']['delete']) { $write_perms = $args['rights']['write'] . $args['rights']['delete']; $rw_perms = $write_perms . $args['rights']['read']; $args['rights']['write'] = $write_perms; $args['rights']['other'] = preg_replace("/[$rw_perms]/", '', $args['rights']['other']); // add localized labels and titles for the altered items $args['labels'] = [ 'other' => $this->rc->gettext('shortacla', 'acl'), ]; $args['titles'] = [ 'other' => $this->rc->gettext('longaclother', 'acl'), ]; } } } return $args; } /** * Handler for ACL permissions listing (acl_rights_supported hook) * * @param array $args Hash array with hook parameters * * @return array Hash array with modified hook parameters */ public function acl_rights_supported($args) { if ($args['folder']) { [$type, ] = $this->get_folder_type($args['folder']); // we're dealing with a groupware folder here... if ($type && $type !== 'mail') { // remove some irrelevant (for groupware objects) rights $args['rights'] = str_split(preg_replace('/[p]/', '', implode('', $args['rights']))); } } return $args; } /** * Checks if IMAP server supports any of METADATA, ANNOTATEMORE, ANNOTATEMORE2 * * @return bool */ public function metadata_support() { $storage = $this->rc->get_storage(); return $storage->get_capability('METADATA') || $storage->get_capability('ANNOTATEMORE') || $storage->get_capability('ANNOTATEMORE2'); } /** * Checks if IMAP server supports any of METADATA, ANNOTATEMORE, ANNOTATEMORE2 * * @param string $folder Folder name * * @return array Folder content-type */ public function get_folder_type($folder) { $type = explode('.', (string)kolab_storage::folder_type($folder)); if (!isset($type[1])) { $type[1] = null; } return $type; } /** * Sets folder content-type. * * @param string $folder Folder name * @param string $type Content type * * @return bool True on success */ public function set_folder_type($folder, $type = 'mail') { return kolab_storage::set_folder_type($folder, $type); } /** * Returns the name of default folder * * @param string $type Folder type * * @return ?string Folder name */ public function get_default_folder($type) { $folderdata = kolab_storage::folders_typedata(); if (!is_array($folderdata)) { return null; } // get all folders of specified type $folderdata = array_intersect($folderdata, [$type . '.default']); return key($folderdata); } /** * Returns CSS class name for specified folder type * * @param string $type Folder type * * @return string Class name */ public static function folder_class_name($type) { if ($type && strpos($type, '.')) { [$ctype, $subtype] = explode('.', $type); return 'type-' . $ctype . ' subtype-' . $subtype; } return 'type-' . ($type ? $type : 'mail'); } /** * Creates default folders if they doesn't exist */ private function create_default_folders(&$folders, $filter, $folderdata = null, $lsub = false) { $storage = $this->rc->get_storage(); $namespace = $storage->get_namespace(); $defaults = []; $prefix = ''; // Find personal namespace prefix if (is_array($namespace['personal']) && count($namespace['personal']) == 1) { $prefix = $namespace['personal'][0][0]; } $this->load_config(); // get configured defaults foreach ($this->types as $type) { foreach ((array)$this->subtypes[$type] as $subtype) { $opt_name = 'kolab_folders_' . $type . '_' . $subtype; if ($folder = $this->rc->config->get($opt_name)) { // convert configuration value to UTF7-IMAP charset $folder = rcube_charset::convert($folder, RCUBE_CHARSET, 'UTF7-IMAP'); // and namespace prefix if needed if ($prefix && strpos($folder, $prefix) === false && $folder != 'INBOX') { $folder = $prefix . $folder; } $defaults[$type . '.' . $subtype] = $folder; } } } if (empty($defaults)) { return; } if ($folderdata === null) { $folderdata = kolab_storage::folders_typedata(); } if (!is_array($folderdata)) { return; } // find default folders foreach ($defaults as $type => $foldername) { // get all folders of specified type $_folders = array_intersect($folderdata, [$type]); // default folder found if (!empty($_folders)) { continue; } [$type1, $type2] = explode('.', $type); $activate = in_array($type1, $this->act_types); $exists = false; $result = false; $subscribed = false; // check if folder exists if (!empty($folderdata[$foldername]) || $foldername == 'INBOX') { $exists = true; } elseif ((!$filter || $filter == $type1) && in_array($foldername, $folders)) { // this assumes also that subscribed folder exists $exists = true; } else { $exists = $storage->folder_exists($foldername); } // create folder if (!$exists) { $exists = $storage->create_folder($foldername); } // set type + subscribe + activate if ($exists) { if ($result = kolab_storage::set_folder_type($foldername, $type)) { // check if folder is subscribed if ((!$filter || $filter == $type1) && $lsub && in_array($foldername, $folders)) { // already subscribed $subscribed = true; } else { $subscribed = $storage->subscribe($foldername); } // activate folder if ($activate) { kolab_storage::folder_activate($foldername); } } } // add new folder to the result if ($result && (!$filter || $filter == $type1) && (!$lsub || $subscribed)) { $folders[] = $foldername; } } } /** * Static getter for default folder of the given type * * @param string $type Folder type * * @return string Folder name */ public static function default_folder($type) { return self::$instance->get_default_folder($type); } /** * Get /shared/vendor/cmu/cyrus-imapd/expire value * * @param string $folder IMAP folder name * * @return int|false The annotation value or False if not supported */ private function get_expire_annotation($folder) { $storage = $this->rc->get_storage(); if ($storage->get_vendor() != 'cyrus') { return false; } if (!strlen($folder)) { return 0; } $value = $storage->get_metadata($folder, $this->expire_annotation); if (is_array($value)) { return !empty($value[$folder]) ? intval($value[$folder][$this->expire_annotation] ?? 0) : 0; } return false; } /** * Add expiration time input to the form if supported */ private function add_expire_input(&$form, $folder, $type = null) { if (($expire = $this->get_expire_annotation($folder)) !== false) { $post = trim(rcube_utils::get_input_value('_expire', rcube_utils::INPUT_POST)); $is_mail = empty($type) || preg_match('/^mail/i', $type); $label = $this->gettext('xdays'); $input = new html_inputfield([ 'id' => '_kolabexpire', 'name' => '_expire', 'size' => 3, 'disabled' => !$is_mail, ]); if ($post && $is_mail) { $expire = (int) $post; } if (strpos($label, '$') === 0) { $label = str_replace('$x', '', $label); $html = $input->show($expire ?: '') . html::span('input-group-append', html::span('input-group-text', rcube::Q($label))); } else { $label = str_replace('$x', '', $label); $html = html::span('input-group-prepend', html::span('input-group-text', rcube::Q($label))) . $input->show($expire ?: ''); } $form['props']['fieldsets']['settings']['content']['kolabexpire'] = [ 'label' => $this->gettext('folderexpire'), 'value' => html::div('input-group', $html), ]; } } /** * Handler for various folders list widgets (hooks) * * @param array $args Hash array with hook parameters * * @return array Hash array with modified hook parameters */ public function render_folderlist($args) { $storage = $this->rc->get_storage(); $ns_other = $storage->get_namespace('other'); $is_fl = $this->rc->plugins->is_processing('folders_list'); foreach ((array) $ns_other as $root) { $delim = $root[1]; $prefix = rtrim($root[0], $delim); $length = strlen($prefix); if (!$length) { continue; } // folders_list hook mode if ($is_fl) { foreach ((array) $args['list'] as $folder_name => $folder) { if (strpos($folder_name, $root[0]) === 0 && !substr_count($folder_name, $root[1], $length + 1)) { if ($name = kolab_storage::folder_id2user(substr($folder_name, $length + 1), true)) { $old = $args['list'][$folder_name]['display']; $content = $args['list'][$folder_name]['content']; $name = rcube::Q($name); $content = str_replace(">$old<", ">$name<", $content); $args['list'][$folder_name]['display'] = $name; $args['list'][$folder_name]['content'] = $content; } } } // TODO: Re-sort the list } // render_* hooks mode elseif (!empty($args['list'][$prefix]) && !empty($args['list'][$prefix]['folders'])) { $map = []; foreach ($args['list'][$prefix]['folders'] as $folder_name => $folder) { if ($name = kolab_storage::folder_id2user($folder_name, true)) { $args['list'][$prefix]['folders'][$folder_name]['name'] = $name; } $map[$folder_name] = $name ?: $args['list'][$prefix]['folders'][$folder_name]['name']; } // Re-sort the list uasort($map, 'strcoll'); $args['list'][$prefix]['folders'] = array_replace($map, $args['list'][$prefix]['folders']); } } return $args; } } diff --git a/plugins/kolab_notes/kolab_notes.php b/plugins/kolab_notes/kolab_notes.php index 3285bc56..9ebaa977 100644 --- a/plugins/kolab_notes/kolab_notes.php +++ b/plugins/kolab_notes/kolab_notes.php @@ -1,1497 +1,1497 @@ * * 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 kolab_notes extends rcube_plugin { public $task = '?(?!login|logout).*'; public $allowed_prefs = ['kolab_notes_sort_col']; public $rc; private $ui; private $lists; private $folders; private $cache = []; private $message_notes = []; private $note; private $bonnie_api = false; private $search_more_results = false; /** * Required startup method of a Roundcube plugin */ public function init() { $this->require_plugin('libkolab'); $this->rc = rcube::get_instance(); // proceed initialization in startup hook $this->add_hook('startup', [$this, 'startup']); } /** * Startup hook */ public function startup($args) { // the notes module can be enabled/disabled by the kolab_auth plugin if ($this->rc->config->get('kolab_notes_disabled', false) || !$this->rc->config->get('kolab_notes_enabled', true)) { return; } $this->register_task('notes'); // load plugin configuration $this->load_config(); // load localizations $this->add_texts('localization/', $args['task'] == 'notes' && (!$args['action'] || $args['action'] == 'dialog-ui')); $this->rc->load_language($_SESSION['language'], ['notes.notes' => $this->gettext('navtitle')]); // add label for task title if ($args['task'] == 'notes') { $this->add_hook('storage_init', [$this, 'storage_init']); // register task actions $this->register_action('index', [$this, 'notes_view']); $this->register_action('fetch', [$this, 'notes_fetch']); $this->register_action('get', [$this, 'note_record']); $this->register_action('action', [$this, 'note_action']); $this->register_action('list', [$this, 'list_action']); $this->register_action('dialog-ui', [$this, 'dialog_view']); $this->register_action('print', [$this, 'print_note']); if (!$this->rc->output->ajax_call && in_array($args['action'], ['dialog-ui', 'list'])) { $this->load_ui(); } } elseif ($args['task'] == 'mail') { $this->add_hook('storage_init', [$this, 'storage_init']); $this->add_hook('message_compose', [$this, 'mail_message_compose']); if (in_array($args['action'], ['show', 'preview', 'print'])) { $this->add_hook('message_load', [$this, 'mail_message_load']); $this->add_hook('template_object_messagebody', [$this, 'mail_messagebody_html']); } // add 'Append note' item to message menu if ($this->api->output->type == 'html' && ($_REQUEST['_rel'] ?? null) != 'note') { $this->api->add_content( html::tag( 'li', ['role' => 'menuitem'], $this->api->output->button([ 'command' => 'append-kolab-note', 'label' => 'kolab_notes.appendnote', 'type' => 'link', 'classact' => 'icon appendnote active', 'class' => 'icon appendnote disabled', 'innerclass' => 'icon note', ]) ), 'messagemenu' ); $this->api->output->add_label('kolab_notes.appendnote', 'kolab_notes.editnote', 'kolab_notes.deletenotesconfirm', 'kolab_notes.entertitle', 'save', 'delete', 'cancel', 'close'); $this->include_script('notes_mail.js'); } } if (!$this->rc->output->ajax_call && empty($this->rc->output->env['framed'])) { $this->load_ui(); } // get configuration for the Bonnie API $this->bonnie_api = libkolab::get_bonnie_api(); // notes use fully encoded identifiers kolab_storage::$encode_ids = true; } /** * Hook into IMAP FETCH HEADER.FIELDS command and request MESSAGE-ID */ public function storage_init($p) { $p['fetch_headers'] = trim($p['fetch_headers'] . ' MESSAGE-ID'); return $p; } /** * Load and initialize UI class */ private function load_ui() { if (!$this->ui) { require_once($this->home . '/kolab_notes_ui.php'); $this->ui = new kolab_notes_ui($this); $this->ui->init(); } } /** * Read available calendars for the current user and store them internally */ private function _read_lists($force = false) { // already read sources if (isset($this->lists) && !$force) { return $this->lists; } // get all folders that have type "task" $folders = kolab_storage::sort_folders(kolab_storage::get_folders('note')); $this->lists = $this->folders = []; // find default folder $default_index = 0; foreach ($folders as $i => $folder) { if ($folder->default) { $default_index = $i; } } // put default folder on top of the list if ($default_index > 0) { $default_folder = $folders[$default_index]; unset($folders[$default_index]); array_unshift($folders, $default_folder); } foreach ($folders as $folder) { $item = $this->folder_props($folder); $this->lists[$item['id']] = $item; $this->folders[$item['id']] = $folder; $this->folders[$folder->name] = $folder; } } /** * Get a list of available folders from this source */ public function get_lists(&$tree = null) { $this->_read_lists(); // attempt to create a default folder for this user if (empty($this->lists)) { $folder = ['name' => 'Notes', 'type' => 'note', 'default' => true, 'subscribed' => true]; if (kolab_storage::folder_update($folder)) { $this->_read_lists(true); } } $folders = []; foreach ($this->lists as $id => $list) { if (!empty($this->folders[$id])) { $folders[] = $this->folders[$id]; } } // include virtual folders for a full folder tree if (!is_null($tree)) { $folders = kolab_storage::folder_hierarchy($folders, $tree); } $delim = $this->rc->get_storage()->get_hierarchy_delimiter(); $lists = []; foreach ($folders as $folder) { $list_id = $folder->id; $imap_path = explode($delim, $folder->name); // find parent do { array_pop($imap_path); $parent_id = kolab_storage::folder_id(implode($delim, $imap_path)); } while (count($imap_path) > 1 && empty($this->folders[$parent_id])); // restore "real" parent ID if ($parent_id && empty($this->folders[$parent_id])) { $parent_id = kolab_storage::folder_id($folder->get_parent()); } $fullname = $folder->get_name(); $listname = $folder->get_foldername(); // special handling for virtual folders if ($folder instanceof kolab_storage_folder_user) { $lists[$list_id] = [ 'id' => $list_id, 'name' => $fullname, 'listname' => $listname, 'title' => $folder->get_title(), 'virtual' => true, 'editable' => false, 'rights' => 'l', 'group' => 'other virtual', 'class' => 'user', 'parent' => $parent_id, ]; } elseif ($folder instanceof kolab_storage_folder_virtual) { $lists[$list_id] = [ 'id' => $list_id, 'name' => $fullname, 'listname' => $listname, 'virtual' => true, 'editable' => false, 'rights' => 'l', 'group' => $folder->get_namespace(), 'parent' => $parent_id, ]; } else { if (!$this->lists[$list_id]) { $this->lists[$list_id] = $this->folder_props($folder); $this->folders[$list_id] = $folder; } $this->lists[$list_id]['parent'] = $parent_id; $lists[$list_id] = $this->lists[$list_id]; } } return $lists; } /** * Search for shared or otherwise not listed folders the user has access * * @param string $query Search string * @param string $source Section/source to search * * @return array List of notes folders */ protected function search_lists($query, $source) { if (!kolab_storage::setup()) { return []; } $this->search_more_results = false; $this->lists = $this->folders = []; // find unsubscribed IMAP folders that have "event" type if ($source == 'folders') { foreach ((array)kolab_storage::search_folders('note', $query, ['other']) as $folder) { $this->folders[$folder->id] = $folder; $this->lists[$folder->id] = $this->folder_props($folder); } } // search other user's namespace via LDAP elseif ($source == 'users') { $limit = $this->rc->config->get('autocomplete_max', 15) * 2; // we have slightly more space, so display twice the number foreach (kolab_storage::search_users($query, 0, [], $limit * 10) as $user) { $folders = []; // search for note folders shared by this user foreach (kolab_storage::list_user_folders($user, 'note', false) as $foldername) { $folders[] = new kolab_storage_folder($foldername, 'note'); } $count = 0; if (count($folders)) { $userfolder = new kolab_storage_folder_user($user['kolabtargetfolder'], '', $user); $this->folders[$userfolder->id] = $userfolder; $this->lists[$userfolder->id] = $this->folder_props($userfolder); foreach ($folders as $folder) { $this->folders[$folder->id] = $folder; $this->lists[$folder->id] = $this->folder_props($folder); $count++; } } if ($count >= $limit) { $this->search_more_results = true; break; } } } return $this->get_lists(); } /** * Derive list properties from the given kolab_storage_folder object */ protected function folder_props($folder) { if ($folder->get_namespace() == 'personal') { $norename = false; $editable = true; $rights = 'lrswikxtea'; $alarms = true; } else { $alarms = false; $rights = 'lr'; $editable = false; if (($myrights = $folder->get_myrights()) && !PEAR::isError($myrights)) { $rights = $myrights; if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false) { $editable = strpos($rights, 'i'); } } $info = $folder->get_folder_info(); $norename = !$editable || $info['norename'] || $info['protected']; } $list_id = $folder->id; return [ 'id' => $list_id, 'name' => $folder->get_name(), 'listname' => $folder->get_foldername(), 'editname' => $folder->get_foldername(), 'editable' => $editable, 'rights' => $rights, 'norename' => $norename, 'parentfolder' => $folder->get_parent(), 'subscribed' => (bool)$folder->is_subscribed(), 'default' => $folder->default, 'group' => $folder->default ? 'default' : $folder->get_namespace(), 'class' => trim($folder->get_namespace() . ($folder->default ? ' default' : '')), ]; } /** * Get the kolab_calendar instance for the given calendar ID * * @param string $id List identifier (encoded imap folder name) * * @return ?kolab_storage_folder Object nor null if list doesn't exist */ public function get_folder($id) { // create list and folder instance if necesary if (empty($this->lists[$id])) { $folder = kolab_storage::get_folder(kolab_storage::id_decode($id)); if ($folder->type) { $this->folders[$id] = $folder; $this->lists[$id] = $this->folder_props($folder); } } return $this->folders[$id] ?? null; } /******* UI functions ********/ /** * Render main view of the tasklist task */ public function notes_view() { $this->ui->init(); $this->ui->init_templates(); $this->rc->output->set_pagetitle($this->gettext('navtitle')); $this->rc->output->send('kolab_notes.notes'); } /** * Deliver a rediced UI for inline (dialog) */ public function dialog_view() { // resolve message reference if ($msgref = rcube_utils::get_input_value('_msg', rcube_utils::INPUT_GPC, true)) { $storage = $this->rc->get_storage(); [$uid, $folder] = explode('-', $msgref, 2); if ($message = $storage->get_message_headers($msgref)) { $this->rc->output->set_env('kolab_notes_template', [ '_from_mail' => true, 'title' => $message->get('subject'), 'links' => [kolab_storage_config::get_message_reference( kolab_storage_config::get_message_uri($message, $folder), 'note' )], ]); } } $this->ui->init_templates(); $this->rc->output->send('kolab_notes.dialogview'); } /** * Handler to retrieve note records for the given list and/or search query */ public function notes_fetch() { $search = rcube_utils::get_input_value('_q', rcube_utils::INPUT_GPC, true); $list = rcube_utils::get_input_value('_list', rcube_utils::INPUT_GPC); $data = $this->notes_data($this->list_notes($list, $search), $tags); $this->rc->output->command('plugin.data_ready', [ 'list' => $list, 'search' => $search, 'data' => $data, 'tags' => array_values($tags), ]); } /** * Convert the given note records for delivery to the client */ protected function notes_data($records, &$tags) { $config = kolab_storage_config::get_instance(); $tags = $config->apply_tags($records); $config->apply_links($records); foreach ($records as $i => $rec) { unset($records[$i]['description']); $this->_client_encode($records[$i]); } return $records; } /** * Read note records for the given list from the storage backend */ protected function list_notes($list_id, $search = null) { $results = []; // query Kolab storage $query = []; // full text search (only works with cache enabled) if (strlen($search)) { $words = array_filter(rcube_utils::normalize_string(mb_strtolower($search), true)); foreach ($words as $word) { if (strlen($word) > 2) { // only words > 3 chars are stored in DB $query[] = ['words', '~', $word]; } } } $this->_read_lists(); if ($folder = $this->get_folder($list_id)) { foreach ($folder->select($query, empty($query)) as $record) { // post-filter search results if (strlen($search)) { $matches = 0; $desc = $this->is_html($record) ? strip_tags($record['description']) : ($record['description'] ?? ''); $contents = mb_strtolower($record['title'] . $desc); foreach ($words as $word) { if (mb_strpos($contents, $word) !== false) { $matches++; } } // skip records not matching all search words if ($matches < count($words)) { continue; } } $record['list'] = $list_id; $results[] = $record; } } return $results; } /** * Handler for delivering a full note record to the client */ public function note_record() { $data = $this->get_note([ 'uid' => rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC), 'list' => rcube_utils::get_input_value('_list', rcube_utils::INPUT_GPC), ]); // encode for client use if (is_array($data)) { $this->_client_encode($data); } $this->rc->output->command('plugin.render_note', $data); } /** * Get the full note record identified by the given UID + Lolder identifier */ public function get_note($note) { if (is_array($note)) { $uid = $note['uid'] ?: $note['id']; $list_id = $note['list']; } else { $uid = $note; } // deliver from in-memory cache if (!empty($list_id) && !empty($this->cache["$list_id:$uid"])) { return $this->cache["$list_id:$uid"]; } $result = false; $this->_read_lists(); if (!empty($list_id)) { if ($folder = $this->get_folder($list_id)) { $result = $folder->get_object($uid); } } // iterate over all calendar folders and search for the event ID else { foreach ($this->folders as $list_id => $folder) { if ($result = $folder->get_object($uid)) { $result['list'] = $list_id; break; } } } if ($result) { // get note tags $result['tags'] = $this->get_tags($result['uid']); // get note links $result['links'] = $this->get_links($result['uid']); } return $result; } /** * Helper method to encode the given note record for use in the client */ private function _client_encode(&$note) { foreach ($note as $key => $prop) { if ($key[0] == '_' || $key == 'x-custom') { unset($note[$key]); } } foreach (['created','changed'] as $key) { if (is_object($note[$key]) && $note[$key] instanceof DateTime) { $note[$key . '_'] = $note[$key]->format('U'); $note[$key] = $this->rc->format_date($note[$key]); } } // clean HTML contents if (!empty($note['description']) && $this->is_html($note)) { $note['html'] = $this->_wash_html($note['description']); } // convert link URIs references into structs if (array_key_exists('links', $note)) { foreach ((array)$note['links'] as $i => $link) { if (strpos($link, 'imap://') === 0 && ($msgref = kolab_storage_config::get_message_reference($link, 'note'))) { $note['links'][$i] = $msgref; } } } return $note; } /** * Handler for client-initiated actions on a single note record */ public function note_action() { $action = rcube_utils::get_input_value('_do', rcube_utils::INPUT_POST); $note = rcube_utils::get_input_value('_data', rcube_utils::INPUT_POST, true); $success = $silent = $refresh = false; switch ($action) { case 'new': case 'edit': if ($success = $this->save_note($note)) { $refresh = $this->get_note($note); } break; case 'move': $uids = explode(',', $note['uid']); foreach ($uids as $uid) { $note['uid'] = $uid; if (!($success = $this->move_note($note, $note['to']))) { $refresh = $this->get_note($note); break; } } break; case 'delete': $uids = explode(',', $note['uid']); foreach ($uids as $uid) { $note['uid'] = $uid; if (!($success = $this->delete_note($note))) { $refresh = $this->get_note($note); break; } } break; case 'changelog': $data = $this->get_changelog($note); if (is_array($data) && !empty($data)) { $rcmail = $this->rc; $dtformat = $rcmail->config->get('date_format') . ' ' . $this->rc->config->get('time_format'); array_walk($data, function (&$change) use ($rcmail, $dtformat) { if ($change['date']) { $dt = rcube_utils::anytodatetime($change['date']); if ($dt instanceof DateTime) { $change['date'] = $rcmail->format_date($dt, $dtformat); } } }); $this->rc->output->command('plugin.note_render_changelog', $data); } else { $this->rc->output->command('plugin.note_render_changelog', false); } $silent = true; break; case 'diff': $silent = true; $data = $this->get_diff($note, $note['rev1'], $note['rev2']); if (is_array($data)) { $this->rc->output->command('plugin.note_show_diff', $data); } else { $this->rc->output->command('display_message', $this->gettext('objectdiffnotavailable'), 'error'); } break; case 'show': if ($rec = $this->get_revison($note, $note['rev'])) { $this->rc->output->command('plugin.note_show_revision', $this->_client_encode($rec)); } else { $this->rc->output->command('display_message', $this->gettext('objectnotfound'), 'error'); } $silent = true; break; case 'restore': if ($this->restore_revision($note, $note['rev'])) { $refresh = $this->get_note($note); $this->rc->output->command('display_message', $this->gettext(['name' => 'objectrestoresuccess', 'vars' => ['rev' => $note['rev']]]), 'confirmation'); $this->rc->output->command('plugin.close_history_dialog'); } else { $this->rc->output->command('display_message', $this->gettext('objectrestoreerror'), 'error'); } $silent = true; break; } // show confirmation/error message if ($success) { $this->rc->output->show_message('successfullysaved', 'confirmation'); } elseif (!$silent) { $this->rc->output->show_message('errorsaving', 'error'); } // unlock client $this->rc->output->command('plugin.unlock_saving'); if ($refresh) { $this->rc->output->command('plugin.update_note', $this->_client_encode($refresh)); } } /** * Update an note record with the given data * * @param array $note Hash array with note properties (id, list) * * @return bool True on success, False on error */ private function save_note(&$note) { $this->_read_lists(); $list_id = $note['list']; if (!$list_id || !($folder = $this->get_folder($list_id))) { return false; } // moved from another folder if (!empty($note['_fromlist']) && ($fromfolder = $this->get_folder($note['_fromlist']))) { if (!$fromfolder->move($note['uid'], $folder->name)) { return false; } unset($note['_fromlist']); } // load previous version of this record to merge $old = null; if (!empty($note['uid'])) { $old = $folder->get_object($note['uid']); if (!$old || PEAR::isError($old)) { return false; } // merge existing properties if the update isn't complete if (!isset($note['title']) || !isset($note['description'])) { $note += $old; } } // generate new note object from input $object = $this->_write_preprocess($note, $old); // email links and tags are handled separately $links = $object['links'] ?? null; $tags = $object['tags'] ?? null; unset($object['links']); unset($object['tags']); $saved = $folder->save($object, 'note', $note['uid']); if (!$saved) { rcube::raise_error( [ 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving note object to Kolab server"], true, false ); $saved = false; } else { // save links in configuration.relation object $this->save_links($object['uid'], $links); // save tags in configuration.relation object $this->save_tags($object['uid'], $tags); $note = $object; $note['list'] = $list_id; $note['tags'] = (array) $tags; // cache this in memory for later read $key = $list_id . ':' . $note['uid']; $this->cache[$key] = $note; } return $saved; } /** * Move the given note to another folder */ public function move_note($note, $list_id) { $this->_read_lists(); $tofolder = $this->get_folder($list_id); $fromfolder = $this->get_folder($note['list']); if ($fromfolder && $tofolder) { return $fromfolder->move($note['uid'], $tofolder->name); } return false; } /** * Remove a single note record from the backend * * @param array $note Hash array with note properties (id, list) * @param bool $force Remove record irreversible (mark as deleted otherwise) * * @return bool True on success, False on error */ public function delete_note($note, $force = true) { $this->_read_lists(); $list_id = $note['list']; if (!$list_id || !($folder = $this->get_folder($list_id))) { return false; } $status = $folder->delete($note['uid'], $force); if ($status) { $this->save_links($note['uid'], null); $this->save_tags($note['uid'], null); } return $status; } /** * Render the template for printing with placeholders */ public function print_note() { $uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET); $list = rcube_utils::get_input_value('_list', rcube_utils::INPUT_GET); $this->note = $this->get_note(['uid' => $uid, 'list' => $list]); // encode for client use if (is_array($this->note)) { $this->_client_encode($this->note); } $this->rc->output->set_pagetitle($this->note['title']); $this->rc->output->add_handlers([ 'noteheader' => [$this, 'print_note_header'], 'notebody' => [$this, 'print_note_body'], ]); $this->include_script('notes.js'); $this->rc->output->send('kolab_notes.print'); } public function print_note_header() { $tags = array_map(['rcube', 'Q'], (array) $this->note['tags']); $tags = implode(' ', $tags); return html::tag('h1', ['id' => 'notetitle'], rcube::Q($this->note['title'])) . html::div(['id' => 'notetags', 'class' => 'tagline'], $tags) . html::div( 'dates', html::label(null, rcube::Q($this->gettext('created'))) . html::span(['id' => 'notecreated'], rcube::Q($this->note['created'])) . html::label(null, rcube::Q($this->gettext('changed'))) . html::span(['id' => 'notechanged'], rcube::Q($this->note['changed'])) ); } public function print_note_body() { return $this->note['html'] ?? rcube::Q($this->note['description']); } /** * Provide a list of revisions for the given object * * @param array $note Hash array with note properties * * @return array|false List of changes, each as a hash array */ public function get_changelog($note) { if (empty($this->bonnie_api)) { return false; } [$uid, $mailbox, $msguid] = $this->_resolve_note_identity($note); $result = $uid && $mailbox ? $this->bonnie_api->changelog('note', $uid, $mailbox, $msguid) : null; if (is_array($result) && $result['uid'] == $uid) { return $result['changes']; } return false; } /** * Return full data of a specific revision of a note record * * @param mixed $note UID string or hash array with note properties * @param mixed $rev Revision number * * @return array|false Note object as hash array */ public function get_revison($note, $rev) { if (empty($this->bonnie_api)) { return false; } [$uid, $mailbox, $msguid] = $this->_resolve_note_identity($note); // call Bonnie API $result = $this->bonnie_api->get('note', $uid, $rev, $mailbox, $msguid); if (is_array($result) && $result['uid'] == $uid && !empty($result['xml'])) { $format = kolab_format::factory('note'); $format->load($result['xml']); $rec = $format->to_array(); if ($format->is_valid()) { $rec['rev'] = $result['rev']; return $rec; } } return false; } /** * Get a list of property changes beteen two revisions of a note object * * @param array $note Hash array with note properties * @param mixed $rev1 Revision: "from" * @param mixed $rev2 Revision: "to" * * @return array|false List of property changes, each as a hash array */ public function get_diff($note, $rev1, $rev2) { if (empty($this->bonnie_api)) { return false; } [$uid, $mailbox, $msguid] = $this->_resolve_note_identity($note); // call Bonnie API $result = $this->bonnie_api->diff('note', $uid, $rev1, $rev2, $mailbox, $msguid); if (is_array($result) && $result['uid'] == $uid) { $result['rev1'] = $rev1; $result['rev2'] = $rev2; // convert some properties, similar to self::_client_encode() $keymap = [ 'summary' => 'title', 'lastmodified-date' => 'changed', ]; // map kolab object properties to keys and values the client expects array_walk($result['changes'], function (&$change, $i) use ($keymap) { if (array_key_exists($change['property'], $keymap)) { $change['property'] = $keymap[$change['property']]; } if ($change['property'] == 'created' || $change['property'] == 'changed') { if ($old_ = rcube_utils::anytodatetime($change['old'])) { $change['old_'] = $this->rc->format_date($old_); } if ($new_ = rcube_utils::anytodatetime($change['new'])) { $change['new_'] = $this->rc->format_date($new_); } } // compute a nice diff of note contents if ($change['property'] == 'description') { $change['diff_'] = libkolab::html_diff($change['old'], $change['new']); if (!empty($change['diff_'])) { unset($change['old'], $change['new']); $change['diff_'] = preg_replace(['!^.*]*>!Uims','!.*$!Uims'], '', $change['diff_']); $change['diff_'] = preg_replace("!\n!", '', $change['diff_']); } } }); return $result; } return false; } /** * Command the backend to restore a certain revision of a note. * This shall replace the current object with an older version. * * @param array $note Hash array with note properties (id, list) * @param mixed $rev Revision number * * @return bool True on success, False on failure */ public function restore_revision($note, $rev) { if (empty($this->bonnie_api)) { return false; } [$uid, $mailbox, $msguid] = $this->_resolve_note_identity($note); $folder = $this->get_folder($note['list']); $success = false; if ($folder && ($raw_msg = $this->bonnie_api->rawdata('note', $uid, $rev, $mailbox))) { $imap = $this->rc->get_storage(); // insert $raw_msg as new message if ($imap->save_message($folder->name, $raw_msg, null, false)) { $success = true; // delete old revision from imap and cache $imap->delete_message($msguid, $folder->name); $folder->cache->set($msguid, false); $this->cache = []; } } return $success; } /** * Helper method to resolved the given note identifier into uid and mailbox * * @return array (uid,mailbox,msguid) tuple */ private function _resolve_note_identity($note) { $mailbox = $msguid = null; if (!is_array($note)) { $note = $this->get_note($note); } if (is_array($note)) { $uid = $note['uid'] ?: $note['id']; $list = $note['list']; } else { return [null, $mailbox, $msguid]; } if ($folder = $this->get_folder($list)) { $mailbox = $folder->get_mailbox_id(); // get object from storage in order to get the real object uid an msguid if ($rec = $folder->get_object($uid)) { $msguid = $rec['_msguid']; $uid = $rec['uid']; } } return [$uid, $mailbox, $msguid]; } /** * Handler for client requests to list (aka folder) actions */ public function list_action() { $action = rcube_utils::get_input_value('_do', rcube_utils::INPUT_GPC); $list = rcube_utils::get_input_value('_list', rcube_utils::INPUT_GPC, true); $success = $update_cmd = false; $jsenv = []; if (empty($action)) { $action = rcube_utils::get_input_value('action', rcube_utils::INPUT_GPC); } switch ($action) { case 'form-new': case 'form-edit': $this->_read_lists(); $this->ui->list_editform($action, $this->lists[$list['id']], $this->folders[$list['id']]); exit; case 'new': $list['type'] = 'note'; $list['subscribed'] = true; $folder = kolab_storage::folder_update($list); if ($folder === false) { $save_error = $this->gettext(kolab_storage::$last_error); } else { $success = true; $update_cmd = 'plugin.update_list'; $list['id'] = kolab_storage::folder_id($folder); $list['_reload'] = true; } break; case 'edit': $this->_read_lists(); $oldparent = $this->lists[$list['id']]['parentfolder']; $newfolder = kolab_storage::folder_update($list); if ($newfolder === false) { $save_error = $this->gettext(kolab_storage::$last_error); } else { $success = true; $update_cmd = 'plugin.update_list'; $list['newid'] = kolab_storage::folder_id($newfolder); $list['_reload'] = $list['parent'] != $oldparent; // compose the new display name $delim = $this->rc->get_storage()->get_hierarchy_delimiter(); $path_imap = explode($delim, $newfolder); $list['name'] = kolab_storage::object_name($newfolder); $list['editname'] = rcube_charset::convert(array_pop($path_imap), 'UTF7-IMAP'); $list['listname'] = $list['editname']; } break; case 'delete': $this->_read_lists(); $folder = $this->get_folder($list['id']); if ($folder && kolab_storage::folder_delete($folder->name)) { $success = true; $update_cmd = 'plugin.destroy_list'; } else { $save_error = $this->gettext(kolab_storage::$last_error); } break; case 'search': $this->load_ui(); $results = []; foreach ((array)$this->search_lists(rcube_utils::get_input_value('q', rcube_utils::INPUT_GPC), rcube_utils::get_input_value('source', rcube_utils::INPUT_GPC)) as $id => $prop) { $editname = $prop['editname']; unset($prop['editname']); // force full name to be displayed // let the UI generate HTML and CSS representation for this calendar $html = $this->ui->folder_list_item($id, $prop, $jsenv, true); - $prop += $jsenv[$id] ?? []; + $prop += $jsenv[$id] ?? []; // @phpstan-ignore-line $prop['editname'] = $editname; $prop['html'] = $html; $results[] = $prop; } // report more results available if ($this->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; case 'subscribe': $success = false; if ($list['id'] && ($folder = $this->get_folder($list['id']))) { if (isset($list['permanent'])) { $success |= $folder->subscribe(intval($list['permanent'])); } if (isset($list['active'])) { $success |= $folder->activate(intval($list['active'])); } // apply to child folders, too if ($list['recursive']) { foreach ((array)kolab_storage::list_folders($folder->name, '*', 'node') as $subfolder) { if (isset($list['permanent'])) { ($list['permanent'] ? kolab_storage::folder_subscribe($subfolder) : kolab_storage::folder_unsubscribe($subfolder)); } if (isset($list['active'])) { ($list['active'] ? kolab_storage::folder_activate($subfolder) : kolab_storage::folder_deactivate($subfolder)); } } } } break; } $this->rc->output->command('plugin.unlock_saving'); if ($success) { $this->rc->output->show_message('successfullysaved', 'confirmation'); if ($update_cmd) { $this->rc->output->command($update_cmd, $list); } } else { $error_msg = $this->gettext('errorsaving') . (!empty($save_error) ? ': ' . $save_error : ''); $this->rc->output->show_message($error_msg, 'error'); } } /** * Hook to add note attachments to message compose if the according parameter is present. * This completes the 'send note by mail' feature. */ public function mail_message_compose($args) { if (!empty($args['param']['with_notes'])) { $uids = explode(',', $args['param']['with_notes']); $list = $args['param']['notes_list']; foreach ($uids as $uid) { if ($note = $this->get_note(['uid' => $uid, 'list' => $list])) { $data = $this->note2message($note); $args['attachments'][] = [ 'name' => abbreviate_string($note['title'], 50, ''), 'mimetype' => 'message/rfc822', 'data' => $data, 'size' => strlen($data), ]; if (empty($args['param']['subject'])) { $args['param']['subject'] = $note['title']; } } } unset($args['param']['with_notes'], $args['param']['notes_list']); } return $args; } /** * 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->message_notes = $this->get_message_notes($p['object']->headers, $p['object']->folder); } } /** * Handler for 'messagebody_html' hook */ public function mail_messagebody_html($args) { $html = ''; foreach ($this->message_notes as $note) { $html .= html::a([ 'href' => $this->rc->url(['task' => 'notes', '_list' => $note['list'], '_id' => $note['uid']]), 'class' => 'kolabnotesref', 'rel' => $note['uid'] . '@' . $note['list'], 'target' => '_blank', ], rcube::Q($note['title'])); } // prepend note links to message body if ($html) { $this->load_ui(); $args['content'] = html::div('kolabmessagenotes boxinformation', $html) . $args['content']; } return $args; } /** * Determine whether the given note is HTML formatted */ private function is_html($note) { // check for opening and closing or tags return !empty($note['description']) && preg_match('/<(html|body)(\s+[a-z]|>)/', $note['description'], $m) && strpos($note['description'], '') > 0; } /** * Build an RFC 822 message from the given note */ private function note2message($note) { $message = new Mail_mime("\r\n"); $message->setParam('text_encoding', '8bit'); $message->setParam('html_encoding', 'quoted-printable'); $message->setParam('head_encoding', 'quoted-printable'); $message->setParam('head_charset', RCUBE_CHARSET); $message->setParam('html_charset', RCUBE_CHARSET); $message->setParam('text_charset', RCUBE_CHARSET); $message->headers([ 'Subject' => $note['title'], 'Date' => $note['changed']->format('r'), ]); if ($this->is_html($note)) { $message->setHTMLBody($note['description']); // add a plain text version of the note content as an alternative part. $h2t = new rcube_html2text($note['description'], false, true, 0, RCUBE_CHARSET); $plain_part = rcube_mime::wordwrap($h2t->get_text(), $this->rc->config->get('line_length', 72), "\r\n", false, RCUBE_CHARSET); $plain_part = trim(wordwrap($plain_part, 998, "\r\n", true)); // make sure all line endings are CRLF $plain_part = preg_replace('/\r?\n/', "\r\n", $plain_part); $message->setTXTBody($plain_part); } else { $message->setTXTBody($note['description']); } return $message->getMessage(); } private function save_links($uid, $links) { $config = kolab_storage_config::get_instance(); return $config->save_object_links($uid, (array) $links); } /** * Find messages assigned to specified note */ private function get_links($uid) { $config = kolab_storage_config::get_instance(); return $config->get_object_links($uid); } /** * Get note tags */ private function get_tags($uid) { $config = kolab_storage_config::get_instance(); $tags = $config->get_tags($uid); $tags = array_map(function ($v) { return $v['name']; }, $tags); return $tags; } /** * Find notes assigned to specified message */ private function get_message_notes($message, $folder) { $config = kolab_storage_config::get_instance(); $result = $config->get_message_relations($message, $folder, 'note'); foreach ($result as $idx => $note) { $result[$idx]['list'] = kolab_storage::folder_id($note['_mailbox']); } return $result; } /** * Update note tags */ private function save_tags($uid, $tags) { $config = kolab_storage_config::get_instance(); $config->save_tags($uid, $tags); } /** * Process the given note data (submitted by the client) before saving it */ private function _write_preprocess($note, $old = []) { $object = $note; // TODO: handle attachments // convert link references into simple URIs if (array_key_exists('links', $note)) { $object['links'] = array_map(function ($link) { return is_array($link) ? $link['uri'] : strval($link); }, $note['links']); } else { if ($old) { $object['links'] = $old['links'] ?? null; } } // clean up HTML content $object['description'] = $this->_wash_html($note['description']); $is_html = true; // try to be smart and convert to plain-text if no real formatting is detected if (preg_match('!<(?:p|pre)>(.*)!Uims', $object['description'], $m)) { if (!preg_match('!<(a|b|i|strong|em|p|span|div|pre|li|img)(\s+[a-z]|>)!im', $m[1], $n) || ($n[1] != 'img' && !strpos($m[1], '')) ) { // $converter = new rcube_html2text($m[1], false, true, 0); // $object['description'] = rtrim($converter->get_text()); $object['description'] = html_entity_decode(preg_replace('!!', "\n", $m[1])); $is_html = false; } } // Add proper HTML header, otherwise Kontact renders it as plain text if ($is_html) { $object['description'] = '' . "\n" . str_replace('', '', $object['description']); } // copy meta data (starting with _) from old object foreach ((array)$old as $key => $val) { if (!isset($object[$key]) && $key[0] == '_') { $object[$key] = $val; } } // make list of categories unique if (!empty($object['tags'])) { $object['tags'] = array_unique(array_filter($object['tags'])); } unset($object['list'], $object['tempid'], $object['created'], $object['changed'], $object['created_'], $object['changed_']); return $object; } /** * Sanity checks/cleanups HTML content */ private function _wash_html($html) { // Add header with charset spec., washtml cannot work without that $html = '' . '' . '' . $html . ''; // clean HTML with washtml by Frederic Motte $wash_opts = [ 'show_washed' => false, 'allow_remote' => 1, 'charset' => RCUBE_CHARSET, 'html_elements' => ['html', 'head', 'meta', 'body', 'link'], 'html_attribs' => ['rel', 'type', 'name', 'http-equiv'], ]; // initialize HTML washer $washer = new rcube_washtml($wash_opts); $washer->add_callback('form', [$this, '_washtml_callback']); $washer->add_callback('a', [$this, '_washtml_callback']); // Remove non-UTF8 characters $html = rcube_charset::clean($html); $html = $washer->wash($html); // remove unwanted comments (produced by washtml) $html = preg_replace('//', '', $html); return $html; } /** * Callback function for washtml cleaning class */ public function _washtml_callback($tagname, $attrib, $content, $washtml) { switch ($tagname) { case 'form': $out = html::div('form', $content); break; case 'a': // strip temporary link tags from plain-text markup $attrib = html::parse_attrib_string($attrib); if (!empty($attrib['class']) && strpos($attrib['class'], 'x-templink') !== false) { // remove link entirely if (strpos($attrib['href'], html_entity_decode($content)) !== false) { $out = $content; break; } $attrib['class'] = trim(str_replace('x-templink', '', $attrib['class'])); } $out = html::a($attrib, $content); break; default: $out = ''; } return $out; } } diff --git a/plugins/kolab_notes/kolab_notes_ui.php b/plugins/kolab_notes/kolab_notes_ui.php index d782d38d..35ae135a 100644 --- a/plugins/kolab_notes/kolab_notes_ui.php +++ b/plugins/kolab_notes/kolab_notes_ui.php @@ -1,366 +1,364 @@ plugin = $plugin; $this->rc = $plugin->rc; } /** * Calendar UI initialization and requests handlers */ public function init() { if ($this->ready) { // already done return; } // add taskbar button $this->plugin->add_button([ 'command' => 'notes', 'class' => 'button-notes', 'classsel' => 'button-notes button-selected', 'innerclass' => 'button-inner', 'label' => 'kolab_notes.navtitle', 'type' => 'link', ], 'taskbar'); $this->plugin->include_stylesheet($this->plugin->local_skin_path() . '/notes.css'); $this->ready = true; } /** * Register handler methods for the template engine */ public function init_templates() { $this->plugin->register_handler('plugin.notebooks', [$this, 'folders']); #$this->plugin->register_handler('plugin.folders_select', array($this, 'folders_select')); $this->plugin->register_handler('plugin.searchform', [$this->rc->output, 'search_form']); $this->plugin->register_handler('plugin.listing', [$this, 'listing']); $this->plugin->register_handler('plugin.editform', [$this, 'editform']); $this->plugin->register_handler('plugin.notetitle', [$this, 'notetitle']); $this->plugin->register_handler('plugin.detailview', [$this, 'detailview']); $this->plugin->register_handler('plugin.attachments_list', [$this, 'attachments_list']); $this->plugin->register_handler('plugin.object_changelog_table', ['libkolab', 'object_changelog_table']); $this->rc->output->include_script('list.js'); $this->rc->output->include_script('treelist.js'); $this->plugin->include_script('notes.js'); $this->plugin->api->include_script('libkolab/libkolab.js'); // load config options and user prefs relevant for the UI $settings = [ 'sort_col' => $this->rc->config->get('kolab_notes_sort_col', 'changed'), ]; if ($list = rcube_utils::get_input_value('_list', rcube_utils::INPUT_GPC)) { $settings['selected_list'] = $list; } if ($uid = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC)) { $settings['selected_uid'] = $uid; } $this->rc->html_editor(); $this->rc->output->set_env('kolab_notes_settings', $settings); $this->rc->output->add_label('save', 'cancel', 'delete', 'close', 'listoptionstitle'); } public function folders($attrib) { $attrib += ['id' => 'rcmkolabnotebooks']; $is_select = ($attrib['type'] ?? null) == 'select'; if ($is_select) { $attrib['is_escaped'] = true; $select = new html_select($attrib); } $tree = !$is_select ? true : null; $lists = $this->plugin->get_lists($tree); $jsenv = []; + // @phpstan-ignore-next-line if (is_object($tree)) { $html = $this->folder_tree_html($tree, $lists, $jsenv, $attrib); } else { $html = ''; foreach ($lists as $prop) { $id = $prop['id']; if (empty($prop['virtual'])) { unset($prop['user_id']); $jsenv[$id] = $prop; } if ($is_select) { if ($prop['editable'] || strpos($prop['rights'], 'i') !== false) { $select->add($prop['name'], $prop['id']); } } else { $html .= html::tag( 'li', ['id' => 'rcmliknb' . rcube_utils::html_identifier($id), 'class' => $prop['group']], $this->folder_list_item($id, $prop, $jsenv) ); } } } $this->rc->output->set_env('kolab_notebooks', $jsenv); $this->rc->output->add_gui_object('notebooks', $attrib['id']); return $is_select ? $select->show() : html::tag('ul', $attrib, $html, html::$common_attrib); } /** * Return html for a structured list
      for the folder tree */ public function folder_tree_html($node, $data, &$jsenv, $attrib) { $out = ''; foreach ($node->children as $folder) { $id = $folder->id; $prop = $data[$id]; $is_collapsed = false; // TODO: determine this somehow? $content = $this->folder_list_item($id, $prop, $jsenv); if (!empty($folder->children)) { $content .= html::tag( 'ul', - ['style' => ($is_collapsed ? "display:none;" : null)], + ['style' => ($is_collapsed ? "display:none;" : null)], // @phpstan-ignore-line $this->folder_tree_html($folder, $data, $jsenv, $attrib) ); } if (strlen($content)) { $out .= html::tag( 'li', [ 'id' => 'rcmliknb' . rcube_utils::html_identifier($id), 'class' => $prop['group'] . (!empty($prop['virtual']) ? ' virtual' : ''), ], $content ); } } return $out; } /** * Helper method to build a tasklist item (HTML content and js data) */ public function folder_list_item($id, $prop, &$jsenv, $checkbox = false) { if (empty($prop['virtual'])) { unset($prop['user_id']); $jsenv[$id] = $prop; } $classes = ['folder']; if (!empty($prop['virtual'])) { $classes[] = 'virtual'; } elseif (!$prop['editable']) { $classes[] = 'readonly'; } if ($prop['subscribed']) { $classes[] = 'subscribed'; } if ($prop['class']) { $classes[] = $prop['class']; } $title = !empty($prop['title']) ? $prop['title'] : ($prop['name'] != $prop['listname'] || strlen($prop['name']) > 25 ? html_entity_decode($prop['name'], ENT_COMPAT, RCUBE_CHARSET) : ''); $label_id = 'nl:' . $id; $attr = !empty($prop['virtual']) ? ['tabindex' => '0'] : ['href' => $this->rc->url(['_list' => $id])]; + return html::div( implode(' ', $classes), html::a($attr + ['class' => 'listname', 'title' => $title, 'id' => $label_id], $prop['listname'] ?: $prop['name']) . ( !empty($prop['virtual']) ? '' : ( $checkbox ? html::tag('input', ['type' => 'checkbox', 'name' => '_list[]', 'value' => $id, 'checked' => $prop['active'], 'aria-labelledby' => $label_id]) : '' ) . html::span('handle', '') . html::span( 'actions', ( empty($prop['default']) ? html::a(['href' => '#', 'class' => 'remove', 'title' => $this->plugin->gettext('removelist')], ' ') : '' ) . ( isset($prop['subscribed']) ? html::a(['href' => '#', 'class' => 'subscribed', 'title' => $this->plugin->gettext('foldersubscribe'), 'role' => 'checkbox', 'aria-checked' => $prop['subscribed'] ? 'true' : 'false'], ' ') : '' ) ) ) ); - - return ''; } public function listing($attrib) { $attrib += ['id' => 'rcmkolabnoteslist']; $this->rc->output->add_gui_object('noteslist', $attrib['id']); return html::tag('table', $attrib, '', html::$common_attrib); } public function editform($attrib) { $attrib += ['action' => '#', 'id' => 'rcmkolabnoteseditform']; $textarea = new html_textarea([ 'name' => 'content', 'id' => 'notecontent', 'cols' => 60, 'rows' => 20, 'tabindex' => 0, 'class' => 'mce_editor form-control', ]); $this->rc->output->add_gui_object('noteseditform', $attrib['id']); return html::tag('form', $attrib, $textarea->show(), array_merge(html::$common_attrib, ['action'])); } public function detailview($attrib) { $attrib += ['id' => 'rcmkolabnotesdetailview']; $this->rc->output->add_gui_object('notesdetailview', $attrib['id']); return html::div($attrib, ''); } public function notetitle($attrib) { $attrib += ['id' => 'rcmkolabnotestitle']; $this->rc->output->add_gui_object('noteviewtitle', $attrib['id']); $summary = new html_inputfield([ 'name' => 'summary', 'class' => 'notetitle inline-edit form-control', 'size' => 60, 'id' => 'notetitleinput', 'tabindex' => 0, ]); $html = html::div( 'form-group row', html::label(['class' => 'col-sm-2 col-form-label', 'for' => 'notetitleinput'], $this->plugin->gettext('kolab_notes.title')) . html::span('col-sm-10', $summary->show()) ) . html::div( 'form-group row', html::label(['class' => 'col-sm-2 col-form-label'], $this->plugin->gettext('kolab_notes.tags')) . html::div(['class' => 'tagline tagedit col-sm-10'], ' ') ) . html::div( ['class' => 'dates text-only', 'style' => 'display:none'], html::div( 'form-group row', html::label(['class' => 'col-sm-2 col-form-label'], $this->plugin->gettext('created')) . html::span('col-sm-10', html::span('notecreated form-control-plaintext', '')) ) . html::div( 'form-group row', html::label(['class' => 'col-sm-2 col-form-label'], $this->plugin->gettext('changed')) . html::span('col-sm-10', html::span('notechanged form-control-plaintext', '')) ) ); return html::div($attrib, $html); } public function attachments_list($attrib) { $attrib += ['id' => 'rcmkolabnotesattachmentslist']; $this->rc->output->add_gui_object('notesattachmentslist', $attrib['id']); return html::tag('ul', $attrib, '', html::$common_attrib); } /** * Render create/edit form for notes lists (folders) */ public function list_editform($action, $list, $folder) { - $this->action = $action; $this->list = $list; $this->folder = is_object($folder) ? $folder->name : ''; // UTF7; $this->rc->output->set_env('pagetitle', $this->plugin->gettext('arialabelnotebookform')); $this->rc->output->add_handler('folderform', [$this, 'notebookform']); $this->rc->output->send('libkolab.folderform'); } /** * Render create/edit form for notes lists (folders) */ public function notebookform($attrib) { $folder_name = $this->folder; $hidden_fields[] = ['name' => 'oldname', 'value' => $folder_name]; $storage = $this->rc->get_storage(); $delim = $storage->get_hierarchy_delimiter(); $form = []; if (strlen($folder_name)) { $options = $storage->folder_info($folder_name); $path_imap = explode($delim, $folder_name); array_pop($path_imap); // pop off name part $path_imap = implode($delim, $path_imap); } else { $path_imap = ''; $options = []; } // General tab $form['properties'] = [ 'name' => $this->rc->gettext('properties'), 'fields' => [], ]; // folder name (default field) $input_name = new html_inputfield(['name' => 'name', 'id' => 'noteslist-name', 'size' => 20]); $form['properties']['fields']['name'] = [ 'label' => $this->plugin->gettext('listname'), 'value' => $input_name->show($this->list['editname'], ['disabled' => ($options['norename'] || $options['protected'])]), 'id' => 'noteslist-name', ]; // prevent user from moving folder if (!empty($options) && ($options['norename'] || $options['protected'])) { $hidden_fields[] = ['name' => 'parent', 'value' => $path_imap]; } else { $select = kolab_storage::folder_selector('note', ['name' => 'parent', 'id' => 'parent-folder'], $folder_name); $form['properties']['fields']['path'] = [ 'label' => $this->plugin->gettext('parentfolder'), 'value' => $select->show(strlen($folder_name) ? $path_imap : ''), 'id' => 'parent-folder', ]; } $form_html = kolab_utils::folder_form($form, $folder_name, 'kolab_notes', $hidden_fields); return html::tag('form', $attrib + ['action' => '#', 'method' => 'post', 'id' => 'noteslistpropform'], $form_html); } } diff --git a/plugins/libcalendaring/lib/libcalendaring_vcalendar.php b/plugins/libcalendaring/lib/libcalendaring_vcalendar.php index 41b2ed3a..f07a7869 100644 --- a/plugins/libcalendaring/lib/libcalendaring_vcalendar.php +++ b/plugins/libcalendaring/lib/libcalendaring_vcalendar.php @@ -1,1591 +1,1592 @@ * * 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; private $prodid; private $type_component_map = ['event' => 'VEVENT', 'task' => 'VTODO']; private $attendee_keymap = [ '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 = [ '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 = []; public $method; public $agent = ''; public $objects = []; public $freebusy = []; public $sender; public $message_date; public $mime_id; /** * Default constructor */ public function __construct($tz = null) { $this->timezone = $tz; $this->prodid = '-//Roundcube ' . RCUBE_VERSION . '//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 = []; $this->freebusy = []; $this->vtimezones = []; $this->iteratorkey = 0; if ($this->fp) { fclose($this->fp); $this->fp = null; } } /** * Import events from iCalendar format * * @param string $vcal vCalendar input * @param string $charset Input charset (from envelope) * @param bool $forward_exceptions 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( [ 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "iCal data parse error: " . $e->getMessage()], true, false ); } } return []; } /** * Read iCalendar events from a file * * @param string $filepath File path to read from * @param string $charset Input charset (from envelope) * @param bool $forward_exceptions 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 $filepath File path to read from * @param string $charset Input charset (from envelope) * @param bool $forward_exceptions True if parsing exceptions should be forwarded to the caller * * @return bool 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 = []; $this->freebusy = []; } $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( [ '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 VObject\Component $vobject Component to read from * * @return array List of events extracted from the file */ public function import_from_vobject($vobject) { $seen = []; $exceptions = []; 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; } elseif (empty($seen[$object['uid']])) { $seen[$object['uid']] = true; $this->objects[] = $object; } } elseif ($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 = []; 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 VObject\Component\VEvent|VObject\Component\VTodo $ve VEvent object to convert * * @return array Hash array with object properties */ private function _to_array($ve) { $event = [ 'uid' => self::convert_string($ve->UID), 'title' => self::convert_string($ve->SUMMARY), '_type' => $ve->name == 'VTODO' ? 'task' : 'event', // set defaults 'priority' => 0, 'attendees' => [], 'x-custom' => [], ]; // Catch possible exceptions when date is invalid (Bug #2144) // We can skip these fields, they aren't critical foreach (['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 = ['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'; } elseif ($value == 'CANCELLED') { $event['cancelled'] = true; } elseif ($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'] : []; // 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'; } elseif (in_array($value, ['FREE', 'BUSY', 'TENTATIVE'])) { $event['free_busy'] = strtolower($value); } break; case 'ATTENDEE': case 'ORGANIZER': $params = ['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']; } } elseif (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; } elseif (!empty($params['VALUE']) && strtoupper($params['VALUE']) == 'BINARY') { $attachment = self::map_keys($params, [ 'FMTTYPE' => 'mimetype', 'X-LABEL' => 'name', 'X-APPLE-FILENAME' => 'name', 'X-SIZE' => 'size', ]); $attachment['data'] = $value; $attachment['size'] ??= strlen($value); $attachment['id'] = md5(($attachment['mimetype'] ?? 'application/octet-stream') . ($attachment['name'] ?? 'noname')); $event['attachments'][] = $attachment; } break; default: if (substr($prop->name, 0, 2) == 'X-') { $event['x-custom'][] = [$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) elseif ($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 = []; 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(); } elseif ($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'][] = ['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 * * @param DateTime $date */ 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 = ['_type' => 'freebusy', 'periods' => []]; $seen = []; 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 = [ '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. [$busyStart, $busyEnd] = explode('/', $period); $busyStart = DateTimeParser::parse($busyStart); $busyEnd = DateTimeParser::parse($busyEnd); if ($busyEnd instanceof \DateInterval) { $tmp = clone $busyStart; - $tmp->add($busyEnd); - $busyEnd = $tmp; + $busyEnd = $tmp->add($busyEnd); } if ($busyEnd && $busyEnd > $busyStart) { $this->freebusy['periods'][] = [$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 = self::toDateTime($item); $item->_dateonly = $dateonly; $dt[] = $item; } } else { $dt = self::toDateTime($prop->getDateTime()); if (!$prop->hasTime()) { $dt->_dateonly = true; } } } elseif ($prop instanceof VObject\Property\ICalendar\Period) { $dt = []; foreach ($prop->getParts() as $val) { try { [$start, $end] = explode('/', $val); - $start = DateTimeParser::parseDateTime($start); + $start = self::toDateTime(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); + $end = self::toDateTime(DateTimeParser::parseDateTime($end)); } - $dt[] = [self::toDateTime($start), self::toDateTime($end)]; + $dt[] = [$start, $end]; } catch (Exception $e) { // ignore single date parse errors } } } elseif ($prop instanceof \DateTimeInterface) { $dt = self::toDateTime($prop); } // force return value to array if requested if ($as_array) { if (empty($dt)) { return []; } return is_array($dt) ? $dt : [$dt]; } return $dt ?? null; } /** * Create a Sabre\VObject\Property instance from a PHP DateTime object * * @param VObject\Document $cal Parent node to create property for * @param string $name Property name * @param DateTime $dt Date time object * @param bool $utc Set as UTC date * @param bool $dateonly Set as VALUE=DATE property * * @return VObject\Property */ public function datetime_prop($cal, $name, $dt, $utc = false, $dateonly = null, $set_type = false) { $tz = null; $is_utc = false; if ($dt) { if ($utc) { $dt->setTimeZone(new DateTimeZone('UTC')); $is_utc = true; } else { $is_utc = ($tz = $dt->getTimezone()) && in_array($tz->getName(), ['UTC','GMT','Z']); } } $is_dateonly = $dateonly === null && $dt ? !empty($dt->_dateonly) : (bool) $dateonly; $vdt = $cal->createProperty($name, $dt, null, $is_dateonly ? 'DATE' : 'DATE-TIME'); if ($is_dateonly) { $vdt['VALUE'] = 'DATE'; } elseif ($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] = [$ts, $ts]; } } return $vdt; } /** * Copy values from one hash array to another using a key-map */ public static function map_keys($values, $map) { $out = []; foreach ($map as $from => $to) { if (isset($values[$from])) { $out[$to] = is_array($values[$from]) ? implode(',', $values[$from]) : $values[$from]; } } return $out; } /** * */ private static function parameters_array($prop) { $params = []; foreach ($prop->parameters() as $name => $value) { $params[strtoupper($name)] = strval($value); } return $params; } /** * Export events to iCalendar format * * @param array $objects Events as array * @param ?string $method VCalendar method to advertise * @param bool $write Directly send data to stdout instead of returning * @param ?callable $get_attachment Optional callback function to fetch attachment contents * @param bool $with_timezones Add VTIMEZONE block with timezone definitions for the included events * * @return string|true Events in iCalendar format (http://tools.ietf.org/html/rfc5545) */ public function export($objects, $method = null, $write = false, $get_attachment = null, $with_timezones = true) { $this->method = $method; // encapsulate in VCALENDAR container $vcal = new VObject\Component\VCalendar(); $vcal->VERSION = '2.0'; // @phpstan-ignore-line $vcal->PRODID = $this->prodid; // @phpstan-ignore-line $vcal->CALSCALE = 'GREGORIAN'; // @phpstan-ignore-line if (!empty($method)) { $vcal->METHOD = $method; // @phpstan-ignore-line } // 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; } return $vcal->serialize(); } /** * Converts internal event representation to Sabre component * * @param array $object Event * @param ?callable $get_attachment Optional callback function to fetch attachment contents * * @return VObject\Component Sabre component */ public function toSabreComponent($object, $get_attachment = null) { $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 $event Hash array with event/task properties from libkolab + * @param array $event Hash array with event/task properties from libkolab * @param VObject\Component\VCalendar $vcal VCalendar object to append event to or false for directly sending data to stdout - * @param ?callable $get_attachment Optional callback function to fetch attachment contents - * @param object $recurrence_id RECURRENCE-ID property when serializing a recurrence exception + * @param ?callable $get_attachment Optional callback function to fetch attachment contents + * @param VObject\Property $recurrence_id 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'] = self::toDateTime($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); } 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'], ["\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'); } elseif (!empty($event['free_busy']) && $event['free_busy'] == 'tentative') { $ve->add('STATUS', 'TENTATIVE'); } elseif (!empty($event['complete']) && $event['complete'] == 100) { $ve->add('STATUS', 'COMPLETED'); } elseif (!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 = []; 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'], ['VALUE' => 'URI']); } $ve->add($va); } } // legacy support elseif (!empty($event['alarms'])) { $va = $cal->createComponent('VALARM'); [$trigger, $va->action] = explode(':', $event['alarms']); $val = libcalendaring::parse_alarm_value($trigger); if (!empty($val[3])) { $va->add('TRIGGER', $val[3]); } elseif ($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 (!empty($attendee['role']) && $attendee['role'] == 'ORGANIZER') { if (empty($event['organizer'])) { $event['organizer'] = $attendee; } } elseif (!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'], ['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 $idx => $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) && !empty($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'] ?? $idx, $event))) { // embed attachments for iCal $ve->add( 'ATTACH', $data, array_filter([ 'VALUE' => 'BINARY', 'ENCODING' => 'BASE64', 'FMTTYPE' => $attach['mimetype'] ?? null, 'X-LABEL' => $attach['name'] ?? null, 'X-SIZE' => $attach['size'] ?? null, ]) ); unset($data); // attempt to free memory } // list attachments as absolute URIs elseif (!empty($this->attach_uri)) { $ve->add( 'ATTACH', strtr($this->attach_uri, [ '{{id}}' => urlencode($attach['id'] ?? $idx), '{{name}}' => urlencode($attach['name']), '{{mimetype}}' => urlencode($attach['mimetype']), ]), ['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 $tzid Timezone ID as used in PHP's Date functions * @param int $from Unix timestamp with first date/time in this timezone * @param int $to Unix timestap with last date/time in this timezone * @param VObject\Component\VCalendar $cal Optional VCalendar component * * @return VObject\Component|false 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) { // do nothing } } elseif ($tzid instanceof DateTimeZone) { $tz = $tzid; } if (empty($tz) || !$tz instanceof 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; $t_dst = $t_std = 0; foreach ($transitions as $i => $trans) { 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; } // FIXME: Imho $trans['time'] is UTC, shouldn't we consider timezone offset for DTSTART below? $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; } /** * Convert DateTime into libcalendaring_datetime + * + * @return libcalendaring_datetime */ private static function toDateTime($date) { return libcalendaring_datetime::createFromFormat( 'Y-m-d\\TH:i:s', $date->format('Y-m-d\\TH:i:s'), $date->getTimezone() ); } /*** Implement PHP 5 Iterator interface to make foreach work ***/ #[\ReturnTypeWillChange] public function current() { return $this->objects[$this->iteratorkey]; } #[\ReturnTypeWillChange] public function key() { return $this->iteratorkey; } #[\ReturnTypeWillChange] public 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); } } #[\ReturnTypeWillChange] public function rewind() { $this->iteratorkey = 0; } #[\ReturnTypeWillChange] public 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/libkolab/lib/kolab_attachments_handler.php b/plugins/libkolab/lib/kolab_attachments_handler.php index b4d8be26..92453761 100644 --- a/plugins/libkolab/lib/kolab_attachments_handler.php +++ b/plugins/libkolab/lib/kolab_attachments_handler.php @@ -1,480 +1,479 @@ * @author Aleksander Machniak * * Copyright (C) 2012-2018, 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_attachments_handler { private $rc; private $attachment; public function __construct() { $this->rc = rcmail::get_instance(); } public static function ui() { $rcmail = rcmail::get_instance(); $self = new self(); $rcmail->output->add_handler('plugin.attachments_form', [$self, 'files_form']); $rcmail->output->add_handler('plugin.attachments_list', [$self, 'files_list']); $rcmail->output->add_handler('plugin.filedroparea', [$self, 'files_drop_area']); } /** * Generate HTML element for attachments list */ public function files_list($attrib = []) { if (empty($attrib['id'])) { $attrib['id'] = 'kolabattachmentlist'; } // define list of file types which can be displayed inline // same as in program/steps/mail/show.inc $this->rc->output->set_env('mimetypes', (array)$this->rc->config->get('client_mimetypes')); $this->rc->output->add_gui_object('attachmentlist', $attrib['id']); return html::tag('ul', $attrib, '', html::$common_attrib); } /** * Generate the form for event attachments upload */ public function files_form($attrib = []) { // add ID if not given if (empty($attrib['id'])) { $attrib['id'] = 'kolabuploadform'; } return $this->rc->upload_form($attrib, 'uploadform', 'upload-file', ['multiple' => true]); } /** * Register UI object for HTML5 drag & drop file upload */ public function files_drop_area($attrib = []) { // add ID if not given if (empty($attrib['id'])) { $attrib['id'] = 'kolabfiledroparea'; } $this->rc->output->add_gui_object('filedrop', $attrib['id']); $this->rc->output->set_env('filedrop', ['action' => 'upload', 'fieldname' => '_attachments']); } /** * Displays attachment preview page */ public function attachment_page($attachment) { $this->attachment = $attachment; $this->rc->plugins->include_script('libkolab/libkolab.js'); $this->rc->output->add_handler('plugin.attachmentframe', [$this, 'attachment_frame']); $this->rc->output->add_handler('plugin.attachmentcontrols', [$this, 'attachment_header']); $this->rc->output->set_env('filename', $attachment['name']); $this->rc->output->set_env('mimetype', $attachment['mimetype']); $this->rc->output->send('libkolab.attachment'); } /** * Handler for attachment uploads */ public function attachment_upload($session_key, $id_prefix = '') { // Upload progress update if (!empty($_GET['_progress'])) { $this->rc->upload_progress(); } $uploads_api = method_exists($this->rc, 'insert_uploaded_file'); // Roundcube >= 1.7 $id = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC); $uploadid = rcube_utils::get_input_value('_uploadid', rcube_utils::INPUT_GPC); $recid = $uploads_api ? $session_key : ($id_prefix . ($id ?: 'new')); if (!$uploads_api) { if (empty($_SESSION[$session_key]) || $_SESSION[$session_key]['id'] != $recid) { $_SESSION[$session_key] = []; $_SESSION[$session_key]['id'] = $recid; $_SESSION[$session_key]['attachments'] = []; } } // clear all stored output properties (like scripts and env vars) $this->rc->output->reset(); if (is_array($_FILES['_attachments']['tmp_name'])) { foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath) { // Process uploaded attachment if there is no error $err = $_FILES['_attachments']['error'][$i]; if (!$err) { $filename = $_FILES['_attachments']['name'][$i]; $attachment = [ 'path' => $filepath, 'size' => $_FILES['_attachments']['size'][$i], 'name' => $filename, 'mimetype' => rcube_mime::file_content_type($filepath, $filename, $_FILES['_attachments']['type'][$i]), 'group' => $recid, ]; if ($uploads_api) { $err = !$this->rc->insert_uploaded_file($attachment); } else { $attachment = $this->rc->plugins->exec_hook('attachment_upload', $attachment); } } if (!$err && !empty($attachment['status']) && empty($attachment['abort'])) { $id = $attachment['id']; unset($attachment['status'], $attachment['abort']); if (!$uploads_api) { // store new attachment in session $this->rc->session->append($session_key . '.attachments', $id, $attachment); } if (!empty($_SESSION[$session_key . '_deleteicon']) - && ($icon = $_SESSION[$session_key . '_deleteicon']) - && is_file($icon) + && is_file($icon = $_SESSION[$session_key . '_deleteicon']) ) { $button = html::img([ 'src' => $icon, 'alt' => $this->rc->gettext('delete'), ]); } elseif (!empty($_SESSION[$session_key . '_textbuttons'])) { $button = rcube::Q($this->rc->gettext('delete')); } else { $button = ''; } $link_content = sprintf( '%s(%s)', rcube::Q($attachment['name']), $this->rc->show_bytes($attachment['size']) ); $delete_link = html::a([ 'href' => "#delete", 'class' => 'delete', 'onclick' => sprintf("return %s.remove_from_attachment_list('rcmfile%s')", rcmail_output::JS_OBJECT_NAME, $id), 'title' => $this->rc->gettext('delete'), 'aria-label' => $this->rc->gettext('delete') . ' ' . $attachment['name'], ], $button); $content_link = html::a([ 'href' => "#load", 'class' => 'filename', 'onclick' => 'return false', // sprintf("return %s.command('load-attachment','rcmfile%s', this, event)", rcmail_output::JS_OBJECT_NAME, $id), ], $link_content); $left = !empty($_SESSION[$session_key . '_icon_pos']) && $_SESSION[$session_key . '_icon_pos'] == 'left'; $content = $left ? $delete_link . $content_link : $content_link . $delete_link; $this->rc->output->command('add2attachment_list', "rcmfile$id", [ 'html' => $content, 'name' => $attachment['name'], 'mimetype' => $attachment['mimetype'], 'classname' => 'no-menu ' . rcube_utils::file2class($attachment['mimetype'], $attachment['name']), 'complete' => true, ], $uploadid); } else { // upload failed if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) { $msg = $this->rc->gettext(['name' => 'filesizeerror', 'vars' => [ 'size' => $this->rc->show_bytes(parse_bytes(ini_get('upload_max_filesize')))]]); } elseif (!empty($attachment['error'])) { $msg = $attachment['error']; } else { $msg = $this->rc->gettext('fileuploaderror'); } $this->rc->output->command('display_message', $msg, 'error'); $this->rc->output->command('remove_from_attachment_list', $uploadid); } } } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') { // if filesize exceeds post_max_size then $_FILES array is empty, // show filesizeerror instead of fileuploaderror if ($maxsize = ini_get('post_max_size')) { $msg = $this->rc->gettext(['name' => 'filesizeerror', 'vars' => [ 'size' => $this->rc->show_bytes(parse_bytes($maxsize))]]); } else { $msg = $this->rc->gettext('fileuploaderror'); } $this->rc->output->command('display_message', $msg, 'error'); $this->rc->output->command('remove_from_attachment_list', $uploadid); } $this->rc->output->send('iframe'); } /** * Deliver an event/task attachment to the client * (similar as in Roundcube core program/steps/mail/get.inc) */ public function attachment_get($attachment) { ob_end_clean(); if ($attachment && !empty($attachment['body'])) { // allow post-processing of the attachment body $part = new rcube_message_part(); $part->filename = $attachment['name']; $part->size = $attachment['size']; $part->mimetype = $attachment['mimetype']; $plugin = $this->rc->plugins->exec_hook('message_part_get', [ 'body' => $attachment['body'], 'mimetype' => strtolower($attachment['mimetype']), 'download' => !empty($_GET['_download']), 'part' => $part, ]); if (!empty($plugin['abort'])) { exit; } $mimetype = $plugin['mimetype']; [$ctype_primary, $ctype_secondary] = explode('/', $mimetype); $browser = $this->rc->output->browser; // send download headers if ($plugin['download']) { header("Content-Type: application/octet-stream"); if ($browser->ie) { header("Content-Type: application/force-download"); } } elseif ($ctype_primary == 'text') { header("Content-Type: text/$ctype_secondary"); } else { header("Content-Type: $mimetype"); header("Content-Transfer-Encoding: binary"); } // display page, @TODO: support text/plain (and maybe some other text formats) if ($mimetype == 'text/html' && empty($_GET['_download'])) { $OUTPUT = new rcmail_html_page(); // @TODO: use washtml on $body $OUTPUT->write($plugin['body']); } else { // don't kill the connection if download takes more than 30 sec. @set_time_limit(0); $filename = $attachment['name']; $filename = preg_replace('[\r\n]', '', $filename); if ($browser->ie) { $filename = rawurlencode($filename); } else { $filename = addcslashes($filename, '"'); } $disposition = !empty($_GET['_download']) ? 'attachment' : 'inline'; header("Content-Disposition: $disposition; filename=\"$filename\""); echo $plugin['body']; } exit; } // if we arrive here, the requested part was not found header('HTTP/1.1 404 Not Found'); exit; } /** * Show "loading..." page in attachment iframe */ public function attachment_loading_page() { $url = str_replace('&_preload=1', '', $_SERVER['REQUEST_URI']); $message = $this->rc->gettext('loadingdata'); header('Content-Type: text/html; charset=' . RCUBE_CHARSET); print "\n\n" . '' . "\n" . '' . "\n" . "\n\n$message\n\n"; exit; } /** * Template object for attachment display frame */ public function attachment_frame($attrib = []) { $mimetype = strtolower($this->attachment['mimetype']); [$ctype_primary, $ctype_secondary] = explode('/', $mimetype); $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary == 'text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']); $this->rc->output->add_gui_object('attachmentframe', $attrib['id']); return html::iframe($attrib); } /** * Template object for attachment metadata */ public function attachment_header($attrib = []) { $rcmail = rcube::get_instance(); $dl_link = strtolower($attrib['downloadlink'] ?? '') == 'true'; $dl_url = $this->rc->url(['_frame' => null, '_download' => 1] + $_GET); $table = new html_table(['cols' => $dl_link ? 3 : 2]); if (!empty($this->attachment['name'])) { $table->add('title', rcube::Q($this->rc->gettext('filename'))); $table->add('header', rcube::Q($this->attachment['name'])); if ($dl_link) { $table->add('download-link', html::a($dl_url, rcube::Q($this->rc->gettext('download')))); } } if (!empty($this->attachment['mimetype'])) { $table->add('title', rcube::Q($this->rc->gettext('type'))); $table->add('header', rcube::Q($this->attachment['mimetype'])); } if (!empty($this->attachment['size'])) { $table->add('title', rcube::Q($this->rc->gettext('filesize'))); $table->add('header', rcube::Q($this->rc->show_bytes($this->attachment['size']))); } $this->rc->output->set_env('attachment_download_url', $dl_url); return $table->show($attrib); } /** * Remove uploaded attachments */ public function attachments_cleanup($session_key) { // Roundcube >= 1.7 if (method_exists($this->rc, 'delete_uploaded_files')) { $this->rc->delete_uploaded_files($session_key); } elseif (!empty($_SESSION[$session_key]) && ($group = $_SESSION[$session_key]['id'])) { $this->rc->plugins->exec_hook('attachments_cleanup', ['group' => $group]); $this->rc->session->remove($session_key); } } /** * Collect uploaded attachments */ public function attachments_set($session_key, $group, $ids = []) { $attachments = []; // Roundcube >= 1.7 if (method_exists($this->rc, 'list_uploaded_files')) { foreach ($this->rc->list_uploaded_files($session_key) as $attachment) { if (is_array($ids) && in_array($attachment['id'], $ids)) { $attachments[$attachment['id']] = $attachment; } } } elseif (!empty($_SESSION[$session_key]) && $_SESSION[$session_key]['id'] == $group) { if (!empty($_SESSION[$session_key]['attachments'])) { foreach ($_SESSION[$session_key]['attachments'] as $id => $attachment) { if (is_array($ids) && in_array($id, $ids)) { $attachments[$id] = $attachment; } } } } foreach ($attachments as $id => $attachment) { $attachments[$id] = $this->rc->plugins->exec_hook('attachment_get', $attachment); unset($attachments[$id]['abort'], $attachments[$id]['group']); } return $attachments; } /** * Register mail message attachments */ public function copy_mail_attachments($session_key, $group, $message) { $result = []; $imap = $this->rc->get_storage(); $uploads_api = method_exists($this->rc, 'insert_uploaded_file'); // Roundcube >= 1.7 if (!$uploads_api) { if (!empty($_SESSION[$session_key]) || $_SESSION[$session_key]['id'] != $group) { $_SESSION[$session_key] = [ 'id' => $group, 'attachments' => [], ]; } } foreach ((array) $message->attachments as $part) { $attachment = [ 'data' => $imap->get_message_part($message->uid, $part->mime_id, $part), 'size' => $part->size, 'name' => $part->filename, 'mimetype' => $part->mimetype, 'group' => $group, ]; if ($uploads_api) { $attachment['status'] = $this->rc->insert_uploaded_file($attachment, 'attachment_save'); } else { $attachment = $this->rc->plugins->exec_hook('attachment_save', $attachment); } if (!empty($attachment['status']) && empty($attachment['abort'])) { $id = $attachment['id']; $attachment['classname'] = rcube_utils::file2class($attachment['mimetype'], $attachment['name']); unset($attachment['status'], $attachment['abort'], $attachment['data']); if (!$uploads_api) { // store new attachment in session $_SESSION[$session_key]['attachments'][$id] = $attachment; } $attachment['id'] = 'rcmfile' . $attachment['id']; // add prefix to consider it 'new' $result[] = $attachment; } } return $result; } } diff --git a/plugins/libkolab/lib/kolab_bonnie_api.php b/plugins/libkolab/lib/kolab_bonnie_api.php index 681b40d3..c2ee6a90 100644 --- a/plugins/libkolab/lib/kolab_bonnie_api.php +++ b/plugins/libkolab/lib/kolab_bonnie_api.php @@ -1,96 +1,93 @@ * * Copyright (C) 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 kolab_bonnie_api { public $ready = false; - private $config = []; private $client = null; /** * Default constructor */ public function __construct($config) { - $this->config = $config; - $this->client = new kolab_bonnie_api_client($config['uri'], $config['timeout'] ?: 30, (bool)$config['debug']); $this->client->set_secret($config['secret']); $this->client->set_authentication($config['user'], $config['pass']); $this->client->set_request_user(rcube::get_instance()->get_user_name()); $this->ready = !empty($config['secret']) && !empty($config['user']) && !empty($config['pass']); } /** * Wrapper function for .changelog() API call */ public function changelog($type, $uid, $mailbox, $msguid = null) { return $this->client->execute($type . '.changelog', ['uid' => $uid, 'mailbox' => $mailbox, 'msguid' => $msguid]); } /** * Wrapper function for .diff() API call */ public function diff($type, $uid, $rev1, $rev2, $mailbox, $msguid = null, $instance = null) { return $this->client->execute($type . '.diff', [ 'uid' => $uid, 'rev1' => $rev1, 'rev2' => $rev2, 'mailbox' => $mailbox, 'msguid' => $msguid, 'instance' => $instance, ]); } /** * Wrapper function for .get() API call */ public function get($type, $uid, $rev, $mailbox, $msguid = null) { return $this->client->execute($type . '.get', ['uid' => $uid, 'rev' => $rev, 'mailbox' => $mailbox, 'msguid' => $msguid]); } /** * Wrapper function for .rawdata() API call */ public function rawdata($type, $uid, $rev, $mailbox, $msguid = null) { return $this->client->execute($type . '.rawdata', ['uid' => $uid, 'rev' => $rev, 'mailbox' => $mailbox, 'msguid' => $msguid]); } /** * Generic wrapper for direct API calls */ public function _execute($method, $params = []) { return $this->client->execute($method, $params); } } diff --git a/plugins/libkolab/lib/kolab_date_recurrence.php b/plugins/libkolab/lib/kolab_date_recurrence.php index d64f4250..3cd9dbe8 100644 --- a/plugins/libkolab/lib/kolab_date_recurrence.php +++ b/plugins/libkolab/lib/kolab_date_recurrence.php @@ -1,258 +1,259 @@ * * 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 { /** @var EventCal */ private $engine; /* @var kolab_format_xcal */ private $object; /** @var DateTime */ private $start; /** @var DateTime */ private $next; /** @var cDateTime */ private $cnext; /** @var DateInterval */ private $duration; /** @var bool */ private $allday; /** * Default constructor * * @param kolab_format_xcal $object The Kolab object to operate on */ public 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 $timestamp 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()) { + $cnext = new cDateTime($this->engine->getNextOccurence($this->cnext)); + if ($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 last occurence of this recurrence cycle * * @return DateTimeInterface|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 (isset($event['recurrence']['UNTIL']) && $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 for an infinite recurrence if (empty($event['recurrence']['COUNT'])) { if (!empty($event['start']) && $event['start'] instanceof DateTime) { $start_dt = clone $event['start']; $start_dt->add(new DateInterval('P100Y')); return $start_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; } // no break default: return $orig_start; } $event['start'] = $start; $event['recurrence']['INTERVAL'] = $interval; if (!empty($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([ '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 instanceof libcalendaring_datetime) { $start->_dateonly = true; } return $start; } } diff --git a/plugins/libkolab/lib/kolab_format.php b/plugins/libkolab/lib/kolab_format.php index 2d9088be..3e453458 100644 --- a/plugins/libkolab/lib/kolab_format.php +++ b/plugins/libkolab/lib/kolab_format.php @@ -1,818 +1,820 @@ * * 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 . */ abstract class kolab_format { public static $timezone; /*abstract*/ public $CTYPE; /*abstract*/ public $CTYPEv2; /*abstract*/ protected $objclass; /*abstract*/ protected $read_func; /*abstract*/ protected $write_func; protected $obj; protected $data; protected $xmldata; protected $xmlobject; protected $formaterror; protected $loaded = false; protected $version = '3.0'; public const KTYPE_PREFIX = 'application/x-vnd.kolab.'; public const PRODUCT_ID = 'Roundcube-libkolab-1.1'; // mapping table for valid PHP timezones not supported by libkolabxml // basically the entire list of ftp://ftp.iana.org/tz/data/backward protected static $timezone_map = [ 'Africa/Asmera' => 'Africa/Asmara', 'Africa/Timbuktu' => 'Africa/Abidjan', 'America/Argentina/ComodRivadavia' => 'America/Argentina/Catamarca', 'America/Atka' => 'America/Adak', 'America/Buenos_Aires' => 'America/Argentina/Buenos_Aires', 'America/Catamarca' => 'America/Argentina/Catamarca', 'America/Coral_Harbour' => 'America/Atikokan', 'America/Cordoba' => 'America/Argentina/Cordoba', 'America/Ensenada' => 'America/Tijuana', 'America/Fort_Wayne' => 'America/Indiana/Indianapolis', 'America/Indianapolis' => 'America/Indiana/Indianapolis', 'America/Jujuy' => 'America/Argentina/Jujuy', 'America/Knox_IN' => 'America/Indiana/Knox', 'America/Louisville' => 'America/Kentucky/Louisville', 'America/Mendoza' => 'America/Argentina/Mendoza', 'America/Porto_Acre' => 'America/Rio_Branco', 'America/Rosario' => 'America/Argentina/Cordoba', 'America/Virgin' => 'America/Port_of_Spain', 'Asia/Ashkhabad' => 'Asia/Ashgabat', 'Asia/Calcutta' => 'Asia/Kolkata', 'Asia/Chungking' => 'Asia/Shanghai', 'Asia/Dacca' => 'Asia/Dhaka', 'Asia/Katmandu' => 'Asia/Kathmandu', 'Asia/Macao' => 'Asia/Macau', 'Asia/Saigon' => 'Asia/Ho_Chi_Minh', 'Asia/Tel_Aviv' => 'Asia/Jerusalem', 'Asia/Thimbu' => 'Asia/Thimphu', 'Asia/Ujung_Pandang' => 'Asia/Makassar', 'Asia/Ulan_Bator' => 'Asia/Ulaanbaatar', 'Atlantic/Faeroe' => 'Atlantic/Faroe', 'Atlantic/Jan_Mayen' => 'Europe/Oslo', 'Australia/ACT' => 'Australia/Sydney', 'Australia/Canberra' => 'Australia/Sydney', 'Australia/LHI' => 'Australia/Lord_Howe', 'Australia/NSW' => 'Australia/Sydney', 'Australia/North' => 'Australia/Darwin', 'Australia/Queensland' => 'Australia/Brisbane', 'Australia/South' => 'Australia/Adelaide', 'Australia/Tasmania' => 'Australia/Hobart', 'Australia/Victoria' => 'Australia/Melbourne', 'Australia/West' => 'Australia/Perth', 'Australia/Yancowinna' => 'Australia/Broken_Hill', 'Brazil/Acre' => 'America/Rio_Branco', 'Brazil/DeNoronha' => 'America/Noronha', 'Brazil/East' => 'America/Sao_Paulo', 'Brazil/West' => 'America/Manaus', 'Canada/Atlantic' => 'America/Halifax', 'Canada/Central' => 'America/Winnipeg', 'Canada/East-Saskatchewan' => 'America/Regina', 'Canada/Eastern' => 'America/Toronto', 'Canada/Mountain' => 'America/Edmonton', 'Canada/Newfoundland' => 'America/St_Johns', 'Canada/Pacific' => 'America/Vancouver', 'Canada/Saskatchewan' => 'America/Regina', 'Canada/Yukon' => 'America/Whitehorse', 'Chile/Continental' => 'America/Santiago', 'Chile/EasterIsland' => 'Pacific/Easter', 'Cuba' => 'America/Havana', 'Egypt' => 'Africa/Cairo', 'Eire' => 'Europe/Dublin', 'Europe/Belfast' => 'Europe/London', 'Europe/Tiraspol' => 'Europe/Chisinau', 'GB' => 'Europe/London', 'GB-Eire' => 'Europe/London', 'Greenwich' => 'Etc/GMT', 'Hongkong' => 'Asia/Hong_Kong', 'Iceland' => 'Atlantic/Reykjavik', 'Iran' => 'Asia/Tehran', 'Israel' => 'Asia/Jerusalem', 'Jamaica' => 'America/Jamaica', 'Japan' => 'Asia/Tokyo', 'Kwajalein' => 'Pacific/Kwajalein', 'Libya' => 'Africa/Tripoli', 'Mexico/BajaNorte' => 'America/Tijuana', 'Mexico/BajaSur' => 'America/Mazatlan', 'Mexico/General' => 'America/Mexico_City', 'NZ' => 'Pacific/Auckland', 'NZ-CHAT' => 'Pacific/Chatham', 'Navajo' => 'America/Denver', 'PRC' => 'Asia/Shanghai', 'Pacific/Ponape' => 'Pacific/Pohnpei', 'Pacific/Samoa' => 'Pacific/Pago_Pago', 'Pacific/Truk' => 'Pacific/Chuuk', 'Pacific/Yap' => 'Pacific/Chuuk', 'Poland' => 'Europe/Warsaw', 'Portugal' => 'Europe/Lisbon', 'ROC' => 'Asia/Taipei', 'ROK' => 'Asia/Seoul', 'Singapore' => 'Asia/Singapore', 'Turkey' => 'Europe/Istanbul', 'UCT' => 'Etc/UCT', 'US/Alaska' => 'America/Anchorage', 'US/Aleutian' => 'America/Adak', 'US/Arizona' => 'America/Phoenix', 'US/Central' => 'America/Chicago', 'US/East-Indiana' => 'America/Indiana/Indianapolis', 'US/Eastern' => 'America/New_York', 'US/Hawaii' => 'Pacific/Honolulu', 'US/Indiana-Starke' => 'America/Indiana/Knox', 'US/Michigan' => 'America/Detroit', 'US/Mountain' => 'America/Denver', 'US/Pacific' => 'America/Los_Angeles', 'US/Samoa' => 'Pacific/Pago_Pago', 'Universal' => 'Etc/UTC', 'W-SU' => 'Europe/Moscow', 'Zulu' => 'Etc/UTC', ]; /** * Factory method to instantiate a kolab_format object of the given type and version * * @param string $type Object type to instantiate * @param string $version Format version * @param string $xmldata Cached xml data to initialize with * - * @return kolab_format + * @return kolab_format|PEAR_Error */ public static function factory($type, $version = '3.0', $xmldata = null) { if (!isset(self::$timezone)) { self::$timezone = new DateTimeZone('UTC'); } if (!self::supports($version)) { + // @phpstan-ignore-next-line return PEAR::raiseError("No support for Kolab format version " . $version); } $type = preg_replace('/configuration\.[a-z._]+$/', 'configuration', $type); $suffix = preg_replace('/[^a-z]+/', '', $type); $classname = 'kolab_format_' . $suffix; if (class_exists($classname)) { return new $classname($xmldata, $version); } + // @phpstan-ignore-next-line return PEAR::raiseError("Failed to load Kolab Format wrapper for type " . $type); } /** * Determine support for the given format version * * @param float $version Format version to check * * @return bool True if supported, False otherwise */ public static function supports($version) { if ($version == '2.0') { return class_exists('kolabobject'); } // default is version 3 return class_exists('kolabformat'); } /** * Convert the given date/time value into a cDateTime object * * @param mixed $datetime Date/Time value either as unix timestamp, date string or PHP DateTime object * @param DateTimeZone $tz The timezone the date/time is in. Use global default if Null, local time if False * @param bool $dateonly True of the given date has no time component * @param DateTimeZone $dest_tz The timezone to convert the date to before converting to cDateTime * * @return cDateTime The libkolabxml date/time object */ public static function get_datetime($datetime, $tz = null, $dateonly = false, $dest_tz = null) { // use timezone information from datetime or global setting if (!$tz && $tz !== false) { if ($datetime instanceof DateTimeInterface) { $tz = $datetime->getTimezone(); } if (!$tz) { $tz = self::$timezone; } } $result = new cDateTime(); try { // got a unix timestamp (in UTC) if (is_numeric($datetime)) { $datetime = new libcalendaring_datetime('@' . $datetime, new DateTimeZone('UTC')); if ($tz) { $datetime->setTimezone($tz); } } elseif (is_string($datetime) && strlen($datetime)) { $datetime = $tz ? new libcalendaring_datetime($datetime, $tz) : new libcalendaring_datetime($datetime); } elseif ($datetime instanceof DateTimeInterface) { $datetime = clone $datetime; } } catch (Exception $e) { } if ($datetime instanceof DateTimeInterface) { if ($dest_tz instanceof DateTimeZone && $dest_tz !== $datetime->getTimezone() && method_exists($datetime, 'setTimezone') ) { $datetime->setTimezone($dest_tz); $tz = $dest_tz; } $result->setDate($datetime->format('Y'), $datetime->format('n'), $datetime->format('j')); if ($dateonly) { // Dates should be always in local time only return $result; } $result->setTime($datetime->format('G'), $datetime->format('i'), $datetime->format('s')); // libkolabxml throws errors on some deprecated timezone names $utc_aliases = ['UTC', 'GMT', '+00:00', 'Z', 'Etc/GMT', 'Etc/UTC']; if ($tz && in_array($tz->getName(), $utc_aliases)) { $result->setUTC(true); } elseif ($tz !== false) { $tzid = $tz->getName(); if (array_key_exists($tzid, self::$timezone_map)) { $tzid = self::$timezone_map[$tzid]; } $result->setTimezone($tzid); } } return $result; } /** * Convert the given cDateTime into a PHP DateTime object * * @param cDateTime $cdt The libkolabxml datetime object * @param DateTimeZone $dest_tz The timezone to convert the date to * * @return libcalendaring_datetime|null PHP datetime instance, Null on invalid input */ public static function php_datetime($cdt, $dest_tz = null) { if (!is_object($cdt) || !$cdt->isValid()) { return null; } $d = new libcalendaring_datetime(null, self::$timezone); if ($dest_tz) { $d->setTimezone($dest_tz); } else { try { if ($tzs = $cdt->timezone()) { $tz = new DateTimeZone($tzs); $d->setTimezone($tz); } elseif ($cdt->isUTC()) { $d->setTimezone(new DateTimeZone('UTC')); } } catch (Exception $e) { } } $d->setDate($cdt->year(), $cdt->month(), $cdt->day()); if ($cdt->isDateOnly()) { $d->_dateonly = true; $d->setTime(12, 0, 0); // set time to noon to avoid timezone troubles } else { $d->setTime($cdt->hour(), $cdt->minute(), $cdt->second()); } return $d; } /** * Convert a libkolabxml vector to a PHP array * * @param vector $vec Object * @param int $max Max vector size * * @return array Indexed array containing vector elements */ public static function vector2array($vec, $max = PHP_INT_MAX) { $arr = []; for ($i = 0; $i < $vec->size() && $i < $max; $i++) { $arr[] = $vec->get($i); } return $arr; } /** * Build a libkolabxml vector (string) from a PHP array * * @param array $arr Array with vector elements * * @return vectors */ public static function array2vector($arr) { $vec = new vectors(); foreach ((array)$arr as $val) { if (strlen($val)) { $vec->push($val); } } return $vec; } /** * Parse the X-Kolab-Type header from MIME messages and return the object type in short form * * @param string $type X-Kolab-Type header value * * @return string Kolab object type (contact,event,task,note,etc.) */ public static function mime2object_type($type) { return preg_replace( ['/dictionary.[a-z.]+$/', '/contact.distlist$/'], [ 'dictionary', 'distribution-list'], substr($type, strlen(self::KTYPE_PREFIX)) ); } /** * Default constructor of all kolab_format_* objects */ public function __construct($xmldata = null, $version = null) { $this->obj = new $this->objclass(); $this->xmldata = $xmldata; if ($version) { $this->version = $version; } // use libkolab module if available if (class_exists('kolabobject')) { $this->xmlobject = new XMLObject(); } } /** * Check for format errors after calling kolabformat::write*() * * @return bool True if there were errors, False if OK */ protected function format_errors() { $ret = $log = false; switch (kolabformat::error()) { case kolabformat::NoError: $ret = false; break; case kolabformat::Warning: $ret = false; $uid = is_object($this->obj) ? $this->obj->uid() : $this->data['uid']; $log = "Warning @ $uid"; break; default: $ret = true; $log = "Error"; } if ($log && !isset($this->formaterror)) { rcube::raise_error([ 'code' => 660, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "kolabformat $log: " . kolabformat::errorMessage(), ], true); $this->formaterror = $ret; } return $ret; } /** * Save the last generated UID to the object properties. * Should be called after kolabformat::writeXXXX(); */ protected function update_uid() { // get generated UID if (empty($this->data['uid'])) { if ($this->xmlobject) { $this->data['uid'] = $this->xmlobject->getSerializedUID(); } if (empty($this->data['uid'])) { $this->data['uid'] = kolabformat::getSerializedUID(); } $this->obj->setUid($this->data['uid']); } } /** * Initialize libkolabxml object with cached xml data */ protected function init() { if (!$this->loaded) { if ($this->xmldata) { $this->load($this->xmldata); $this->xmldata = null; } $this->loaded = true; } } /** * Get constant value for libkolab's version parameter * * @param float $v Version value to convert * * @return int|false Constant value of either kolabobject::KolabV2 or kolabobject::KolabV3 or false if kolabobject module isn't available */ protected function libversion($v = null) { if (class_exists('kolabobject')) { $version = $v ?: $this->version; if ($version <= '2.0') { return kolabobject::KolabV2; } else { return kolabobject::KolabV3; } } return false; } /** * Determine the correct libkolab(xml) wrapper function for the given call * depending on the available PHP modules */ protected function libfunc($func) { if (is_array($func) || strpos($func, '::')) { return $func; } elseif (class_exists('kolabobject')) { return [$this->xmlobject, $func]; } else { return 'kolabformat::' . $func; } } /** * Direct getter for object properties */ public function __get($var) { return $this->data[$var]; } /** * Load Kolab object data from the given XML block * * @param string $xml XML data */ public function load($xml) { $this->formaterror = null; $read_func = $this->libfunc($this->read_func); if (is_array($read_func)) { $r = call_user_func($read_func, $xml, $this->libversion()); } else { $r = call_user_func($read_func, $xml, false); } if (is_resource($r)) { $this->obj = new $this->objclass($r); } elseif (is_a($r, $this->objclass)) { $this->obj = $r; } $this->loaded = !$this->format_errors(); } /** * Write object data to XML format * * @param float $version Format version to write * * @return string XML data */ public function write($version = null) { $this->formaterror = null; $this->init(); $write_func = $this->libfunc($this->write_func); if (is_array($write_func)) { $this->xmldata = call_user_func($write_func, $this->obj, $this->libversion($version), self::PRODUCT_ID); } else { $this->xmldata = call_user_func($write_func, $this->obj, self::PRODUCT_ID); } if (!$this->format_errors()) { $this->update_uid(); } else { $this->xmldata = null; } return $this->xmldata; } /** * Set properties to the kolabformat object * * @param array $object Object data as hash array */ public function set(&$object) { $this->init(); if (!empty($object['uid'])) { $this->obj->setUid($object['uid']); } // set some automatic values if missing if (method_exists($this->obj, 'setCreated')) { // Always set created date to workaround libkolabxml (>1.1.4) bug $created = !empty($object['created']) ? $object['created'] : new DateTime('now'); $created->setTimezone(new DateTimeZone('UTC')); // must be UTC $this->obj->setCreated(self::get_datetime($created)); $object['created'] = $created; } $object['changed'] = new DateTime('now', new DateTimeZone('UTC')); $this->obj->setLastModified(self::get_datetime($object['changed'])); // Save custom properties of the given object if (isset($object['x-custom']) && method_exists($this->obj, 'setCustomProperties')) { $vcustom = new vectorcs(); foreach ((array)$object['x-custom'] as $cp) { if (is_array($cp)) { $vcustom->push(new CustomProperty($cp[0], $cp[1])); } } $this->obj->setCustomProperties($vcustom); } // load custom properties from XML for caching (#2238) if method exists (#3125) elseif (method_exists($this->obj, 'customProperties')) { $object['x-custom'] = []; $vcustom = $this->obj->customProperties(); for ($i = 0; $i < $vcustom->size(); $i++) { $cp = $vcustom->get($i); $object['x-custom'][] = [$cp->identifier, $cp->value]; } } } /** * Convert the Kolab object into a hash array data structure * * @param array $data Additional data for merge * * @return array Kolab object data as hash array */ public function to_array($data = []) { $this->init(); // read object properties into local data object $object = [ 'uid' => $this->obj->uid(), 'changed' => self::php_datetime($this->obj->lastModified()), ]; // not all container support the created property if (method_exists($this->obj, 'created')) { $object['created'] = self::php_datetime($this->obj->created()); } // read custom properties if (method_exists($this->obj, 'customProperties')) { $vcustom = $this->obj->customProperties(); for ($i = 0; $i < $vcustom->size(); $i++) { $cp = $vcustom->get($i); $object['x-custom'][] = [$cp->identifier, $cp->value]; } } // merge with additional data, e.g. attachments from the message if ($data) { foreach ($data as $idx => $value) { if (is_array($value)) { $object[$idx] = array_merge((array)($object[$idx] ?? []), $value); } else { $object[$idx] = $value; } } } return $object; } /** * Object validation method to be implemented by derived classes */ abstract public function is_valid(); /** * Callback for kolab_storage_cache to get object specific tags to cache * * @return array List of tags to save in cache */ public function get_tags() { return []; } /** * Callback for kolab_storage_cache to get words to index for fulltext search * * @return array List of words to save in cache */ public function get_words() { return []; } /** * Utility function to extract object attachment data * * @param array $object Hash array reference to append attachment data into */ public function get_attachments(&$object, $all = false) { $this->init(); // handle attachments $vattach = $this->obj->attachments(); for ($i = 0; $i < $vattach->size(); $i++) { $attach = $vattach->get($i); // skip cid: attachments which are mime message parts handled by kolab_storage_folder if (substr($attach->uri(), 0, 4) != 'cid:' && $attach->label()) { $name = $attach->label(); $key = $name . (isset($object['_attachments'][$name]) ? '.' . $i : ''); $content = $attach->data(); $object['_attachments'][$key] = [ 'id' => 'i:' . $i, 'name' => $name, 'mimetype' => $attach->mimetype(), 'size' => strlen($content), 'content' => $content, ]; } elseif ($all && substr($attach->uri(), 0, 4) == 'cid:') { $key = $attach->uri(); $object['_attachments'][$key] = [ 'id' => $key, 'name' => $attach->label(), 'mimetype' => $attach->mimetype(), ]; } elseif (in_array(substr($attach->uri(), 0, 4), ['http','imap'])) { $object['links'][] = $attach->uri(); } } } /** * Utility function to set attachment properties to the kolabformat object * * @param array $object Object data as hash array * @param bool $write True to always overwrite attachment information */ protected function set_attachments($object, $write = true) { // save attachments $vattach = new vectorattachment(); foreach ((array)($object['_attachments'] ?? []) as $cid => $attr) { if (empty($attr)) { continue; } $attach = new Attachment(); $attach->setLabel((string)$attr['name']); $attach->setUri('cid:' . $cid, $attr['mimetype'] ?: 'application/octet-stream'); if ($attach->isValid()) { $vattach->push($attach); $write = true; } else { rcube::raise_error([ 'code' => 660, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Invalid attributes for attachment $cid: " . var_export($attr, true), ], true); } } foreach ((array)($object['links'] ?? []) as $link) { $attach = new Attachment(); $attach->setUri($link, 'unknown'); $vattach->push($attach); $write = true; } if ($write) { $this->obj->setAttachments($vattach); } } /** * Unified way of updating/deleting attachments of edited object * * @param array $object Kolab object data * @param array $old Old version of Kolab object */ public static function merge_attachments(&$object, $old) { $object['_attachments'] = isset($old['_attachments']) && is_array($old['_attachments']) ? $old['_attachments'] : []; // delete existing attachment(s) if (!empty($object['deleted_attachments'])) { foreach ($object['_attachments'] as $idx => $att) { if ($object['deleted_attachments'] === true || in_array($att['id'], $object['deleted_attachments'])) { $object['_attachments'][$idx] = false; } } } // in kolab_storage attachments are indexed by content-id foreach ((array) ($object['attachments'] ?? []) as $attachment) { $key = null; // Roundcube ID has nothing to do with the storage ID, remove it // for uploaded/new attachments // FIXME: Roundcube uses 'data', kolab_format uses 'content' if (!empty($attachment['content']) || !empty($attachment['path']) || !empty($attachment['data'])) { unset($attachment['id']); } if (!empty($attachment['id'])) { foreach ((array) $object['_attachments'] as $cid => $att) { if ($att && $attachment['id'] == $att['id']) { $key = $cid; } } } else { // find attachment by name, so we can update it if exists // and make sure there are no duplicates foreach ($object['_attachments'] as $cid => $att) { if ($att && $attachment['name'] == $att['name']) { $key = $cid; } } } if ($key && $attachment['_deleted']) { $object['_attachments'][$key] = false; } // replace existing entry elseif ($key) { $object['_attachments'][$key] = $attachment; } // append as new attachment else { $object['_attachments'][] = $attachment; } } unset($object['attachments']); unset($object['deleted_attachments']); } } diff --git a/plugins/libkolab/lib/kolab_format_event.php b/plugins/libkolab/lib/kolab_format_event.php index 1cb2f5da..a69901d1 100644 --- a/plugins/libkolab/lib/kolab_format_event.php +++ b/plugins/libkolab/lib/kolab_format_event.php @@ -1,331 +1,331 @@ * * 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 kolab_format_event extends kolab_format_xcal { public $CTYPEv2 = 'application/x-vnd.kolab.event'; public static $scheduling_properties = ['start', 'end', 'allday', 'recurrence', 'location', 'status', 'cancelled']; protected $objclass = 'Event'; protected $read_func = 'readEvent'; protected $write_func = 'writeEvent'; /** * Default constructor */ public function __construct($data = null, $version = 3.0) { parent::__construct(is_string($data) ? $data : null, $version); // got an Event object as argument if (is_object($data) && is_a($data, $this->objclass)) { $this->obj = $data; $this->loaded = true; } // copy static property overriden by this class $this->_scheduling_properties = self::$scheduling_properties; } /** * Set event properties to the kolabformat object * * @param array $object Event data as hash array */ public function set(&$object) { // set common xcal properties parent::set($object); // do the hard work of setting object values $this->obj->setStart(self::get_datetime($object['start'], null, !empty($object['allday']))); $this->obj->setEnd(self::get_datetime($object['end'], null, !empty($object['allday']))); $this->obj->setTransparency(!empty($object['free_busy']) && $object['free_busy'] == 'free'); $status = kolabformat::StatusUndefined; if (!empty($object['free_busy']) && $object['free_busy'] == 'tentative') { $status = kolabformat::StatusTentative; } if (!empty($object['cancelled'])) { $status = kolabformat::StatusCancelled; } elseif (!empty($object['status']) && array_key_exists($object['status'], $this->status_map)) { $status = $this->status_map[$object['status']]; } $this->obj->setStatus($status); // save (recurrence) exceptions if (!empty($object['recurrence']['EXCEPTIONS']) && !isset($object['exceptions'])) { $object['exceptions'] = $object['recurrence']['EXCEPTIONS']; } $recurrence_id_format = libkolab::recurrence_id_format($object); $vexceptions = new vectorevent(); foreach (($object['exceptions'] ?? []) as $i => $exception) { $exevent = new kolab_format_event(); $compacted = $this->compact_exception($exception, $object); $exevent->set($compacted); // only save differing values // get value for recurrence-id $recurrence_id = null; if (!empty($exception['recurrence_date']) && $exception['recurrence_date'] instanceof DateTimeInterface) { $recurrence_id = $exception['recurrence_date']; $compacted['_instance'] = $recurrence_id->format($recurrence_id_format); } elseif (!empty($exception['_instance']) && strlen($exception['_instance']) > 4) { $recurrence_id = rcube_utils::anytodatetime($exception['_instance'], $object['start']->getTimezone()); $compacted['recurrence_date'] = $recurrence_id; } $ex_dt = self::get_datetime($recurrence_id ?: $exception['start'], null, !empty($object['allday'])); $exevent->obj->setRecurrenceID($ex_dt, !empty($exception['thisandfuture'])); $vexceptions->push($exevent->obj); // write cleaned-up exception data back to memory/cache $object['exceptions'][$i] = $this->expand_exception($exevent->data, $object); $object['exceptions'][$i]['_instance'] = $compacted['_instance']; } $this->obj->setExceptions($vexceptions); // link with recurrence.EXCEPTIONS for compatibility if (isset($object['exceptions']) && is_array($object['recurrence'] ?? null)) { $object['recurrence']['EXCEPTIONS'] = &$object['exceptions']; } if (!empty($object['recurrence_date']) && $object['recurrence_date'] instanceof DateTimeInterface) { if (!empty($object['recurrence'])) { // unset recurrence_date for master events with rrule $object['recurrence_date'] = null; } $recid = self::get_datetime($object['recurrence_date'], null, !empty($object['allday'])); $this->obj->setRecurrenceID($recid, !empty($object['thisandfuture'])); } // cache this data $this->data = $object; unset($this->data['_formatobj']); } /** * */ public function is_valid() { return !$this->formaterror && (($this->data && !empty($this->data['start']) && !empty($this->data['end'])) || (is_object($this->obj) && $this->obj->isValid() && $this->obj->uid())); } /** * Convert the Event object into a hash array data structure * * @param array $data Additional data for merge * * @return array Event data as hash array */ public function to_array($data = []) { // return cached result if (!empty($this->data)) { return $this->data; } // read common xcal props $object = parent::to_array($data); // read object properties $object += [ 'end' => self::php_datetime($this->obj->end()), 'allday' => $this->obj->start()->isDateOnly(), 'free_busy' => $this->obj->transparency() ? 'free' : 'busy', // TODO: transparency is only boolean 'attendees' => [], ]; // derive event end from duration (#1916) if (!$object['end'] && $object['start'] && ($duration = $this->obj->duration()) && $duration->isValid()) { $interval = new DateInterval('PT0S'); $interval->d = $duration->weeks() * 7 + $duration->days(); $interval->h = $duration->hours(); $interval->i = $duration->minutes(); $interval->s = $duration->seconds(); $object['end'] = clone $object['start']; $object['end']->add($interval); } // make sure end date is specified (#5307) RFC5545 3.6.1 elseif (!$object['end'] && $object['start']) { $object['end'] = clone $object['start']; } // organizer is part of the attendees list in Roundcube if (!empty($object['organizer'])) { $object['organizer']['role'] = 'ORGANIZER'; array_unshift($object['attendees'], $object['organizer']); } // status defines different event properties... $status = $this->obj->status(); if ($status == kolabformat::StatusTentative) { $object['free_busy'] = 'tentative'; } elseif ($status == kolabformat::StatusCancelled) { $object['cancelled'] = true; } // this is an exception object if ($this->obj->recurrenceID()->isValid()) { $object['thisandfuture'] = $this->obj->thisAndFuture(); $object['recurrence_date'] = self::php_datetime($this->obj->recurrenceID()); } // read exception event objects if (($exceptions = $this->obj->exceptions()) && is_object($exceptions) && $exceptions->size()) { $recurrence_exceptions = []; $recurrence_id_format = libkolab::recurrence_id_format($object); for ($i = 0; $i < $exceptions->size(); $i++) { if (($exobj = $exceptions->get($i))) { $exception = new kolab_format_event($exobj); if ($exception->is_valid()) { $exdata = $exception->to_array(); // fix date-only recurrence ID saved by old versions if ($exdata['recurrence_date'] && $exdata['recurrence_date']->_dateonly && !$object['allday']) { $exdata['recurrence_date']->setTimezone($object['start']->getTimezone()); $exdata['recurrence_date']->setTime($object['start']->format('G'), intval($object['start']->format('i')), intval($object['start']->format('s'))); } $recurrence_id = $exdata['recurrence_date'] ?: $exdata['start']; $exdata['_instance'] = $recurrence_id->format($recurrence_id_format); $recurrence_exceptions[] = $this->expand_exception($exdata, $object); } } } $object['exceptions'] = $recurrence_exceptions; // also link with recurrence.EXCEPTIONS for compatibility - if (!empty($object['recurrence']) && isset($object['exceptions'])) { + if (!empty($object['recurrence'])) { $object['recurrence']['EXCEPTIONS'] = &$object['exceptions']; } } return $this->data = $object; } /** * Getter for a single instance from a recurrence series or stored subcomponents * * @param mixed $recurrence_id The recurrence-id of the requested instance, either as string or a DateTime object * * @return array Event data as hash array or null if not found */ public function get_instance($recurrence_id) { $result = null; $object = $this->to_array(); $recurrence_id_format = libkolab::recurrence_id_format($object); $instance_id = $recurrence_id instanceof DateTimeInterface ? $recurrence_id->format($recurrence_id_format) : strval($recurrence_id); if (!empty($object['recurrence_date']) && $object['recurrence_date'] instanceof DateTimeInterface) { if ($object['recurrence_date']->format($recurrence_id_format) == $instance_id) { $result = $object; } } if (!$result && !empty($object['exceptions']) && is_array($object['exceptions'])) { foreach ($object['exceptions'] as $exception) { if ($exception['_instance'] == $instance_id) { $result = $exception; $result['isexception'] = 1; break; } } } // TODO: compute instances from recurrence rule and return the matching instance // clone from plugins/calendar/drivers/kolab/kolab_calendar::get_recurring_events() return $result; } /** * Callback for kolab_storage_cache to get object specific tags to cache * * @return array List of tags to save in cache */ public function get_tags($obj = null) { $tags = parent::get_tags($obj); $object = $obj ?: $this->data; foreach ((array) ($object['categories'] ?? []) as $cat) { $tags[] = rcube_utils::normalize_string($cat); } return array_unique($tags); } /** * Remove some attributes from the exception container */ private function compact_exception($exception, $master) { $forbidden = ['recurrence','exceptions','organizer','_attachments']; foreach ($forbidden as $prop) { if (array_key_exists($prop, $exception)) { unset($exception[$prop]); } } // preserve this property for date serialization if (!isset($exception['allday'])) { $exception['allday'] = !empty($master['allday']); } return $exception; } /** * Copy attributes not specified by the exception from the master event */ private function expand_exception($exception, $master) { // Note: If an exception has no attendees it means there's "no attendees // for this occurrence", not "attendees are the same as in the event" (#5300) $forbidden = ['exceptions', 'attendees', 'allday']; $is_recurring = !empty($master['recurrence']); foreach ($master as $prop => $value) { if (empty($exception[$prop]) && !empty($value) && $prop[0] != '_' && !in_array($prop, $forbidden) && ($is_recurring || in_array($prop, ['uid','organizer'])) ) { $exception[$prop] = $value; if ($prop == 'recurrence') { unset($exception[$prop]['EXCEPTIONS']); } } } return $exception; } } diff --git a/plugins/libkolab/lib/kolab_ldap.php b/plugins/libkolab/lib/kolab_ldap.php index 0ce9e408..195c9d1e 100644 --- a/plugins/libkolab/lib/kolab_ldap.php +++ b/plugins/libkolab/lib/kolab_ldap.php @@ -1,611 +1,610 @@ * * Copyright (C) 2011-2019, 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 . */ /** * Wrapper class for rcube_ldap_generic */ class kolab_ldap extends rcube_ldap_generic { private $conf = []; private $debug = false; private $fieldmap = []; private $parse_replaces = []; - private $rcache; private $ready = false; public function __construct($p) { $rcmail = rcube::get_instance(); $this->conf = $p; $this->conf['kolab_auth_user_displayname'] = $rcmail->config->get('kolab_auth_user_displayname', '{name}'); $this->fieldmap = $p['fieldmap']; $this->fieldmap['uid'] = 'uid'; $p['attributes'] = array_values($this->fieldmap); $p['debug'] = (bool) $rcmail->config->get('ldap_debug'); if ($cache_type = $rcmail->config->get('ldap_cache', 'db')) { $cache_ttl = $rcmail->config->get('ldap_cache_ttl', '10m'); $this->cache = $rcmail->get_cache('LDAP.kolab_cache', $cache_type, $cache_ttl); } $this->debug = $p['debug']; // Connect to the server (with bind) parent::__construct($p); $this->_connect(); $rcmail->add_shutdown_function([$this, 'close']); } /** * Establish a connection to the LDAP server */ private function _connect() { // try to connect + bind for every host configured // with OpenLDAP 2.x ldap_connect() always succeeds but ldap_bind will fail if host isn't reachable // see http://www.php.net/manual/en/function.ldap-connect.php foreach ((array)$this->config['hosts'] as $host) { // skip host if connection failed if (!$this->connect($host)) { continue; } $bind_pass = $this->config['bind_pass'] ?? null; $bind_user = $this->config['bind_user'] ?? null; $bind_dn = $this->config['bind_dn']; $base_dn = $this->config['base_dn']; $groups_base_dn = $this->config['groups']['base_dn'] ?: $base_dn; // User specific access, generate the proper values to use. if ($this->config['user_specific']) { $rcube = rcube::get_instance(); // No password set, use the session password if (empty($bind_pass)) { $bind_pass = $rcube->get_user_password(); } $u = null; // Get the pieces needed for variable replacement. if ($fu = ($rcube->get_user_email() ?: ($this->config['username'] ?? null))) { [$u, $d] = explode('@', $fu); } else { $d = $this->config['mail_domain'] ?? null; } $dc = 'dc=' . strtr($d, ['.' => ',dc=']); // hierarchal domain string // resolve $dc through LDAP if (!empty($this->config['domain_filter']) && !empty($this->config['search_bind_dn'])) { $this->bind($this->config['search_bind_dn'], $this->config['search_bind_pw']); $dc = $this->domain_root_dn($d); } $replaces = ['%dn' => '', '%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u]; // Search for the dn to use to authenticate if (($this->config['search_base_dn'] ?? false) && ($this->config['search_filter'] ?? false) && (strstr($bind_dn, '%dn') || strstr($base_dn, '%dn') || strstr($groups_base_dn, '%dn')) ) { $search_attribs = ['uid']; if ($search_bind_attrib = (array) $this->config['search_bind_attrib']) { foreach ($search_bind_attrib as $r => $attr) { $search_attribs[] = $attr; $replaces[$r] = ''; } } $search_bind_dn = strtr($this->config['search_bind_dn'], $replaces); $search_base_dn = strtr($this->config['search_base_dn'], $replaces); $search_filter = strtr($this->config['search_filter'], $replaces); $cache_key = 'DN.' . md5("$host:$search_bind_dn:$search_base_dn:$search_filter:" . $this->config['search_bind_pw']); if ($this->cache && ($dn = $this->cache->get($cache_key))) { $replaces['%dn'] = $dn; } else { $ldap = $this; if (!empty($search_bind_dn) && !empty($this->config['search_bind_pw'])) { // To protect from "Critical extension is unavailable" error // we need to use a separate LDAP connection if (!empty($this->config['vlv'])) { $ldap = new rcube_ldap_generic($this->config); $ldap->config_set(['cache' => $this->cache, 'debug' => $this->debug]); if (!$ldap->connect($host)) { continue; } } if (!$ldap->bind($search_bind_dn, $this->config['search_bind_pw'])) { continue; // bind failed, try next host } } $res = $ldap->search($search_base_dn, $search_filter, 'sub', $search_attribs); if ($res) { $res->rewind(); $replaces['%dn'] = key($res->entries(true)); // add more replacements from 'search_bind_attrib' config if ($search_bind_attrib) { $res = $res->current(); foreach ($search_bind_attrib as $r => $attr) { $replaces[$r] = $res[$attr][0]; } } } if ($ldap != $this) { $ldap->close(); } } // DN not found if (empty($replaces['%dn'])) { if (!empty($this->config['search_dn_default'])) { $replaces['%dn'] = $this->config['search_dn_default']; } else { rcube::raise_error([ 'code' => 100, 'type' => 'ldap', 'file' => __FILE__, 'line' => __LINE__, 'message' => "DN not found using LDAP search."], true); continue; } } if ($this->cache && !empty($replaces['%dn'])) { $this->cache->set($cache_key, $replaces['%dn']); } } // Replace the bind_dn and base_dn variables. $bind_dn = strtr($bind_dn, $replaces); $base_dn = strtr($base_dn, $replaces); $groups_base_dn = strtr($groups_base_dn, $replaces); // replace placeholders in filter settings if (!empty($this->config['filter'])) { $this->config['filter'] = strtr($this->config['filter'], $replaces); } foreach (['base_dn', 'filter', 'member_filter'] as $k) { if (!empty($this->config['groups'][$k])) { $this->config['groups'][$k] = strtr($this->config['groups'][$k], $replaces); } } if (empty($bind_user)) { $bind_user = $u; } } if (empty($bind_pass)) { $this->ready = true; } else { if (!empty($this->config['auth_cid'])) { $this->ready = $this->sasl_bind($this->config['auth_cid'], $bind_pass, $bind_dn); } elseif (!empty($bind_dn)) { $this->ready = $this->bind($bind_dn, $bind_pass); } else { $this->ready = $this->sasl_bind($bind_user, $bind_pass); } } // connection established, we're done here if ($this->ready) { break; } } // end foreach hosts if (!is_resource($this->conn)) { rcube::raise_error(['code' => 100, 'type' => 'ldap', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Could not connect to any LDAP server"], true); $this->ready = false; } return $this->ready; } /** * Fetches user data from LDAP addressbook */ public function get_user_record($user, $host) { $rcmail = rcube::get_instance(); $filter = $rcmail->config->get('kolab_auth_filter'); $filter = $this->parse_vars($filter, $user, $host); $base_dn = $this->parse_vars($this->config['base_dn'], $user, $host); $scope = $this->config['scope']; // @TODO: print error if filter is empty // get record if ($result = parent::search($base_dn, $filter, $scope, $this->attributes)) { if ($result->count() == 1) { $entries = $result->entries(true); $dn = key($entries); $entry = array_pop($entries); $entry = $this->field_mapping($dn, $entry); return $entry; } } } /** * Fetches user data from LDAP addressbook */ public function get_user_groups($dn, $user, $host) { if (empty($dn) || empty($this->config['groups'])) { return []; } $base_dn = $this->parse_vars($this->config['groups']['base_dn'], $user, $host); $name_attr = $this->config['groups']['name_attr'] ? $this->config['groups']['name_attr'] : 'cn'; $member_attr = $this->get_group_member_attr(); $filter = "(member=$dn)(uniqueMember=$dn)"; if ($member_attr != 'member' && $member_attr != 'uniqueMember') { $filter .= "($member_attr=$dn)"; } $filter = strtr("(|$filter)", ["\\" => "\\\\"]); $result = parent::search($base_dn, $filter, 'sub', ['dn', $name_attr]); if (!$result) { return []; } $groups = []; foreach ($result as $entry) { $dn = $entry['dn']; $entry = rcube_ldap_generic::normalize_entry($entry); $groups[$dn] = $entry[$name_attr]; } return $groups; } /** * Get a specific LDAP record * * @param string $dn DN * * @return array|null Record data */ public function get_record($dn) { if (!$this->ready) { return null; } if ($rec = $this->get_entry($dn, $this->attributes)) { $rec = rcube_ldap_generic::normalize_entry($rec); $rec = $this->field_mapping($dn, $rec); } return $rec; } /** * Replace LDAP record data items * * @param string $dn DN * @param array $entry LDAP entry * * return bool True on success, False on failure */ public function replace($dn, $entry) { // fields mapping foreach ($this->fieldmap as $field => $attr) { if (array_key_exists($field, $entry)) { $entry[$attr] = $entry[$field]; if ($attr != $field) { unset($entry[$field]); } } } return $this->mod_replace($dn, $entry); } /** * Search records (simplified version of rcube_ldap::search) * * @param mixed $fields The field name or array of field names to search in * @param string $value Search value * @param int $mode Matching mode: * 0 - partial (*abc*), * 1 - strict (=), * 2 - prefix (abc*) * @param array $required List of fields that cannot be empty * @param int $limit Number of records * @param int $count Returns the number of records found * * @return array List of LDAP records found */ public function dosearch($fields, $value, $mode = 1, $required = [], $limit = 0, &$count = 0) { if (empty($fields)) { return []; } $mode = intval($mode); // try to resolve field names into ldap attributes $fieldmap = $this->fieldmap; $attrs = array_map(function ($f) use ($fieldmap) { return array_key_exists($f, $fieldmap) ? $fieldmap[$f] : $f; }, (array)$fields); // compose a full-text-search-like filter if (count($attrs) > 1 || $mode != 1) { $filter = self::fulltext_search_filter($value, $attrs, $mode); } // direct search else { $field = $attrs[0]; $filter = "($field=" . self::quote_string($value) . ")"; } // add required (non empty) fields filter $req_filter = ''; foreach ((array)$required as $field) { $attr = array_key_exists($field, $this->fieldmap) ? $this->fieldmap[$field] : $field; // only add if required field is not already in search filter if (!in_array($attr, $attrs)) { $req_filter .= "($attr=*)"; } } if (!empty($req_filter)) { $filter = '(&' . $req_filter . $filter . ')'; } // avoid double-wildcard if $value is empty $filter = preg_replace('/\*+/', '*', $filter); // add general filter to query if (!empty($this->config['filter'])) { $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->config['filter']) . ')' . $filter . ')'; } $base_dn = $this->parse_vars($this->config['base_dn']); $scope = $this->config['scope']; $attrs = array_values($this->fieldmap); $list = []; if ($result = $this->search($base_dn, $filter, $scope, $attrs)) { $count = $result->count(); $i = 0; foreach ($result as $entry) { if ($limit && $limit <= $i) { break; } $dn = $entry['dn']; $entry = rcube_ldap_generic::normalize_entry($entry); $list[$dn] = $this->field_mapping($dn, $entry); $i++; } } return $list; } /** * Set filter used in search() */ public function set_filter($filter) { $this->config['filter'] = $filter; } /** * Maps LDAP attributes to defined fields */ protected function field_mapping($dn, $entry) { $entry['dn'] = $dn; // fields mapping foreach ($this->fieldmap as $field => $attr) { // $entry might be indexed by lower-case attribute names $attr_lc = strtolower($attr); if (isset($entry[$attr_lc])) { $entry[$field] = $entry[$attr_lc]; } elseif (isset($entry[$attr])) { $entry[$field] = $entry[$attr]; } } // compose display name according to config if (empty($this->fieldmap['displayname'])) { $entry['displayname'] = rcube_addressbook::compose_search_name( $entry, $entry['email'], $entry['name'] ?? null, $this->conf['kolab_auth_user_displayname'] ); } return $entry; } /** * Detects group member attribute name */ private function get_group_member_attr($object_classes = []) { if (empty($object_classes)) { $object_classes = $this->config['groups']['object_classes']; } if (!empty($object_classes)) { foreach ((array)$object_classes as $oc) { switch (strtolower($oc)) { case 'group': case 'groupofnames': case 'kolabgroupofnames': $member_attr = 'member'; break; case 'groupofuniquenames': case 'kolabgroupofuniquenames': $member_attr = 'uniqueMember'; break; } } } if (!empty($member_attr)) { return $member_attr; } if (!empty($this->config['groups']['member_attr'])) { return $this->config['groups']['member_attr']; } return 'member'; } /** * Prepares filter query for LDAP search */ public function parse_vars($str, $user = null, $host = null) { // When authenticating user $user is always set // if not set it means we use this LDAP object for other // purposes, e.g. kolab_delegation, then username with // correct domain is in a session if (!$user && !empty($_SESSION['username'])) { $user = $_SESSION['username']; } $dc = null; if (isset($this->icache[$user])) { [$user, $dc] = $this->icache[$user]; } else { $orig_user = $user; $domain = null; $rcmail = rcube::get_instance(); // get default domain if ($username_domain = $rcmail->config->get('username_domain')) { if ($host && is_array($username_domain) && isset($username_domain[$host])) { $domain = rcube_utils::parse_host($username_domain[$host], $host); } elseif (is_string($username_domain)) { $domain = rcube_utils::parse_host($username_domain, $host); } } // realmed username (with domain) if ($user && strpos($user, '@')) { [$usr, $dom] = explode('@', $user); // unrealm domain, user login can contain a domain alias if ($dom != $domain && ($dc = $this->domain_root_dn($dom))) { // @FIXME: we should replace domain in $user, I suppose } } elseif ($domain) { $user .= '@' . $domain; } $this->icache[$orig_user] = [$user, $dc]; } // replace variables in filter [$u, $d] = explode('@', $user); // hierarchal domain string if (empty($dc)) { $dc = 'dc=' . strtr($d, ['.' => ',dc=']); } $replaces = ['%dc' => $dc, '%d' => $d, '%fu' => $user, '%u' => $u]; $this->parse_replaces = $replaces; return strtr($str, $replaces); } /** * Returns variables used for replacement in (last) parse_vars() call * * @return array Variable-value hash array */ public function get_parse_vars() { return $this->parse_replaces; } /** * Register additional fields */ public function extend_fieldmap($map) { foreach ((array)$map as $name => $attr) { if (!in_array($attr, $this->attributes)) { $this->attributes[] = $attr; $this->fieldmap[$name] = $attr; } } } /** * HTML-safe DN string encoding * * @param string $str DN string * * @return string Encoded HTML identifier string */ public static function dn_encode($str) { return rtrim(strtr(base64_encode($str), '+/', '-_'), '='); } /** * Decodes DN string encoded with _dn_encode() * * @param string $str Encoded HTML identifier string * * @return string DN string */ public static function dn_decode($str) { $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT); return base64_decode($str); } } diff --git a/plugins/libkolab/lib/kolab_storage.php b/plugins/libkolab/lib/kolab_storage.php index 8c0c0ddb..54e248a5 100644 --- a/plugins/libkolab/lib/kolab_storage.php +++ b/plugins/libkolab/lib/kolab_storage.php @@ -1,1818 +1,1818 @@ * @author Aleksander Machniak * * 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 kolab_storage { public const CTYPE_KEY = '/shared/vendor/kolab/folder-type'; public const CTYPE_KEY_PRIVATE = '/private/vendor/kolab/folder-type'; public const COLOR_KEY_SHARED = '/shared/vendor/kolab/color'; public const COLOR_KEY_PRIVATE = '/private/vendor/kolab/color'; public const NAME_KEY_SHARED = '/shared/vendor/kolab/displayname'; public const NAME_KEY_PRIVATE = '/private/vendor/kolab/displayname'; public const UID_KEY_SHARED = '/shared/vendor/kolab/uniqueid'; public const UID_KEY_CYRUS = '/shared/vendor/cmu/cyrus-imapd/uniqueid'; public const ERROR_IMAP_CONN = 1; public const ERROR_CACHE_DB = 2; public const ERROR_NO_PERMISSION = 3; public const ERROR_INVALID_FOLDER = 4; public static $version = '3.0'; public static $last_error; public static $encode_ids = false; private static $ready = false; private static $with_tempsubs = true; private static $subscriptions; private static $ldapcache = []; private static $ldap = []; private static $states; private static $config; private static $imap; // Default folder names private static $default_folders = [ 'event' => 'Calendar', 'contact' => 'Contacts', 'task' => 'Tasks', 'note' => 'Notes', 'file' => 'Files', 'configuration' => 'Configuration', 'journal' => 'Journal', 'mail.inbox' => 'INBOX', 'mail.drafts' => 'Drafts', 'mail.sentitems' => 'Sent', 'mail.wastebasket' => 'Trash', 'mail.outbox' => 'Outbox', 'mail.junkemail' => 'Junk', ]; /** * Setup the environment needed by the libs */ public static function setup() { if (self::$ready) { return true; } $rcmail = rcube::get_instance(); self::$config = $rcmail->config; self::$version = strval($rcmail->config->get('kolab_format_version', self::$version)); self::$imap = $rcmail->get_storage(); self::$ready = class_exists('kolabformat') && (self::$imap->get_capability('METADATA') || self::$imap->get_capability('ANNOTATEMORE') || self::$imap->get_capability('ANNOTATEMORE2')); if (self::$ready) { // do nothing } elseif (!class_exists('kolabformat')) { rcube::raise_error([ 'code' => 900, 'type' => 'php', 'message' => "required kolabformat module not found", ], true); } elseif (self::$imap->get_error_code()) { rcube::raise_error([ 'code' => 900, 'type' => 'php', 'message' => "IMAP error", ], true); } // adjust some configurable settings if ($event_scheduling_prop = $rcmail->config->get('kolab_event_scheduling_properties', null)) { kolab_format_event::$scheduling_properties = (array)$event_scheduling_prop; } // adjust some configurable settings if ($task_scheduling_prop = $rcmail->config->get('kolab_task_scheduling_properties', null)) { kolab_format_task::$scheduling_properties = (array)$task_scheduling_prop; } return self::$ready; } /** * Initializes LDAP object to resolve Kolab users * * @param string $name Name of the configuration option with LDAP config */ public static function ldap($name = 'kolab_users_directory') { self::setup(); $config = self::$config->get($name); if (empty($config)) { $name = 'kolab_auth_addressbook'; $config = self::$config->get($name); } if (!empty(self::$ldap[$name])) { return self::$ldap[$name]; } if (!is_array($config)) { $ldap_config = (array)self::$config->get('ldap_public'); $config = $ldap_config[$config] ?? null; } if (empty($config)) { return null; } $ldap = new kolab_ldap($config); // overwrite filter option if ($filter = self::$config->get('kolab_users_filter')) { self::$config->set('kolab_auth_filter', $filter); } $user_field = $user_attrib = self::$config->get('kolab_users_id_attrib'); // Fallback to kolab_auth_login, which is not attribute, but field name if (!$user_field && ($user_field = self::$config->get('kolab_auth_login', 'email'))) { $user_attrib = $config['fieldmap'][$user_field] ?? null; } if ($user_field && $user_attrib) { $ldap->extend_fieldmap([$user_field => $user_attrib]); } self::$ldap[$name] = $ldap; return $ldap; } /** * Get a list of storage folders for the given data type * * @param string $type Data type to list folders for (contact,distribution-list,event,task,note) * @param ?bool $subscribed Enable to return subscribed folders only (null to use configured subscription mode) * * @return array List of Kolab_Folder objects (folder names in UTF7-IMAP) */ public static function get_folders($type, $subscribed = null) { $folders = $folderdata = []; if (self::setup()) { foreach ((array)self::list_folders('', '*', $type, $subscribed, $folderdata) as $foldername) { $folders[$foldername] = new kolab_storage_folder($foldername, $type, $folderdata[$foldername]); } } return $folders; } /** * Getter for the storage folder for the given type * * @param string $type Data type to list folders for (contact,distribution-list,event,task,note) * * @return kolab_storage_folder|null The folder object */ public static function get_default_folder($type) { if (self::setup()) { foreach ((array)self::list_folders('', '*', $type . '.default', false, $folderdata) as $foldername) { return new kolab_storage_folder($foldername, $type, $folderdata[$foldername]); } } return null; } /** * Getter for a specific storage folder * * @param string $folder IMAP folder to access (UTF7-IMAP) * @param string $type Expected folder type * * @return kolab_storage_folder|null The folder object */ public static function get_folder($folder, $type = null) { return self::setup() ? new kolab_storage_folder($folder, $type) : null; } /** * Getter for a single Kolab object, identified by its UID. * This will search all folders storing objects of the given type. * * @param string $uid Object UID * @param string $type Object type (contact,event,task,journal,file,note,configuration) * * @return array|false The Kolab object represented as hash array or false if not found */ public static function get_object($uid, $type) { self::setup(); $folder = null; foreach ((array)self::list_folders('', '*', $type, null, $folderdata) as $foldername) { if (!$folder) { $folder = new kolab_storage_folder($foldername, $type, $folderdata[$foldername]); } else { $folder->set_folder($foldername, $type, $folderdata[$foldername]); } if ($object = $folder->get_object($uid)) { return $object; } } return false; } /** * Execute cross-folder searches with the given query. * * @param array $query Pseudo-SQL query as list of filter parameter triplets * @param string $type Folder type (contact,event,task,journal,file,note,configuration) * @param ?int $limit Expected number of records or limit (for performance reasons) * * @return array List of Kolab data objects (each represented as hash array) * @see kolab_storage_format::select() */ public static function select($query, $type, $limit = null) { self::setup(); $folder = null; $result = []; foreach ((array)self::list_folders('', '*', $type, null, $folderdata) as $foldername) { $folder = new kolab_storage_folder($foldername, $type, $folderdata[$foldername]); if ($limit) { $folder->set_order_and_limit(null, $limit); } foreach ($folder->select($query) as $object) { $result[] = $object; } } return $result; } /** * Returns Free-busy server URL */ public static function get_freebusy_server() { $rcmail = rcube::get_instance(); if ($url = $rcmail->config->get('kolab_freebusy_server')) { $url = rcube_utils::resolve_url($url); $url = unslashify($url); } return $url; } /** * Compose an URL to query the free/busy status for the given user * * @param string $email Email address of the user to get free/busy data for * @param ?DateTime $start Start of the query range (optional) * @param ?DateTime $end End of the query range (optional) * * @return ?string Fully qualified URL to query free/busy data */ public static function get_freebusy_url($email, $start = null, $end = null) { $url = self::get_freebusy_server(); if (empty($url)) { return null; } $query = ''; $param = []; $utc = new \DateTimeZone('UTC'); // https://www.calconnect.org/pubdocs/CD0903%20Freebusy%20Read%20URL.pdf if ($start instanceof \DateTime) { $start->setTimezone($utc); $param['start'] = $param['dtstart'] = $start->format('Ymd\THis\Z'); } if ($end instanceof \DateTime) { $end->setTimezone($utc); $param['end'] = $param['dtend'] = $end->format('Ymd\THis\Z'); } if (!empty($param)) { $query = '?' . http_build_query($param); } if (strpos($url, '%u')) { // Expected configured full URL, just replace the %u variable // Note: Cyrus v3 Free-Busy service does not use .ifb extension $url = str_replace('%u', rawurlencode($email), $url); } else { $url .= '/' . $email . '.ifb'; } return $url . $query; } /** * Creates folder ID from folder name * * @param string $folder Folder name (UTF7-IMAP) * @param bool $enc Use lossless encoding * * @return string Folder ID string */ public static function folder_id($folder, $enc = null) { return $enc == true || ($enc === null && self::$encode_ids) ? self::id_encode($folder) : asciiwords(strtr($folder, '/.-', '___')); } /** * Encode the given ID to a safe ascii representation * * @param string $id Arbitrary identifier string * * @return string Ascii representation */ public static function id_encode($id) { return rtrim(strtr(base64_encode($id), '+/', '-_'), '='); } /** * Convert the given identifier back to it's raw value * * @param string $id Ascii identifier * * @return string Raw identifier string */ public static function id_decode($id) { return base64_decode(str_pad(strtr($id, '-_', '+/'), strlen($id) % 4, '=', STR_PAD_RIGHT)); } /** * Return the (first) path of the requested IMAP namespace * * @param string $name Namespace name (personal, shared, other) * * @return string IMAP root path for that namespace */ public static function namespace_root($name) { self::setup(); foreach ((array)self::$imap->get_namespace($name) as $paths) { if (strlen($paths[0]) > 1) { return $paths[0]; } } return ''; } /** * Deletes IMAP folder * * @param string $name Folder name (UTF7-IMAP) * * @return bool True on success, false on failure */ public static function folder_delete($name) { // clear cached entries first if ($folder = self::get_folder($name)) { $folder->cache->purge(); } $rcmail = rcube::get_instance(); $plugin = $rcmail->plugins->exec_hook('folder_delete', ['name' => $name]); $success = self::$imap->delete_folder($name); self::$last_error = self::$imap->get_error_str(); return $success; } /** * Creates IMAP folder * * @param string $name Folder name (UTF7-IMAP) * @param string $type Folder type * @param bool $subscribed Sets folder subscription * @param bool $active Sets folder state (client-side subscription) * * @return bool True on success, false on failure */ public static function folder_create($name, $type = null, $subscribed = false, $active = false) { self::setup(); $rcmail = rcube::get_instance(); $plugin = $rcmail->plugins->exec_hook('folder_create', ['record' => [ 'name' => $name, 'subscribe' => $subscribed, ]]); if ($saved = self::$imap->create_folder($name, $subscribed)) { // set metadata for folder type if ($type) { $saved = self::set_folder_type($name, $type); // revert if metadata could not be set if (!$saved) { self::$imap->delete_folder($name); } // activate folder elseif ($active) { self::set_state($name, true); } } } if ($saved) { return true; } self::$last_error = self::$imap->get_error_str(); return false; } /** * Renames IMAP folder * * @param string $oldname Old folder name (UTF7-IMAP) * @param string $newname New folder name (UTF7-IMAP) * * @return bool True on success, false on failure */ public static function folder_rename($oldname, $newname) { self::setup(); $rcmail = rcube::get_instance(); $plugin = $rcmail->plugins->exec_hook('folder_rename', [ 'oldname' => $oldname, 'newname' => $newname]); $oldfolder = self::get_folder($oldname); $active = self::folder_is_active($oldname); $success = self::$imap->rename_folder($oldname, $newname); self::$last_error = self::$imap->get_error_str(); // pass active state to new folder name if ($success && $active) { self::set_state($oldname, false); self::set_state($newname, true); } // assign existing cache entries to new resource uri if ($success && $oldfolder) { $oldfolder->cache->rename($newname); } return $success; } /** * Rename or Create a new IMAP folder. * * Does additional checks for permissions and folder name restrictions * * @param array &$prop Hash array with folder properties and metadata * - name: Folder name * - oldname: Old folder name when changed * - parent: Parent folder to create the new one in * - type: Folder type to create * - subscribed: Subscribed flag (IMAP subscription) * - active: Activation flag (client-side subscription) * * @return string|false New folder name or False on failure * * @see self::set_folder_props() for list of other properties */ public static function folder_update(&$prop) { self::setup(); $folder = rcube_charset::convert($prop['name'], RCUBE_CHARSET, 'UTF7-IMAP'); $oldfolder = $prop['oldname'] ?? ''; // UTF7 $parent = $prop['parent'] ?? ''; // UTF7 $delimiter = self::$imap->get_hierarchy_delimiter(); if (strlen($oldfolder)) { $options = self::$imap->folder_info($oldfolder); } if (!empty($options) && ($options['norename'] || $options['protected'])) { } // sanity checks (from steps/settings/save_folder.inc) elseif (!strlen($folder)) { self::$last_error = 'cannotbeempty'; return false; } elseif (strlen($folder) > 128) { self::$last_error = 'nametoolong'; return false; } else { // these characters are problematic e.g. when used in LIST/LSUB foreach ([$delimiter, '%', '*'] as $char) { if (strpos($folder, $char) !== false) { self::$last_error = 'forbiddencharacter'; return false; } } } if (!empty($options) && (!empty($options['protected']) || !empty($options['norename']))) { $folder = $oldfolder; } elseif (strlen($parent)) { $folder = $parent . $delimiter . $folder; } else { // add namespace prefix (when needed) $folder = self::$imap->mod_folder($folder, 'in'); } // Check access rights to the parent folder if (strlen($parent) && (!strlen($oldfolder) || $oldfolder != $folder)) { $parent_opts = self::$imap->folder_info($parent); if ($parent_opts['namespace'] != 'personal' && (empty($parent_opts['rights']) || !preg_match('/[ck]/', implode('', $parent_opts['rights']))) ) { self::$last_error = 'No permission to create folder'; return false; } } // update the folder name if (strlen($oldfolder)) { if ($oldfolder != $folder) { $result = self::folder_rename($oldfolder, $folder); } else { $result = true; } } // create new folder else { $result = self::folder_create($folder, $prop['type'], $prop['subscribed'], $prop['active']); } if ($result) { self::set_folder_props($folder, $prop); } return $result ? $folder : false; } /** * Getter for human-readable name of Kolab object (folder) * with kolab_custom_display_names support. * See http://wiki.kolab.org/UI-Concepts/Folder-Listing for reference * * @param string $folder IMAP folder name (UTF7-IMAP) * @param string $folder_ns Will be set to namespace name of the folder * * @return string Name of the folder-object */ public static function object_name($folder, &$folder_ns = null) { // find custom display name in folder METADATA if ($name = self::custom_displayname($folder)) { return $name; } return self::object_prettyname($folder, $folder_ns); } /** * Get custom display name (saved in metadata) for the given folder */ public static function custom_displayname($folder) { static $_metadata; // find custom display name in folder METADATA if (self::$config->get('kolab_custom_display_names', true) && self::setup()) { if ($_metadata !== null) { $metadata = $_metadata; } else { // For performance reasons ask for all folders, it will be cached as one cache entry $metadata = self::$imap->get_metadata("*", [self::NAME_KEY_PRIVATE, self::NAME_KEY_SHARED]); // If cache is disabled store result in memory if (!self::$config->get('imap_cache')) { $_metadata = $metadata; } } if ($data = $metadata[$folder] ?? null) { if (($name = $data[self::NAME_KEY_PRIVATE]) || ($name = $data[self::NAME_KEY_SHARED])) { return $name; } } } return false; } /** * Getter for human-readable name of Kolab object (folder) * See http://wiki.kolab.org/UI-Concepts/Folder-Listing for reference * * @param string $folder IMAP folder name (UTF7-IMAP) * @param string $folder_ns Will be set to namespace name of the folder * * @return string Name of the folder-object */ public static function object_prettyname($folder, &$folder_ns = null) { self::setup(); $found = false; $namespace = self::$imap->get_namespace(); $prefix = null; if (!empty($namespace['shared'])) { foreach ($namespace['shared'] as $ns) { if (strlen($ns[0]) && strpos($folder, $ns[0]) === 0) { $prefix = ''; $folder = substr($folder, strlen($ns[0])); $delim = $ns[1]; $found = true; $folder_ns = 'shared'; break; } } } if (!$found && !empty($namespace['other'])) { foreach ($namespace['other'] as $ns) { if (strlen($ns[0]) && strpos($folder, $ns[0]) === 0) { // remove namespace prefix and extract username $folder = substr($folder, strlen($ns[0])); $delim = $ns[1]; // get username part and map it to user name $pos = strpos($folder, $delim); $fid = $pos ? substr($folder, 0, $pos) : $folder; if ($user = self::folder_id2user($fid, true)) { $fid = str_replace($delim, '', $user); } $prefix = "($fid)"; $folder = $pos ? substr($folder, $pos + 1) : ''; $found = true; $folder_ns = 'other'; break; } } } if (!$found && !empty($namespace['personal'])) { foreach ($namespace['personal'] as $ns) { if (strlen($ns[0]) && strpos($folder, $ns[0]) === 0) { // remove namespace prefix $folder = substr($folder, strlen($ns[0])); $prefix = ''; $delim = $ns[1]; $found = true; break; } } } if (empty($delim)) { $delim = self::$imap->get_hierarchy_delimiter(); } $folder = rcube_charset::convert($folder, 'UTF7-IMAP'); $folder = html::quote($folder); $folder = str_replace(html::quote($delim), ' » ', $folder); if ($prefix) { $folder = html::quote($prefix) . ($folder !== '' ? ' ' . $folder : ''); } if (empty($folder_ns)) { $folder_ns = 'personal'; } return $folder; } /** * Helper method to generate a truncated folder name to display. * Note: $origname is a string returned by self::object_name() */ public static function folder_displayname($origname, &$names) { $name = $origname; // find folder prefix to truncate for ($i = count($names) - 1; $i >= 0; $i--) { if (strpos($name, $names[$i] . ' » ') === 0) { $length = strlen($names[$i] . ' » '); $prefix = substr($name, 0, $length); $count = count(explode(' » ', $prefix)); $diff = 1; // check if prefix folder is in other users namespace for ($n = count($names) - 1; $n >= 0; $n--) { if (strpos($prefix, '(' . $names[$n] . ') ') === 0) { $diff = 0; break; } } $name = str_repeat('   ', $count - $diff) . '» ' . substr($name, $length); break; } // other users namespace and parent folder exists elseif (strpos($name, '(' . $names[$i] . ') ') === 0) { $length = strlen('(' . $names[$i] . ') '); $prefix = substr($name, 0, $length); $count = count(explode(' » ', $prefix)); $name = str_repeat('   ', $count) . '» ' . substr($name, $length); break; } } $names[] = $origname; return $name; } /** * Creates a SELECT field with folders list * * @param string $type Folder type * @param array $attrs SELECT field attributes (e.g. name) * @param string $current The name of current folder (to skip it) * * @return html_select SELECT object */ public static function folder_selector($type, $attrs, $current = '') { // get all folders of specified type (sorted) $folders = self::get_folders($type, true); $delim = self::$imap->get_hierarchy_delimiter(); $names = []; $len = strlen($current); $parent = ''; $p_len = 0; if ($len && ($rpos = strrpos($current, $delim))) { $parent = substr($current, 0, $rpos); $p_len = strlen($parent); } // Filter folders list foreach ($folders as $c_folder) { $name = $c_folder->name; // skip current folder and it's subfolders if ($len) { if ($name == $current) { // Make sure parent folder is listed (might be skipped e.g. if it's namespace root) if ($p_len && !isset($names[$parent])) { $names[$parent] = self::object_name($parent); } continue; } if (strpos($name, $current . $delim) === 0) { continue; } } if ($p_len && $name == $parent) { // always show the parent of current folder } elseif ($c_folder->get_owner() != $_SESSION['username']) { // skip folders where user have no rights to create subfolders $rights = $c_folder->get_myrights(); if (!preg_match('/[ck]/', $rights)) { continue; } } $names[$name] = $c_folder->get_name(); } // Build SELECT field of parent folder $attrs['is_escaped'] = true; $select = new html_select($attrs); $select->add('---', ''); $listnames = []; foreach (array_keys($names) as $imap_name) { $name = $origname = $names[$imap_name]; // find folder prefix to truncate for ($i = count($listnames) - 1; $i >= 0; $i--) { if (strpos($name, $listnames[$i] . ' » ') === 0) { $length = strlen($listnames[$i] . ' » '); $prefix = substr($name, 0, $length); $count = count(explode(' » ', $prefix)); $name = str_repeat('  ', $count - 1) . '» ' . substr($name, $length); break; } } $listnames[] = $origname; $select->add($name, $imap_name); } return $select; } /** * Returns a list of folder names * * @param string $root Optional root folder * @param string $mbox Optional name pattern * @param string $filter Data type to list folders for (contact,event,task,journal,file,note,mail,configuration) * @param bool $subscribed Enable to return subscribed folders only (null to use configured subscription mode) * @param array $folderdata Will be filled with folder-types data * * @return array List of folders */ public static function list_folders($root = '', $mbox = '*', $filter = null, $subscribed = null, &$folderdata = []) { if (!self::setup()) { return []; } // use IMAP subscriptions if ($subscribed === null && self::$config->get('kolab_use_subscriptions')) { $subscribed = true; } if (!$filter) { // Get ALL folders list, standard way if ($subscribed) { $folders = self::_imap_list_subscribed($root, $mbox, $filter); } else { $folders = self::_imap_list_folders($root, $mbox); } return $folders; } $prefix = $root . $mbox; $regexp = '/^' . preg_quote($filter, '/') . '(\..+)?$/'; // get folders types for all folders $folderdata = self::folders_typedata($prefix); if (!is_array($folderdata)) { return []; } // If we only want groupware folders and don't care about the subscription state, // then the metadata will already contain all folder names and we can avoid the LIST below. if (!$subscribed && $filter != 'mail' && $prefix == '*') { foreach ($folderdata as $folder => $type) { if (!preg_match($regexp, (string) $type)) { unset($folderdata[$folder]); } } return self::$imap->sort_folder_list(array_keys($folderdata), true); } // Get folders list if ($subscribed) { $folders = self::_imap_list_subscribed($root, $mbox, $filter); } else { $folders = self::_imap_list_folders($root, $mbox); } // In case of an error, return empty list (?) if (!is_array($folders)) { return []; } // Filter folders list foreach ($folders as $idx => $folder) { $type = $folderdata[$folder] ?? null; if ($filter == 'mail' && empty($type)) { continue; } if (empty($type) || !preg_match($regexp, $type)) { unset($folders[$idx]); } } return $folders; } /** * Wrapper for rcube_imap::list_folders() with optional post-filtering */ protected static function _imap_list_folders($root, $mbox) { $postfilter = null; // compose a post-filter expression for the excluded namespaces if ($root . $mbox == '*' && ($skip_ns = self::$config->get('kolab_skip_namespace'))) { $excludes = []; foreach ((array)$skip_ns as $ns) { if ($ns_root = self::namespace_root($ns)) { $excludes[] = $ns_root; } } if (count($excludes)) { $postfilter = '!^(' . implode(')|(', array_map('preg_quote', $excludes)) . ')!'; } } // use normal LIST command to return all folders, it's fast enough $folders = self::$imap->list_folders($root, $mbox, null, null, !empty($postfilter)); if (!empty($postfilter)) { $folders = array_filter($folders, function ($folder) use ($postfilter) { return !preg_match($postfilter, $folder); }); $folders = self::$imap->sort_folder_list($folders); } return $folders; } /** * Wrapper for rcube_imap::list_folders_subscribed() * with support for temporarily subscribed folders */ protected static function _imap_list_subscribed($root, $mbox, $filter = null) { $folders = self::$imap->list_folders_subscribed($root, $mbox); // add temporarily subscribed folders if ($filter != 'mail' && self::$with_tempsubs && is_array($_SESSION['kolab_subscribed_folders'] ?? null)) { $folders = array_unique(array_merge($folders, $_SESSION['kolab_subscribed_folders'])); } return $folders; } /** * Search for shared or otherwise not listed groupware folders the user has access * * @param string $type Folder type of folders to search for * @param string $query Search string * @param array $exclude_ns Namespace(s) to exclude results from * * @return array List of matching kolab_storage_folder objects */ public static function search_folders($type, $query, $exclude_ns = []) { if (!self::setup()) { return []; } $folders = []; $query = str_replace('*', '', $query); // find unsubscribed IMAP folders of the given type foreach ((array)self::list_folders('', '*', $type, false, $folderdata) as $foldername) { // FIXME: only consider the last part of the folder path for searching? $realname = strtolower(rcube_charset::convert($foldername, 'UTF7-IMAP')); if (($query == '' || strpos($realname, $query) !== false) && !self::folder_is_subscribed($foldername, true) && !in_array(self::$imap->folder_namespace($foldername), (array)$exclude_ns) ) { $folders[] = new kolab_storage_folder($foldername, $type, $folderdata[$foldername]); } } return $folders; } /** * Sort the given list of kolab folders by namespace/name * * @param array $folders List of kolab_storage_folder objects * * @return array Sorted list of folders */ public static function sort_folders($folders) { $pad = ' '; $out = []; $nsnames = ['personal' => [], 'shared' => [], 'other' => []]; $_folders = []; foreach ($folders as $folder) { $_folders[$folder->name] = $folder; $ns = $folder->get_namespace(); $nsnames[$ns][$folder->name] = strtolower(html_entity_decode($folder->get_name(), ENT_COMPAT, RCUBE_CHARSET)) . $pad; // decode » } // $folders is a result of get_folders() we can assume folders were already sorted foreach (array_keys($nsnames) as $ns) { asort($nsnames[$ns], SORT_LOCALE_STRING); foreach (array_keys($nsnames[$ns]) as $utf7name) { $out[] = $_folders[$utf7name]; } } return $out; } /** * Check the folder tree and add the missing parents as virtual folders * - * @param array $folders Folders list - * @param object $tree Reference to the root node of the folder tree + * @param array $folders Folders list + * @param ?kolab_storage_folder_virtual $tree Reference to the root node of the folder tree * * @return array Flat folders list */ public static function folder_hierarchy($folders, &$tree = null) { if (!self::setup()) { return []; } $_folders = []; $delim = self::$imap->get_hierarchy_delimiter(); $other_ns = rtrim(self::namespace_root('other'), $delim); $tree = new kolab_storage_folder_virtual('', '', ''); // create tree root $refs = ['' => $tree]; foreach ($folders as $idx => $folder) { $path = explode($delim, $folder->name); array_pop($path); $folder->parent = implode($delim, $path); $folder->children = []; // reset list // skip top folders or ones with a custom displayname if (count($path) < 1 || kolab_storage::custom_displayname($folder->name)) { $tree->children[] = $folder; } else { $parents = []; $depth = $folder->get_namespace() == 'personal' ? 1 : 2; while (count($path) >= $depth && ($parent = implode($delim, $path))) { array_pop($path); $parent_parent = implode($delim, $path); if (empty($refs[$parent])) { if ($folder->type && self::folder_type($parent) == $folder->type) { $refs[$parent] = new kolab_storage_folder($parent, $folder->type, $folder->type); $refs[$parent]->parent = $parent_parent; } elseif ($parent_parent == $other_ns) { $refs[$parent] = new kolab_storage_folder_user($parent, $parent_parent); } else { $name = kolab_storage::object_name($parent); $refs[$parent] = new kolab_storage_folder_virtual($parent, $name, $folder->get_namespace(), $parent_parent); } $parents[] = $refs[$parent]; } } if (!empty($parents)) { $parents = array_reverse($parents); foreach ($parents as $parent) { $parent_node = !empty($refs[$parent->parent]) ? $refs[$parent->parent] : $tree; $parent_node->children[] = $parent; $_folders[] = $parent; } } $parent_node = !empty($refs[$folder->parent]) ? $refs[$folder->parent] : $tree; $parent_node->children[] = $folder; } $refs[$folder->name] = $folder; $_folders[] = $folder; unset($folders[$idx]); } return $_folders; } /** * Returns folder types indexed by folder name * * @param string $prefix Folder prefix (Default '*' for all folders) * * @return array|bool List of folders, False on failure */ public static function folders_typedata($prefix = '*') { if (!self::setup()) { return false; } $type_keys = [self::CTYPE_KEY, self::CTYPE_KEY_PRIVATE]; // fetch metadata from *some* folders only if (($prefix == '*' || $prefix == '') && ($skip_ns = self::$config->get('kolab_skip_namespace'))) { $delimiter = self::$imap->get_hierarchy_delimiter(); $folderdata = $blacklist = []; foreach ((array)$skip_ns as $ns) { if ($ns_root = rtrim(self::namespace_root($ns), $delimiter)) { $blacklist[] = $ns_root; } } foreach (['personal','other','shared'] as $ns) { if (!in_array($ns, (array)$skip_ns)) { $ns_root = rtrim(self::namespace_root($ns), $delimiter); // list top-level folders and their childs one by one // GETMETADATA "%" doesn't list shared or other namespace folders but "*" would if ($ns_root == '') { foreach ((array)self::$imap->get_metadata('%', $type_keys) as $folder => $metadata) { if (!in_array($folder, $blacklist)) { $folderdata[$folder] = $metadata; $opts = self::$imap->folder_attributes($folder); if (!in_array('\\HasNoChildren', $opts) && ($data = self::$imap->get_metadata($folder . $delimiter . '*', $type_keys))) { $folderdata += $data; } } } } elseif ($data = self::$imap->get_metadata($ns_root . $delimiter . '*', $type_keys)) { $folderdata += $data; } } } } else { $folderdata = self::$imap->get_metadata($prefix, $type_keys); } if (!is_array($folderdata)) { return false; } return array_map(['kolab_storage', 'folder_select_metadata'], $folderdata); } /** * Callback for array_map to select the correct annotation value */ public static function folder_select_metadata($types) { if (!empty($types[self::CTYPE_KEY_PRIVATE])) { return $types[self::CTYPE_KEY_PRIVATE]; } elseif (!empty($types[self::CTYPE_KEY])) { [$ctype, ] = explode('.', $types[self::CTYPE_KEY]); return $ctype; } return null; } /** * Returns type of IMAP folder * * @param string $folder Folder name (UTF7-IMAP) * * @return string|null Folder type */ public static function folder_type($folder) { self::setup(); $metadata = self::$imap->get_metadata($folder, [self::CTYPE_KEY, self::CTYPE_KEY_PRIVATE]); if (!is_array($metadata)) { return null; } if (!empty($metadata[$folder])) { return self::folder_select_metadata($metadata[$folder]); } return 'mail'; } /** * Sets folder content-type. * * @param string $folder Folder name * @param string $type Content type * * @return bool True on success */ public static function set_folder_type($folder, $type = 'mail') { self::setup(); [$ctype, $subtype] = strpos($type, '.') !== false ? explode('.', $type) : [$type, null]; $success = self::$imap->set_metadata($folder, [self::CTYPE_KEY => $ctype, self::CTYPE_KEY_PRIVATE => $subtype ? $type : null]); if (!$success) { // fallback: only set private annotation $success |= self::$imap->set_metadata($folder, [self::CTYPE_KEY_PRIVATE => $type]); } return $success; } /** * Check subscription status of this folder * * @param string $folder Folder name * @param bool $temp Include temporary/session subscriptions * * @return bool True if subscribed, false if not */ public static function folder_is_subscribed($folder, $temp = false) { if (self::$subscriptions === null) { self::setup(); self::$with_tempsubs = false; self::$subscriptions = self::$imap->list_folders_subscribed(); self::$with_tempsubs = true; } return in_array($folder, self::$subscriptions) || ($temp && in_array($folder, $_SESSION['kolab_subscribed_folders'] ?? [])); } /** * Change subscription status of this folder * * @param string $folder Folder name * @param bool $temp Only subscribe temporarily for the current session * * @return bool True on success, false on error */ public static function folder_subscribe($folder, $temp = false) { self::setup(); // temporary/session subscription if ($temp) { if (self::folder_is_subscribed($folder)) { return true; } elseif (empty($_SESSION['kolab_subscribed_folders']) || !in_array($folder, $_SESSION['kolab_subscribed_folders'])) { $_SESSION['kolab_subscribed_folders'][] = $folder; return true; } } elseif (self::$imap->subscribe($folder)) { self::$subscriptions = null; return true; } return false; } /** * Change subscription status of this folder * * @param string $folder Folder name * @param bool $temp Only remove temporary subscription * * @return bool True on success, false on error */ public static function folder_unsubscribe($folder, $temp = false) { self::setup(); // temporary/session subscription if ($temp) { if (!empty($_SESSION['kolab_subscribed_folders']) && ($i = array_search($folder, $_SESSION['kolab_subscribed_folders'])) !== false) { unset($_SESSION['kolab_subscribed_folders'][$i]); } return true; } elseif (self::$imap->unsubscribe($folder)) { self::$subscriptions = null; return true; } return false; } /** * Check activation status of this folder * * @param string $folder Folder name * * @return bool True if active, false if not */ public static function folder_is_active($folder) { $active_folders = self::get_states(); return in_array($folder, $active_folders); } /** * Change activation status of this folder * * @param string $folder Folder name * * @return bool True on success, false on error */ public static function folder_activate($folder) { // activation implies temporary subscription self::folder_subscribe($folder, true); return self::set_state($folder, true); } /** * Change activation status of this folder * * @param string $folder Folder name * * @return bool True on success, false on error */ public static function folder_deactivate($folder) { // remove from temp subscriptions, really? self::folder_unsubscribe($folder, true); return self::set_state($folder, false); } /** * Return list of active folders */ private static function get_states() { if (self::$states !== null) { return self::$states; } $rcube = rcube::get_instance(); $folders = $rcube->config->get('kolab_active_folders'); if ($folders !== null) { self::$states = !empty($folders) ? explode('**', $folders) : []; } // for backward-compatibility copy server-side subscriptions to activation states else { self::setup(); if (self::$subscriptions === null) { self::$with_tempsubs = false; self::$subscriptions = self::$imap->list_folders_subscribed(); self::$with_tempsubs = true; } self::$states = (array) self::$subscriptions; $folders = implode('**', self::$states); $rcube->user->save_prefs(['kolab_active_folders' => $folders]); } return self::$states; } /** * Update list of active folders */ private static function set_state($folder, $state) { self::get_states(); // update in-memory list $idx = array_search($folder, self::$states); if ($state && $idx === false) { self::$states[] = $folder; } elseif (!$state && $idx !== false) { unset(self::$states[$idx]); } // update user preferences $folders = implode('**', self::$states); return rcube::get_instance()->user->save_prefs(['kolab_active_folders' => $folders]); } /** * Creates default folder of specified type * To be run when none of subscribed folders (of specified type) is found * * @param string $type Folder type * @param array $props Folder properties (color, etc) * * @return string|null Folder name */ public static function create_default_folder($type, $props = []) { if (!self::setup()) { return null; } $folders = self::$imap->get_metadata('*', [kolab_storage::CTYPE_KEY_PRIVATE]); // from kolab_folders config $folder_type = strpos($type, '.') ? str_replace('.', '_', $type) : $type . '_default'; $default_name = self::$config->get('kolab_folders_' . $folder_type); $folder_type = str_replace('_', '.', $folder_type); // check if we have any folder in personal namespace // folder(s) may exist but not subscribed foreach ((array)$folders as $f => $data) { if (strpos($data[self::CTYPE_KEY_PRIVATE], $type) === 0) { $folder = $f; break; } } if (empty($folder)) { if (!$default_name) { $default_name = self::$default_folders[$type]; } if (!$default_name) { return null; } $folder = rcube_charset::convert($default_name, RCUBE_CHARSET, 'UTF7-IMAP'); $prefix = self::$imap->get_namespace('prefix'); // add personal namespace prefix if needed if ($prefix && strpos($folder, $prefix) !== 0 && $folder != 'INBOX') { $folder = $prefix . $folder; } if (!self::$imap->folder_exists($folder)) { if (!self::$imap->create_folder($folder)) { return null; } } self::set_folder_type($folder, $folder_type); } self::folder_subscribe($folder); if ($props['active']) { self::set_state($folder, true); } if (!empty($props)) { self::set_folder_props($folder, $props); } return $folder; } /** * Sets folder metadata properties * * @param string $folder Folder name * @param array &$prop Folder properties (color, displayname) */ public static function set_folder_props($folder, &$prop) { if (!self::setup()) { return; } // TODO: also save 'showalarams' and other properties here $ns = self::$imap->folder_namespace($folder); $supported = [ 'color' => [self::COLOR_KEY_SHARED, self::COLOR_KEY_PRIVATE], 'displayname' => [self::NAME_KEY_SHARED, self::NAME_KEY_PRIVATE], ]; foreach ($supported as $key => $metakeys) { if (array_key_exists($key, $prop)) { $meta_saved = false; if ($ns == 'personal') { // save in shared namespace for personal folders $meta_saved = self::$imap->set_metadata($folder, [$metakeys[0] => $prop[$key]]); } if (!$meta_saved) { // try in private namespace $meta_saved = self::$imap->set_metadata($folder, [$metakeys[1] => $prop[$key]]); } if ($meta_saved) { unset($prop[$key]); } // unsetting will prevent fallback to local user prefs } } } /** * Search users in Kolab LDAP storage * * @param mixed $query Search value (or array of field => value pairs) * @param int $mode Matching mode: 0 - partial (*abc*), 1 - strict (=), 2 - prefix (abc*) * @param array $required List of fields that shall ot be empty * @param int $limit Maximum number of records * @param int $count Returns the number of records found * * @return array List of users */ public static function search_users($query, $mode = 1, $required = [], $limit = 0, &$count = 0) { $query = str_replace('*', '', $query); // requires a working LDAP setup if (!strlen($query) || !($ldap = self::ldap())) { return []; } $root = self::namespace_root('other'); $user_attrib = self::$config->get('kolab_users_id_attrib', self::$config->get('kolab_auth_login', 'mail')); $search_attrib = self::$config->get('kolab_users_search_attrib', ['cn','mail','alias']); // search users using the configured attributes $results = $ldap->dosearch($search_attrib, $query, $mode, $required, $limit, $count); // exclude myself if ($_SESSION['kolab_dn']) { unset($results[$_SESSION['kolab_dn']]); } // resolve to IMAP folder name array_walk($results, function (&$user, $dn) use ($root, $user_attrib) { [$localpart, ] = explode('@', $user[$user_attrib]); $user['kolabtargetfolder'] = $root . $localpart; }); return $results; } /** * Returns a list of IMAP folders shared by the given user * * @param array $user User entry from LDAP * @param string $type Data type to list folders for (contact,event,task,journal,file,note,mail,configuration) * @param int $subscribed 1 - subscribed folders only, 0 - all folders, 2 - all non-active * @param array $folderdata Will be filled with folder-types data * * @return array List of folders */ public static function list_user_folders($user, $type, $subscribed = 0, &$folderdata = []) { self::setup(); $folders = []; // use localpart of user attribute as root for folder listing $user_attrib = self::$config->get('kolab_users_id_attrib', self::$config->get('kolab_auth_login', 'mail')); if (!empty($user[$user_attrib])) { [$mbox] = explode('@', $user[$user_attrib]); $delimiter = self::$imap->get_hierarchy_delimiter(); $other_ns = self::namespace_root('other'); $prefix = $other_ns . $mbox . $delimiter; $subscribed = (int) $subscribed; $subs = $subscribed < 2 ? (bool) $subscribed : false; $folders = self::list_folders($prefix, '*', $type, $subs, $folderdata); if ($subscribed === 2 && !empty($folders)) { $active = self::get_states(); if (!empty($active)) { $folders = array_diff($folders, $active); } } } return $folders; } /** * Get a list of (virtual) top-level folders from the other users namespace * * @param string $type Data type to list folders for (contact,event,task,journal,file,note,mail,configuration) * @param bool $subscribed Enable to return subscribed folders only (null to use configured subscription mode) * * @return array List of kolab_storage_folder_user objects */ public static function get_user_folders($type, $subscribed) { $folders = $folderdata = []; if (self::setup()) { $delimiter = self::$imap->get_hierarchy_delimiter(); $other_ns = rtrim(self::namespace_root('other'), $delimiter); $path_len = count(explode($delimiter, $other_ns)); foreach ((array) self::list_folders($other_ns . $delimiter, '*', '', $subscribed) as $foldername) { if ($foldername == 'INBOX') { // skip INBOX which is added by default continue; } $path = explode($delimiter, $foldername); // compare folder type if a subfolder is listed if ($type && count($path) > $path_len + 1 && $type != self::folder_type($foldername)) { continue; } // truncate folder path to top-level folders of the 'other' namespace $foldername = implode($delimiter, array_slice($path, 0, $path_len + 1)); if (empty($folders[$foldername])) { $folders[$foldername] = new kolab_storage_folder_user($foldername, $other_ns); } } // for every (subscribed) user folder, list all (unsubscribed) subfolders foreach ($folders as $userfolder) { foreach ((array) self::list_folders($userfolder->name . $delimiter, '*', $type, false, $folderdata) as $foldername) { if (empty($folders[$foldername])) { $folders[$foldername] = new kolab_storage_folder($foldername, $type, $folderdata[$foldername] ?? null); $userfolder->children[] = $folders[$foldername]; } } } } return $folders; } /** * Handler for user_delete plugin hooks * * Remove all cache data from the local database related to the given user. */ public static function delete_user_folders($args) { $db = rcube::get_instance()->get_dbh(); $prefix = 'imap://' . urlencode($args['username']) . '@' . $args['host'] . '/%'; $db->query("DELETE FROM " . $db->table_name('kolab_folders', true) . " WHERE `resource` LIKE ?", $prefix); } /** * Get folder METADATA for all supported keys * Do this in one go for better caching performance */ public static function folder_metadata($folder) { if (self::setup()) { $keys = [ // For better performance we skip displayname here, see (self::custom_displayname()) // self::NAME_KEY_PRIVATE, // self::NAME_KEY_SHARED, self::CTYPE_KEY, self::CTYPE_KEY_PRIVATE, self::COLOR_KEY_PRIVATE, self::COLOR_KEY_SHARED, self::UID_KEY_SHARED, self::UID_KEY_CYRUS, ]; $metadata = self::$imap->get_metadata($folder, $keys); return $metadata[$folder]; } } /** * Get user attributes for specified other user (imap) folder identifier. * * @param string $folder_id Folder name w/o path (imap user identifier) * @param bool $as_string Return configured display name attribute value * * @return array|string|null User attributes * @see self::ldap() */ public static function folder_id2user($folder_id, $as_string = false) { static $domain, $cache, $name_attr; $rcube = rcube::get_instance(); if ($domain === null) { [, $domain] = explode('@', $rcube->get_user_name()); } if ($name_attr === null) { $name_attr = (array) ($rcube->config->get('kolab_users_name_field', $rcube->config->get('kolab_auth_name')) ?: 'name'); } $token = $folder_id; if ($domain && strpos($token, '@') === false) { $token .= '@' . $domain; } if ($cache === null) { $cache = $rcube->get_cache_shared('kolab_users') ?: false; } // use value cached in memory for repeated lookups if (!$cache && array_key_exists($token, self::$ldapcache)) { $user = self::$ldapcache[$token]; } if (empty($user) && $cache) { $user = $cache->get($token); } if (empty($user) && ($ldap = self::ldap())) { $user = $ldap->get_user_record($token, $_SESSION['imap_host'] ?? ''); if (!empty($user)) { $keys = ['displayname', 'name', 'mail']; // supported keys $user = array_intersect_key($user, array_flip($keys)); if (!empty($user)) { if ($cache) { $cache->set($token, $user); } else { self::$ldapcache[$token] = $user; } } } } if (!empty($user)) { if ($as_string) { foreach ($name_attr as $attr) { if ($display = $user[$attr]) { break; } } if (empty($display)) { $display = $user['displayname'] ?: $user['name']; } if ($display && $display != $folder_id) { $display = "$display ($folder_id)"; } return $display; } return $user; } return null; } /** * Chwala's 'folder_mod' hook handler for mapping other users folder names */ public static function folder_mod($args) { static $roots; if ($roots === null) { self::setup(); $roots = self::$imap->get_namespace('other'); } // Note: We're working with UTF7-IMAP encoding here if ($args['dir'] == 'in') { foreach ((array) $roots as $root) { if (strpos($args['folder'], $root[0]) === 0) { // remove root and explode folder $delim = $root[1]; $folder = explode($delim, substr($args['folder'], strlen($root[0]))); // compare first (user) part with a regexp, it's supposed // to look like this: "Doe, Jane (uid)", so we can extract the uid // and replace the folder with it if (preg_match('~^[^/]+ \(([^)]+)\)$~', $folder[0], $m)) { $folder[0] = $m[1]; $args['folder'] = $root[0] . implode($delim, $folder); } break; } } } else { // dir == 'out' foreach ((array) $roots as $root) { if (strpos($args['folder'], $root[0]) === 0) { // remove root and explode folder $delim = $root[1]; $folder = explode($delim, substr($args['folder'], strlen($root[0]))); // Replace uid with "Doe, Jane (uid)" if ($user = self::folder_id2user($folder[0], true)) { $user = str_replace($delim, '', $user); $folder[0] = rcube_charset::convert($user, RCUBE_CHARSET, 'UTF7-IMAP'); $args['folder'] = $root[0] . implode($delim, $folder); } break; } } } return $args; } } diff --git a/plugins/libkolab/lib/kolab_storage_folder.php b/plugins/libkolab/lib/kolab_storage_folder.php index 924429fe..cbf64db3 100644 --- a/plugins/libkolab/lib/kolab_storage_folder.php +++ b/plugins/libkolab/lib/kolab_storage_folder.php @@ -1,1197 +1,1204 @@ * @author Aleksander Machniak * * Copyright (C) 2012-2013, 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_storage_folder extends kolab_storage_folder_api { /** * The kolab_storage_cache instance for caching operations * @var object */ public $cache; /** * Indicate validity status * @var bool */ public $valid = false; protected $error = 0; protected $resource_uri; /** * Default constructor * * @param string $name The folder name/path * @param ?string $type Expected folder type * @param ?string $type_annotation Optional folder type if known */ public function __construct($name, $type = null, $type_annotation = null) { parent::__construct($name); $this->set_folder($name, $type, $type_annotation); } /** * Set the IMAP folder this instance connects to * * @param string $name The folder name/path * @param ?string $type Expected folder type * @param ?string $type_annotation Optional folder type if known */ public function set_folder($name, $type = null, $type_annotation = null) { $this->name = $name; if (empty($type_annotation)) { $type_annotation = $this->get_type(); } $oldtype = $this->type; [$this->type, $suffix] = array_pad(explode('.', $type_annotation), 2, null); $this->default = $suffix == 'default'; $this->subtype = $this->default ? '' : $suffix; $this->id = kolab_storage::folder_id($name); $this->valid = !empty($this->type) && $this->type != 'mail' && (!$type || $this->type == $type); if (!$this->valid) { $this->error = $this->imap->get_error_code() < 0 ? kolab_storage::ERROR_IMAP_CONN : kolab_storage::ERROR_INVALID_FOLDER; } // reset cached object properties $this->owner = $this->namespace = $this->resource_uri = $this->info = $this->idata = null; // get a new cache instance if folder type changed if (!$this->cache || $this->type != $oldtype) { $this->cache = kolab_storage_cache::factory($this); } else { $this->cache->set_folder($this); } $this->imap->set_folder($this->name); } /** * Returns code of last error * * @return int Error code */ public function get_error() { return $this->error ?: $this->cache->get_error(); } /** * Check IMAP connection error state */ public function check_error() { if (($err_code = $this->imap->get_error_code()) < 0) { $this->error = kolab_storage::ERROR_IMAP_CONN; if (($res_code = $this->imap->get_response_code()) !== 0 && in_array($res_code, [rcube_storage::NOPERM, rcube_storage::READONLY])) { $this->error = kolab_storage::ERROR_NO_PERMISSION; } } return $this->error; } /** * Compose a unique resource URI for this IMAP folder */ public function get_resource_uri() { if (!empty($this->resource_uri)) { return $this->resource_uri; } // strip namespace prefix from folder name $ns = $this->get_namespace(); $nsdata = $this->imap->get_namespace($ns); if (!empty($nsdata[0][0]) && strpos($this->name, $nsdata[0][0]) === 0) { $subpath = substr($this->name, strlen($nsdata[0][0])); if ($ns == 'other') { [$user, $suffix] = explode($nsdata[0][1], $subpath, 2); $subpath = $suffix; } } else { $subpath = $this->name; } // compose fully qualified ressource uri for this instance $this->resource_uri = 'imap://' . urlencode($this->get_owner(true)) . '@' . $this->imap->options['host'] . '/' . $subpath; return $this->resource_uri; } /** * Helper method to extract folder UID metadata * * @return string|null Folder's UID */ public function get_uid() { // UID is defined in folder METADATA $metakeys = [kolab_storage::UID_KEY_SHARED, kolab_storage::UID_KEY_CYRUS]; $metadata = $this->get_metadata(); if ($metadata !== null) { foreach ($metakeys as $key) { if ($uid = ($metadata[$key] ?? null)) { return $uid; } } // generate a folder UID and set it to IMAP $uid = rtrim(chunk_split(md5($this->name . $this->get_owner() . uniqid('-', true)), 12, '-'), '-'); if ($this->set_uid($uid)) { return $uid; } } $this->check_error(); // create hash from folder name if we can't write the UID metadata return md5($this->name . $this->get_owner()); } /** * Helper method to set an UID value to the given IMAP folder instance * * @param string $uid Folder's UID * * @return bool True on succes, False on failure */ public function set_uid($uid) { $success = $this->set_metadata([kolab_storage::UID_KEY_SHARED => $uid]); $this->check_error(); return $success; } /** * Compose a folder Etag identifier */ public function get_ctag() { $fdata = $this->get_imap_data(); $this->check_error(); return sprintf('%d-%d-%d', $fdata['UIDVALIDITY'] ?? 0, $fdata['HIGHESTMODSEQ'] ?? 0, $fdata['UIDNEXT'] ?? 0); } /** * Check activation status of this folder * * @return bool True if enabled, false if not */ public function is_active() { return kolab_storage::folder_is_active($this->name); } /** * Change activation status of this folder * * @param bool $active The desired subscription status: true = active, false = not active * * @return bool True on success, false on error */ public function activate($active) { return $active ? kolab_storage::folder_activate($this->name) : kolab_storage::folder_deactivate($this->name); } /** * Check subscription status of this folder * * @return bool True if subscribed, false if not */ public function is_subscribed() { return kolab_storage::folder_is_subscribed($this->name); } /** * Change subscription status of this folder * * @param bool $subscribed The desired subscription status: true = subscribed, false = not subscribed * * @return bool True on success, false on error */ public function subscribe($subscribed) { return $subscribed ? kolab_storage::folder_subscribe($this->name) : kolab_storage::folder_unsubscribe($this->name); } /** * Get number of objects stored in this folder * * @param mixed $query Pseudo-SQL query as list of filter parameter triplets * or string with object type (e.g. contact, event, todo, journal, note, configuration) * * @return int|null The number of objects of the given type, Null on error * @see self::select() */ public function count($query = null) { if (!$this->valid) { return 0; } // synchronize cache first $this->cache->synchronize(); return $this->cache->count($this->_prepare_query($query)); } /** * Getter for a single Kolab object identified by its UID * * @param string $uid Object UID * * @return array|false|null The Kolab object represented as hash array, False on error */ public function get_object($uid) { if (!$this->valid || !$uid) { return false; } // synchronize caches $this->cache->synchronize(); return $this->cache->get_by_uid($uid); } /** * List Kolab objects matching the given query * * @param mixed $query Pseudo-SQL query as list of filter parameter triplets * or string with object type (e.g. contact, event, todo, journal, note, configuration) * * @return array List of Kolab data objects (each represented as hash array) * @deprecated Use select() */ public function get_objects($query = []) { return $this->select($query); } /** * Select Kolab objects matching the given query * * @param mixed $query Pseudo-SQL query as list of filter parameter triplets * or string with object type (e.g. contact, event, todo, journal, note, configuration) * @param bool $fast Use fast mode to fetch only minimal set of information * (no xml fetching and parsing, etc.) * * @return null|array|kolab_storage_dataset List of Kolab data objects (each represented as hash array) */ public function select($query = [], $fast = false) { if (!$this->valid) { return []; } // synchronize caches $this->cache->synchronize(); // fetch objects from cache return $this->cache->select($this->_prepare_query($query), false, $fast); } /** * Getter for object UIDs only * * @param array $query Pseudo-SQL query as list of filter parameter triplets * * @return array List of Kolab object UIDs */ public function get_uids($query = []) { if (!$this->valid) { return []; } // synchronize caches $this->cache->synchronize(); // fetch UIDs from cache return $this->cache->select($this->_prepare_query($query), true); } /** * Setter for ORDER BY and LIMIT parameters for cache queries * * @param array $sortcols List of columns to order by * @param int $length Limit result set to this length * @param int $offset Offset row */ public function set_order_and_limit($sortcols, $length = null, $offset = 0) { $this->cache->set_order_by($sortcols); if ($length !== null) { $this->cache->set_limit($length, $offset); } } /** * Helper method to sanitize query arguments */ private function _prepare_query($query) { // string equals type query // FIXME: should not be called this way! if (is_string($query)) { return $this->cache->has_type_col() && !empty($query) ? [['type','=',$query]] : []; } foreach ((array)$query as $i => $param) { if ($param[0] == 'type' && !$this->cache->has_type_col()) { unset($query[$i]); } elseif (($param[0] == 'dtstart' || $param[0] == 'dtend' || $param[0] == 'changed')) { if (is_object($param[2]) && $param[2] instanceof DateTimeInterface) { $param[2] = $param[2]->format('U'); } if (is_numeric($param[2])) { $query[$i][2] = date('Y-m-d H:i:s', $param[2]); } } } return $query; } /** * Fetch a Kolab object attachment which is stored in a separate part * of the mail MIME message that represents the Kolab record. * * @param string $uid Object's UID * @param string $part The attachment's mime number * @param ?string $mailbox IMAP folder where message is stored; * If set, that also implies that the given UID is an IMAP UID * @param bool $print True to print the part content * @param resource $fp File pointer to save the message part * @param bool $skip_charset_conv Disables charset conversion * * @return mixed The attachment content as binary string */ public function get_attachment($uid, $part, $mailbox = null, $print = false, $fp = null, $skip_charset_conv = false) { if ($this->valid && ($msguid = ($mailbox ? $uid : $this->cache->uid2msguid($uid)))) { $this->imap->set_folder($mailbox ? $mailbox : $this->name); if (substr($part, 0, 2) == 'i:') { // attachment data is stored in XML if ($object = $this->cache->get($msguid)) { $object['_attachments'] = []; // load data from XML (attachment content is not stored in cache) if (isset($object['_formatobj']) && isset($object['_size'])) { $object['_formatobj']->get_attachments($object); } + // @phpstan-ignore-next-line foreach ($object['_attachments'] as $attach) { if ($attach['id'] == $part) { if ($print) { echo $attach['content']; } elseif ($fp) { fwrite($fp, $attach['content']); } else { return $attach['content']; } return true; } } } } else { // return message part from IMAP directly // TODO: We could improve performance if we cache part's encoding // without 3rd argument get_message_part() will request BODYSTRUCTURE from IMAP return $this->imap->get_message_part($msguid, $part, null, $print, $fp, $skip_charset_conv); } } return null; } /** * Fetch the mime message from the storage server and extract * the Kolab groupware object from it * * @param string $msguid The IMAP message UID to fetch * @param string $type The object type expected (use wildcard '*' to accept all types) * @param string $folder The folder name where the message is stored * * @return mixed Hash array representing the Kolab object, a kolab_format instance or false if not found */ public function read_object($msguid, $type = null, $folder = null) { if (!$this->valid) { return false; } if (!$type) { $type = $this->type; } if (!$folder) { $folder = $this->name; } $this->imap->set_folder($folder); $this->cache->imap_mode(true); $message = new rcube_message($msguid); $this->cache->imap_mode(false); // Message doesn't exist? if (empty($message->headers)) { return false; } // extract the X-Kolab-Type header from the XML attachment part if missing if (empty($message->headers->others['x-kolab-type'])) { foreach ((array)$message->attachments as $part) { if (strpos($part->mimetype, kolab_format::KTYPE_PREFIX) === 0) { $message->headers->others['x-kolab-type'] = $part->mimetype; break; } } } // fix buggy messages stating the X-Kolab-Type header twice elseif (is_array($message->headers->others['x-kolab-type'])) { $message->headers->others['x-kolab-type'] = reset($message->headers->others['x-kolab-type']); } // no object type header found: abort if (empty($message->headers->others['x-kolab-type'])) { rcube::raise_error([ 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "No X-Kolab-Type information found in message $msguid ($this->name).", ], true); return false; } $object_type = kolab_format::mime2object_type($message->headers->others['x-kolab-type']); $content_type = kolab_format::KTYPE_PREFIX . $object_type; // check object type header and abort on mismatch if ($type != '*' && strpos($object_type, $type) !== 0 && !($object_type == 'distribution-list' && $type == 'contact')) { return false; } $attachments = []; // get XML part $xml = null; foreach ((array)$message->attachments as $part) { if (!$xml && ($part->mimetype == $content_type || preg_match('!application/([a-z.]+\+)?xml!i', $part->mimetype))) { $xml = $message->get_part_body($part->mime_id, true); } elseif ($part->filename || $part->content_id) { $key = $part->content_id ? trim($part->content_id, '<>') : $part->filename; $size = null; // Use Content-Disposition 'size' as for the Kolab Format spec. if (isset($part->d_parameters['size'])) { $size = $part->d_parameters['size']; } // we can trust part size only if it's not encoded elseif ($part->encoding == 'binary' || $part->encoding == '7bit' || $part->encoding == '8bit') { $size = $part->size; } $attachments[$key] = [ 'id' => $part->mime_id, 'name' => $part->filename, 'mimetype' => $part->mimetype, 'size' => $size, ]; } } if (!$xml) { rcube::raise_error([ 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Could not find Kolab data part in message $msguid ($this->name).", ], true); return false; } // check kolab format version $format_version = $message->headers->others['x-kolab-mime-version']; if (empty($format_version)) { [$xmltype, $subtype] = explode('.', $object_type); $xmlhead = substr($xml, 0, 512); // detect old Kolab 2.0 format if (strpos($xmlhead, '<' . $xmltype) !== false && strpos($xmlhead, 'xmlns=') === false) { $format_version = '2.0'; } else { $format_version = '3.0'; } // assume 3.0 } // get Kolab format handler for the given type $format = kolab_format::factory($object_type, $format_version); if (is_a($format, 'PEAR_Error')) { return false; } // load Kolab object from XML part $format->load($xml); if ($format->is_valid()) { $object = $format->to_array(['_attachments' => $attachments]); $object['_type'] = $object_type; $object['_msguid'] = $msguid; $object['_mailbox'] = $this->name; $object['_formatobj'] = $format; $object['_size'] = strlen($xml); return $object; } else { // try to extract object UID from XML block if (preg_match('!(.+)!Uims', $xml, $m)) { $msgadd = " UID = " . trim(strip_tags($m[1])); } rcube::raise_error([ 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Could not parse Kolab object data in message $msguid ($this->name)." . ($msgadd ?? ''), ], true); self::save_user_xml("$msguid.xml", $xml); } return false; } /** * Save an object in this folder. * * @param array $object The array that holds the data of the object. * @param string $type The type of the kolab object. * @param string $uid The UID of the old object if it existed before * * @return mixed False on error or IMAP message UID on success */ public function save(&$object, $type = null, $uid = null) { if (!$this->valid || empty($object)) { return false; } if (!$type) { $type = $this->type; } // copy attachments from old message $copyfrom = $object['_copyfrom'] ?? ($object['_msguid'] ?? null); if (!empty($copyfrom) && ($old = $this->cache->get($copyfrom, $type, $object['_mailbox'])) && !empty($old['_attachments'])) { foreach ((array)$old['_attachments'] as $key => $att) { if (!isset($object['_attachments'][$key])) { $object['_attachments'][$key] = $old['_attachments'][$key]; } // unset deleted attachment entries if ($object['_attachments'][$key] == false) { unset($object['_attachments'][$key]); } // load photo.attachment from old Kolab2 format to be directly embedded in xcard block elseif ($type == 'contact' && ($key == 'photo.attachment' || $key == 'kolab-picture.png') && $att['id']) { if (!isset($object['photo'])) { $object['photo'] = $this->get_attachment($copyfrom, $att['id'], $object['_mailbox']); } unset($object['_attachments'][$key]); } } } // save contact photo to attachment for Kolab2 format if (kolab_storage::$version == '2.0' && $object['photo']) { $attkey = 'kolab-picture.png'; // this file name is hard-coded in libkolab/kolabformatV2/contact.cpp $object['_attachments'][$attkey] = [ 'mimetype' => rcube_mime::image_content_type($object['photo']), 'content' => preg_match('![^a-z0-9/=+-]!i', $object['photo']) ? $object['photo'] : base64_decode($object['photo']), ]; } // process attachments if (!empty($object['_attachments'])) { $numatt = count($object['_attachments']); foreach ($object['_attachments'] as $key => $attachment) { // FIXME: kolab_storage and Roundcube attachment hooks use different fields! if (empty($attachment['content']) && !empty($attachment['data'])) { $attachment['content'] = $attachment['data']; unset($attachment['data'], $object['_attachments'][$key]['data']); } // make sure size is set, so object saved in cache contains this info if (!isset($attachment['size'])) { if (!empty($attachment['content'])) { if (is_resource($attachment['content'])) { // this need to be a seekable resource, otherwise // fstat() failes and we're unable to determine size // here nor in rcube_imap_generic before IMAP APPEND $stat = fstat($attachment['content']); $attachment['size'] = $stat ? $stat['size'] : 0; } else { $attachment['size'] = strlen($attachment['content']); } } elseif (!empty($attachment['path'])) { $attachment['size'] = filesize($attachment['path']); } $object['_attachments'][$key] = $attachment; } // generate unique keys (used as content-id) for attachments if (is_numeric($key) && $key < $numatt) { // derrive content-id from attachment file name $ext = preg_match('/(\.[a-z0-9]{1,6})$/i', $attachment['name'], $m) ? $m[1] : null; $basename = preg_replace('/[^a-z0-9_.-]/i', '', basename($attachment['name'], $ext)); // to 7bit ascii if (!$basename) { $basename = 'noname'; } $cid = $basename . '.' . microtime(true) . $key . $ext; $object['_attachments'][$cid] = $attachment; unset($object['_attachments'][$key]); } } } // save recurrence exceptions as individual objects due to lack of support in Kolab v2 format if (kolab_storage::$version == '2.0' && $object['recurrence']['EXCEPTIONS']) { $this->save_recurrence_exceptions($object, $type); } // check IMAP BINARY extension support for 'file' objects // allow configuration to workaround bug in Cyrus < 2.4.17 $rcmail = rcube::get_instance(); $binary = $type == 'file' && !$rcmail->config->get('kolab_binary_disable') && $this->imap->get_capability('BINARY'); $result = false; // generate and save object message if ($raw_msg = $this->build_message($object, $type, $binary, $body_file)) { // resolve old msguid before saving if ($uid && empty($object['_msguid']) && ($msguid = $this->cache->uid2msguid($uid))) { $object['_msguid'] = $msguid; $object['_mailbox'] = $this->name; } $result = $this->imap->save_message($this->name, $raw_msg, null, false, null, null, $binary); // update cache with new UID if ($result) { $old_uid = $object['_msguid'] ?? null; $object['_msguid'] = $result; $object['_mailbox'] = $this->name; if ($old_uid) { // delete old message $this->cache->imap_mode(true); $this->imap->delete_message($old_uid, $object['_mailbox']); $this->cache->imap_mode(false); } // insert/update message in cache $this->cache->save($result, $object, $old_uid); } // remove temp file if ($body_file) { @unlink($body_file); } } return $result; } /** * Save recurrence exceptions as individual objects. * The Kolab v2 format doesn't allow us to save fully embedded exception objects. * * @param array $object Hash array with event properties * @param string $type Object type */ private function save_recurrence_exceptions(&$object, $type = null) { if ($object['recurrence']['EXCEPTIONS']) { $exdates = []; foreach ((array) $object['recurrence']['EXDATE'] as $exdate) { $key = $exdate instanceof DateTimeInterface ? $exdate->format('Y-m-d') : strval($exdate); $exdates[$key] = 1; } // save every exception as individual object foreach ((array) $object['recurrence']['EXCEPTIONS'] as $exception) { $exception['uid'] = self::recurrence_exception_uid($object['uid'], $exception['start']->format('Ymd')); $exception['sequence'] = $object['sequence'] + 1; if ($exception['thisandfuture']) { $exception['recurrence'] = $object['recurrence']; // adjust the recurrence duration of the exception if ($object['recurrence']['COUNT']) { $recurrence = new kolab_date_recurrence($object['_formatobj']); if ($end = $recurrence->end()) { unset($exception['recurrence']['COUNT']); $exception['recurrence']['UNTIL'] = $end; } } // set UNTIL date if we have a thisandfuture exception $untildate = clone $exception['start']; $untildate->sub(new DateInterval('P1D')); $object['recurrence']['UNTIL'] = $untildate; unset($object['recurrence']['COUNT']); } else { - if (!$exdates[$exception['start']->format('Y-m-d')]) { + if (empty($exdates[$exception['start']->format('Y-m-d')])) { $object['recurrence']['EXDATE'][] = clone $exception['start']; } unset($exception['recurrence']); } unset($exception['recurrence']['EXCEPTIONS'], $exception['_formatobj'], $exception['_msguid']); $this->save($exception, $type, $exception['uid']); } unset($object['recurrence']['EXCEPTIONS']); } } /** * Generate an object UID with the given recurrence-ID in a way that it is * unique (the original UID is not a substring) but still recoverable. */ private static function recurrence_exception_uid($uid, $recurrence_id) { $offset = -2; return substr($uid, 0, $offset) . '-' . $recurrence_id . '-' . substr($uid, $offset); } /** * Delete the specified object from this folder. * * @param mixed $object The Kolab object to delete or object UID * @param bool $expunge Should the folder be expunged? * * @return bool True if successful, false on error */ public function delete($object, $expunge = true) { if (!$this->valid) { return false; } $msguid = is_array($object) ? $object['_msguid'] : $this->cache->uid2msguid($object); $success = false; $this->cache->imap_mode(true); if ($msguid && $expunge) { $success = $this->imap->delete_message($msguid, $this->name); } elseif ($msguid) { $success = $this->imap->set_flag($msguid, 'DELETED', $this->name); } $this->cache->imap_mode(false); if ($success) { $this->cache->set($msguid, false); } return $success; } /** * */ public function delete_all() { if (!$this->valid) { return false; } $this->cache->purge(); $this->cache->imap_mode(true); $result = $this->imap->clear_folder($this->name); $this->cache->imap_mode(false); return $result; } /** * Restore a previously deleted object * * @param string $uid Object UID * * @return mixed Message UID on success, false on error */ public function undelete($uid) { if (!$this->valid) { return false; } if ($msguid = $this->cache->uid2msguid($uid, true)) { $this->cache->imap_mode(true); $result = $this->imap->set_flag($msguid, 'UNDELETED', $this->name); $this->cache->imap_mode(false); if ($result) { return $msguid; } } return false; } /** * Move a Kolab object message to another IMAP folder * * @param string $uid Object UID * @param string|kolab_storage_folder $target_folder IMAP folder to move object to * * @return bool True on success, false on failure */ public function move($uid, $target_folder) { if (!$this->valid) { return false; } if (is_string($target_folder)) { $target_folder = kolab_storage::get_folder($target_folder); } if ($msguid = $this->cache->uid2msguid($uid)) { $this->cache->imap_mode(true); $result = $this->imap->move_message($msguid, $target_folder->name, $this->name); $this->cache->imap_mode(false); if ($result) { $new_uid = ($copyuid = $this->imap->conn->data['COPYUID']) ? $copyuid[1] : null; $this->cache->move($msguid, $uid, $target_folder, $new_uid); return true; } else { rcube::raise_error([ 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Failed to move message $msguid to {$target_folder->name}: " . $this->imap->get_error_str(), ], true); } } return false; } /** * Creates source of the configuration object message * * @param array $object The array that holds the data of the object. * @param string $type The type of the kolab object. * @param bool $binary Enables use of binary encoding of attachment(s) * @param string $body_file Reference to filename of message body * * @return mixed Message as string or array with two elements * (one for message file path, second for message headers) */ private function build_message(&$object, $type, $binary, &$body_file) { // load old object to preserve data we don't understand/process $format = null; if (is_object($object['_formatobj'] ?? null)) { $format = $object['_formatobj']; } elseif (!empty($object['_msguid']) && ($old = $this->cache->get($object['_msguid'], $type, $object['_mailbox'] ?? null))) { $format = $old['_formatobj'] ?? null; } // create new kolab_format instance if (!$format) { $format = kolab_format::factory($type, kolab_storage::$version); } if (PEAR::isError($format)) { return false; } $format->set($object); $xml = $format->write(kolab_storage::$version); $object['uid'] = $format->uid; // read UID from format $object['_formatobj'] = $format; if (empty($xml) || !$format->is_valid() || empty($object['uid'])) { return false; } $mime = new Mail_mime("\r\n"); $rcmail = rcube::get_instance(); $headers = []; $files = []; $part_id = 1; $encoding = $binary ? 'binary' : 'base64'; $temp_dir = unslashify($rcmail->config->get('temp_dir')); $marker = null; if ($user_email = $rcmail->get_user_email()) { $headers['From'] = $user_email; $headers['To'] = $user_email; } $headers['Date'] = date('r'); $headers['X-Kolab-Type'] = kolab_format::KTYPE_PREFIX . $type; $headers['X-Kolab-Mime-Version'] = kolab_storage::$version; $headers['Subject'] = $object['uid']; // $headers['Message-ID'] = $rcmail->gen_message_id(); $headers['User-Agent'] = $rcmail->config->get('useragent'); // Check if we have enough memory to handle the message in it // It's faster than using files, so we'll do this if we only can if (!empty($object['_attachments']) && ($mem_limit = parse_bytes(ini_get('memory_limit'))) > 0) { $memory = function_exists('memory_get_usage') ? memory_get_usage() : 16 * 1024 * 1024; // safe value: 16MB foreach ($object['_attachments'] as $attachment) { $memory += $attachment['size']; } // 1.33 is for base64, we need at least 4x more memory than the message size if ($memory * ($binary ? 1 : 1.33) * 4 > $mem_limit) { $marker = '%%%~~~' . md5(microtime(true) . $memory) . '~~~%%%'; $is_file = true; $mime->setParam('delay_file_io', true); } } $mime->headers($headers); $mime->setTXTBody("This is a Kolab Groupware object. " . "To view this object you will need an email client that understands the Kolab Groupware format. " . "For a list of such email clients please visit https://www.kolab.org/\n\n"); $ctype = kolab_storage::$version == '2.0' ? $format->CTYPEv2 : $format->CTYPE; // Convert new lines to \r\n, to wrokaround "NO Message contains bare newlines" // when APPENDing from temp file $xml = preg_replace('/\r?\n/', "\r\n", $xml); $mime->addAttachment( $xml, // file $ctype, // content-type 'kolab.xml', // filename false, // is_file '8bit', // encoding 'attachment', // disposition RCUBE_CHARSET // charset ); $part_id++; $is_file = false; // FIXME: ??? // save object attachments as separate parts foreach ((array)($object['_attachments'] ?? []) as $key => $att) { if (empty($att['content']) && !empty($att['id'])) { // @TODO: use IMAP CATENATE to skip attachment fetch+push operation $msguid = !empty($object['_copyfrom']) ? $object['_copyfrom'] : (!empty($object['_msguid']) ? $object['_msguid'] : $object['uid']); + // @phpstan-ignore-next-line if ($is_file) { $att['path'] = tempnam($temp_dir, 'rcmAttmnt'); if (($fp = fopen($att['path'], 'w')) && $this->get_attachment($msguid, $att['id'], $object['_mailbox'], false, $fp, true)) { fclose($fp); } else { return false; } } else { $att['content'] = $this->get_attachment($msguid, $att['id'], $object['_mailbox'], false, null, true); } } $headers = ['Content-ID' => Mail_mimePart::encodeHeader('Content-ID', '<' . $key . '>', RCUBE_CHARSET, 'quoted-printable')]; $name = !empty($att['name']) ? $att['name'] : $key; // To store binary files we can use faster method // without writting full message content to a temporary file but // directly to IMAP, see rcube_imap_generic::append(). // I.e. use file handles where possible if (!empty($att['path'])) { + // @phpstan-ignore-next-line if ($is_file && $binary) { $files[] = fopen($att['path'], 'r'); $mime->addAttachment($marker, $att['mimetype'], $name, false, $encoding, 'attachment', '', '', '', null, null, '', RCUBE_CHARSET, $headers); } else { $mime->addAttachment($att['path'], $att['mimetype'], $name, true, $encoding, 'attachment', '', '', '', null, null, '', RCUBE_CHARSET, $headers); } } else { + // @phpstan-ignore-next-line if (is_resource($att['content']) && $is_file && $binary) { $files[] = $att['content']; $mime->addAttachment($marker, $att['mimetype'], $name, false, $encoding, 'attachment', '', '', '', null, null, '', RCUBE_CHARSET, $headers); } else { if (is_resource($att['content'])) { @rewind($att['content']); $att['content'] = stream_get_contents($att['content']); } $mime->addAttachment($att['content'], $att['mimetype'], $name, false, $encoding, 'attachment', '', '', '', null, null, '', RCUBE_CHARSET, $headers); } } $object['_attachments'][$key]['id'] = ++$part_id; } // @phpstan-ignore-next-line if (!$is_file || !empty($files)) { $message = $mime->getMessage(); } // parse message and build message array with // attachment file pointers in place of file markers // @phpstan-ignore-next-line if (!empty($files)) { $message = explode($marker, $message); $tmp = []; foreach ($message as $msg_part) { $tmp[] = $msg_part; if ($file = array_shift($files)) { $tmp[] = $file; } } $message = $tmp; } // write complete message body into temp file + // @phpstan-ignore-next-line elseif ($is_file) { // use common temp dir $body_file = tempnam($temp_dir, 'rcmMsg'); if (PEAR::isError($mime_result = $mime->saveMessageBody($body_file))) { rcube::raise_error( ['code' => 650, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Could not create message: " . $mime_result->getMessage()], true, false ); return false; } $message = [trim($mime->txtHeaders()) . "\r\n\r\n", fopen($body_file, 'r')]; } return $message; } /** * Triggers any required updates after changes within the * folder. This is currently only required for handling free/busy * information with Kolab. * * @return bool|PEAR_Error True if successfull. */ public function trigger() { $owner = $this->get_owner(); $result = false; $url = kolab_storage::get_freebusy_server(); switch ($this->type) { case 'event': if ($url && $this->get_namespace() == 'personal') { $result = $this->trigger_url( sprintf( '%s/trigger/%s/%s.pfb', $url, urlencode($owner), urlencode($this->imap->mod_folder($this->name)) ), $this->imap->options['user'], $this->imap->options['password'] ); } break; default: return true; } if ($result instanceof PEAR_Error) { + // @phpstan-ignore-next-line return PEAR::raiseError( sprintf("Failed triggering folder %s. Error was: %s", $this->name, $result->getMessage()) ); } return $result; } /** * Triggers a URL. * * @param string $url The URL to be triggered. * @param string $auth_user Username to authenticate with * @param string $auth_passwd Password for basic auth * * @return bool|PEAR_Error True if successfull. */ private function trigger_url($url, $auth_user = null, $auth_passwd = null) { try { $request = libkolab::http_request($url); // set authentication credentials if ($auth_user && $auth_passwd) { $request->setAuth($auth_user, $auth_passwd); } $result = $request->send(); // rcube::write_log('trigger', $result->getBody()); } catch (Exception $e) { + // @phpstan-ignore-next-line return PEAR::raiseError($e->getMessage()); } return true; } /** * Log content to a file in per_user_loggin dir if configured */ private static function save_user_xml($filename, $content) { $rcmail = rcube::get_instance(); if ($rcmail->config->get('kolab_format_error_log')) { $log_dir = $rcmail->config->get('log_dir', RCUBE_INSTALL_PATH . 'logs'); $user_name = $rcmail->get_user_name(); $log_dir = $log_dir . '/' . $user_name; if (!empty($user_name) && is_writable($log_dir)) { file_put_contents("$log_dir/$filename", $content); } } } } diff --git a/plugins/tasklist/drivers/caldav/tasklist_caldav_driver.php b/plugins/tasklist/drivers/caldav/tasklist_caldav_driver.php index 273fd4ad..9437700e 100644 --- a/plugins/tasklist/drivers/caldav/tasklist_caldav_driver.php +++ b/plugins/tasklist/drivers/caldav/tasklist_caldav_driver.php @@ -1,1619 +1,1617 @@ * * 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 tasklist_caldav_driver extends tasklist_driver { // features supported by the backend public $alarms = false; public $attachments = true; public $attendees = true; public $undelete = false; // task undelete action public $alarm_types = ['DISPLAY','AUDIO']; public $search_more_results; private $rc; private $plugin; private $storage; private $lists; private $folders = []; private $tasks = []; - private $tags = []; private $bonnie_api = false; /** * Default constructor */ public function __construct($plugin) { $this->rc = $plugin->rc; $this->plugin = $plugin; // Initialize the CalDAV storage $url = $this->rc->config->get('tasklist_caldav_server', 'http://localhost'); $this->storage = new kolab_storage_dav($url); // get configuration for the Bonnie API // $this->bonnie_api = libkolab::get_bonnie_api(); // $this->plugin->register_action('folder-acl', [$this, 'folder_acl']); } /** * Read available calendars for the current user and store them internally */ private function _read_lists($force = false) { // already read sources if (isset($this->lists) && !$force) { return $this->lists; } // get all folders that have type "task" $folders = $this->storage->get_folders('task'); $this->lists = $this->folders = []; $prefs = $this->rc->config->get('kolab_tasklists', []); foreach ($folders as $folder) { $tasklist = $this->folder_props($folder, $prefs); $this->lists[$tasklist['id']] = $tasklist; $this->folders[$tasklist['id']] = $folder; // $this->folders[$folder->name] = $folder; } return $this->lists; } /** * Derive list properties from the given kolab_storage_folder object */ protected function folder_props($folder, $prefs) { if ($folder->get_namespace() == 'personal') { $norename = false; $editable = true; $rights = 'lrswikxtea'; $alarms = true; } else { $alarms = false; $rights = 'lr'; $editable = false; if ($myrights = $folder->get_myrights()) { $rights = $myrights; if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false) { $editable = strpos($rights, 'i') !== false; } } $info = $folder->get_folder_info(); $norename = !$editable || $info['norename'] || $info['protected']; } $list_id = $folder->id; return [ 'id' => $list_id, 'name' => $folder->get_name(), 'listname' => $folder->get_foldername(), 'editname' => $folder->get_foldername(), 'color' => $folder->get_color('0000CC'), 'showalarms' => $prefs[$list_id]['showalarms'] ?? $alarms, 'editable' => $editable, 'rights' => $rights, 'norename' => $norename, 'active' => !isset($prefs[$list_id]['active']) || !empty($prefs[$list_id]['active']), 'owner' => $folder->get_owner(), 'parentfolder' => $folder->get_parent(), 'default' => $folder->default, 'virtual' => $folder instanceof kolab_storage_folder_virtual, 'children' => true, // TODO: determine if that folder indeed has child folders // 'subscribed' => (bool) $folder->is_subscribed(), 'removable' => !$folder->default, 'subtype' => $folder->subtype, 'group' => $folder->default ? 'default' : $folder->get_namespace(), 'class' => trim($folder->get_namespace() . ($folder->default ? ' default' : '')), 'caldavuid' => '', // $folder->get_uid(), 'history' => !empty($this->bonnie_api), ]; } /** * Get a list of available task lists from this source * * @param int $filter Bitmask defining filter criterias. * See FILTER_* constants for possible values. * @param ?array $tree * * @return array */ public function get_lists($filter = 0, &$tree = null) { $this->_read_lists(); $folders = $this->filter_folders($filter); $prefs = $this->rc->config->get('kolab_tasklists', []); $lists = []; foreach ($folders as $folder) { $parent_id = null; $list_id = $folder->id; $fullname = $folder->get_name(); $listname = $folder->get_foldername(); // special handling for virtual folders if ($folder instanceof kolab_storage_folder_user) { $lists[$list_id] = [ 'id' => $list_id, 'name' => $fullname, 'listname' => $listname, 'title' => $folder->get_title(), 'virtual' => true, 'editable' => false, 'rights' => 'l', 'group' => 'other virtual', 'class' => 'user', 'parent' => $parent_id, ]; } elseif ($folder instanceof kolab_storage_folder_virtual) { $lists[$list_id] = [ 'id' => $list_id, 'name' => $fullname, 'listname' => $listname, 'virtual' => true, 'editable' => false, 'rights' => 'l', 'group' => $folder->get_namespace(), 'class' => 'folder', 'parent' => $parent_id, ]; } else { if (empty($this->lists[$list_id])) { $this->lists[$list_id] = $this->folder_props($folder, $prefs); $this->folders[$list_id] = $folder; } // $this->lists[$list_id]['parent'] = $parent_id; $lists[$list_id] = $this->lists[$list_id]; } } return $lists; } /** * Get list of folders according to specified filters * * @param int $filter Bitmask defining restrictions. See FILTER_* constants for possible values. * * @return array List of task folders */ protected function filter_folders($filter) { $this->_read_lists(); $folders = []; foreach ($this->lists as $id => $list) { if (!empty($this->folders[$id])) { $folder = $this->folders[$id]; if ($folder->get_namespace() == 'personal') { $folder->editable = true; } elseif ($rights = $folder->get_myrights()) { if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false) { $folder->editable = strpos($rights, 'i') !== false; } } $folders[] = $folder; } } $plugin = $this->rc->plugins->exec_hook('tasklist_list_filter', [ 'list' => $folders, 'filter' => $filter, 'tasklists' => $folders, ]); if ($plugin['abort'] || !$filter) { return $plugin['tasklists'] ?? []; } $personal = $filter & self::FILTER_PERSONAL; $shared = $filter & self::FILTER_SHARED; $tasklists = []; foreach ($folders as $folder) { if (($filter & self::FILTER_WRITEABLE) && !$folder->editable) { continue; } /* if (($filter & self::FILTER_INSERTABLE) && !$folder->insert) { continue; } if (($filter & self::FILTER_ACTIVE) && !$folder->is_active()) { continue; } if (($filter & self::FILTER_PRIVATE) && $folder->subtype != 'private') { continue; } if (($filter & self::FILTER_CONFIDENTIAL) && $folder->subtype != 'confidential') { continue; } */ if ($personal || $shared) { $ns = $folder->get_namespace(); if (!(($personal && $ns == 'personal') || ($shared && $ns == 'shared'))) { continue; } } $tasklists[$folder->id] = $folder; } return $tasklists; } /** * Get the kolab_calendar instance for the given calendar ID * * @param string $id List identifier (encoded imap folder name) * * @return ?kolab_storage_folder Object nor null if list doesn't exist */ protected function get_folder($id) { $this->_read_lists(); return $this->folders[$id] ?? null; } /** * Create a new list assigned to the current user * * @param array $prop Hash array with list properties * - name: List name * - color: The color of the list * - showalarms: True if alarms are enabled * * @return string|false ID of the new list on success, False on error */ public function create_list(&$prop) { $prop['type'] = 'task'; $id = $this->storage->folder_update($prop); if ($id === false) { return false; } $prefs['kolab_tasklists'] = $this->rc->config->get('kolab_tasklists', []); if (isset($prop['showalarms'])) { $prefs['kolab_tasklists'][$id]['showalarms'] = $prop['showalarms'] ? true : false; } if (isset($prefs['kolab_tasklists'][$id])) { $this->rc->user->save_prefs($prefs); } // force page reload to properly render folder hierarchy if (!empty($prop['parent'])) { $prop['_reload'] = true; } else { $folder = $this->get_folder($id); $prop += $this->folder_props($folder, []); } return $id; } /** * Update properties of an existing tasklist * * @param array $prop Hash array with list properties * - id: List Identifier * - name: List name * - color: The color of the list * - showalarms: True if alarms are enabled (if supported) * * @return bool True on success, Fales on failure */ public function edit_list(&$prop) { if (!empty($prop['id'])) { $id = $prop['id']; $prop['type'] = 'task'; if ($this->storage->folder_update($prop) !== false) { $prefs['kolab_tasklists'] = $this->rc->config->get('kolab_tasklists', []); if (isset($prop['showalarms'])) { $prefs['kolab_tasklists'][$id]['showalarms'] = $prop['showalarms'] ? true : false; } if (isset($prefs['kolab_tasklists'][$id])) { $this->rc->user->save_prefs($prefs); } /* // force page reload if folder name/hierarchy changed if ($newfolder != $prop['oldname']) { $prop['_reload'] = true; } */ return true; } } return false; } /** * Set active/subscribed state of a list * * @param array $prop Hash array with list properties * - id: List Identifier * - active: True if list is active, false if not * - permanent: True if list is to be subscribed permanently * * @return bool True on success, Fales on failure */ public function subscribe_list($prop) { if (!empty($prop['id'])) { $prefs['kolab_tasklists'] = $this->rc->config->get('kolab_tasklists', []); if (isset($prop['permanent'])) { $prefs['kolab_tasklists'][$prop['id']]['permanent'] = intval($prop['permanent']); } if (isset($prop['active'])) { $prefs['kolab_tasklists'][$prop['id']]['active'] = intval($prop['active']); } $this->rc->user->save_prefs($prefs); return true; } return false; } /** * Delete the given list with all its contents * * @param array $prop Hash array with list properties * - id: list Identifier * * @return bool True on success, Fales on failure */ public function delete_list($prop) { if (!empty($prop['id'])) { if ($this->storage->folder_delete($prop['id'], 'task')) { // remove folder from user prefs $prefs['kolab_tasklists'] = $this->rc->config->get('kolab_tasklists', []); if (isset($prefs['kolab_tasklists'][$prop['id']])) { unset($prefs['kolab_tasklists'][$prop['id']]); $this->rc->user->save_prefs($prefs); } return true; } } return false; } /** * Search for shared or otherwise not listed tasklists the user has access * * @param string $query Search string * @param string $source Section/source to search * * @return array List of tasklists */ public function search_lists($query, $source) { /* $this->search_more_results = false; $this->lists = $this->folders = array(); // find unsubscribed IMAP folders that have "event" type if ($source == 'folders') { foreach ((array)kolab_storage::search_folders('task', $query, array('other')) as $folder) { $this->folders[$folder->id] = $folder; $this->lists[$folder->id] = $this->folder_props($folder, array()); } } // search other user's namespace via LDAP else if ($source == 'users') { $limit = $this->rc->config->get('autocomplete_max', 15) * 2; // we have slightly more space, so display twice the number foreach (kolab_storage::search_users($query, 0, array(), $limit * 10) as $user) { $folders = array(); // search for tasks folders shared by this user foreach (kolab_storage::list_user_folders($user, 'task', false) as $foldername) { $folders[] = new kolab_storage_folder($foldername, 'task'); } if (count($folders)) { $userfolder = new kolab_storage_folder_user($user['kolabtargetfolder'], '', $user); $this->folders[$userfolder->id] = $userfolder; $this->lists[$userfolder->id] = $this->folder_props($userfolder, array()); foreach ($folders as $folder) { $this->folders[$folder->id] = $folder; $this->lists[$folder->id] = $this->folder_props($folder, array()); $count++; } } if ($count >= $limit) { $this->search_more_results = true; break; } } } return $this->get_lists(); */ return []; } /** * Get a list of tags to assign tasks to * * @return array List of tags */ public function get_tags() { return []; } /** * Get number of tasks matching the given filter * * @param array $lists List of lists to count tasks of * * @return array Hash array with counts grouped by status (all|flagged|completed|today|tomorrow|nodate) */ public function count_tasks($lists = null) { if (empty($lists)) { $lists = $this->_read_lists(); $lists = array_keys($lists); } elseif (is_string($lists)) { $lists = explode(',', $lists); } $today_date = new DateTime('now', $this->plugin->timezone); $today = $today_date->format('Y-m-d'); $tomorrow_date = new DateTime('now + 1 day', $this->plugin->timezone); $tomorrow = $tomorrow_date->format('Y-m-d'); $counts = ['all' => 0, 'today' => 0, 'tomorrow' => 0, 'later' => 0, 'overdue' => 0]; foreach ($lists as $list_id) { if (!$folder = $this->get_folder($list_id)) { continue; } foreach ($folder->select([['tags', '!~', 'x-complete']], true) as $record) { $rec = $this->_to_rcube_task($record, $list_id, false); if ($this->is_complete($rec)) { // don't count complete tasks continue; } $counts['all']++; if (empty($rec['date'])) { $counts['later']++; } elseif ($rec['date'] == $today) { $counts['today']++; } elseif ($rec['date'] == $tomorrow) { $counts['tomorrow']++; } elseif ($rec['date'] < $today) { $counts['overdue']++; } elseif ($rec['date'] > $tomorrow) { $counts['later']++; } } } return $counts; } /** * Get all task records matching the given filter * * @param array $filter Hash array with filter criterias: * - mask: Bitmask representing the filter selection (check against tasklist::FILTER_MASK_* constants) * - from: Date range start as string (Y-m-d) * - to: Date range end as string (Y-m-d) * - search: Search query string * - uid: Task UIDs * @param array $lists List of lists to get tasks from * * @return array List of tasks records matchin the criteria */ public function list_tasks($filter, $lists = null) { if (empty($lists)) { $lists = $this->_read_lists(); $lists = array_keys($lists); } elseif (is_string($lists)) { $lists = explode(',', $lists); } $results = []; // query Kolab storage cache $query = []; if (isset($filter['mask']) && ($filter['mask'] & tasklist::FILTER_MASK_COMPLETE)) { $query[] = ['tags', '~', 'x-complete']; } elseif (empty($filter['since'])) { $query[] = ['tags', '!~', 'x-complete']; } // full text search (only works with cache enabled) if (!empty($filter['search'])) { $search = mb_strtolower($filter['search']); foreach (rcube_utils::normalize_string($search, true) as $word) { $query[] = ['words', '~', $word]; } } if (!empty($filter['since'])) { $query[] = ['changed', '>=', $filter['since']]; } if (!empty($filter['uid'])) { $query[] = ['uid', '=', (array) $filter['uid']]; } foreach ($lists as $list_id) { if (!$folder = $this->get_folder($list_id)) { continue; } foreach ($folder->select($query) as $record) { // TODO: post-filter tasks returned from storage $record['list_id'] = $list_id; $results[] = $record; } } foreach (array_keys($results) as $idx) { $results[$idx] = $this->_to_rcube_task($results[$idx], $results[$idx]['list_id']); } return $results; } /** * Return data of a specific task * * @param mixed $prop Hash array with task properties or task UID * @param int $filter Bitmask defining filter criterias for folders. * See FILTER_* constants for possible values. * * @return array|false Hash array with task properties or false if not found */ public function get_task($prop, $filter = 0) { $this->_parse_id($prop); $id = $prop['uid']; $list_id = $prop['list']; $folders = $list_id ? [$list_id => $this->get_folder($list_id)] : $this->get_lists($filter); // find task in the available folders foreach ($folders as $list_id => $folder) { if (is_array($folder)) { $folder = $this->folders[$list_id]; } if (is_numeric($list_id) || !$folder) { continue; } if (empty($this->tasks[$id]) && ($object = $folder->get_object($id))) { $this->tasks[$id] = $this->_to_rcube_task($object, $list_id); break; } } return $this->tasks[$id] ?? false; } /** * Get all decendents of the given task record * * @param mixed $prop Hash array with task properties or task UID * @param bool $recursive True if all childrens children should be fetched * * @return array List of all child task IDs */ public function get_childs($prop, $recursive = false) { if (is_string($prop)) { $task = $this->get_task($prop); $prop = ['uid' => $task['uid'], 'list' => $task['list']]; } else { $this->_parse_id($prop); } $childs = []; $list_id = $prop['list']; $task_ids = [$prop['uid']]; $folder = $this->get_folder($list_id); // query for childs (recursively) while ($folder && !empty($task_ids)) { $query_ids = []; foreach ($task_ids as $task_id) { $query = [['tags','=','x-parent:' . $task_id]]; foreach ($folder->select($query) as $record) { // don't rely on kolab_storage_folder filtering if ($record['parent_id'] == $task_id) { $childs[] = $list_id . ':' . $record['uid']; $query_ids[] = $record['uid']; } } } if (!$recursive) { break; } $task_ids = $query_ids; } return $childs; } /** * Provide a list of revisions for the given task * * @param array $prop Hash array with task properties * * @return array|false List of changes, each as a hash array * @see tasklist_driver::get_task_changelog() */ public function get_task_changelog($prop) { if (empty($this->bonnie_api)) { return false; } /* list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($prop); $result = $uid && $mailbox ? $this->bonnie_api->changelog('task', $uid, $mailbox, $msguid) : null; if (is_array($result) && $result['uid'] == $uid) { return $result['changes']; } */ return false; } /** * Return full data of a specific revision of an event * * @param mixed $prop UID string or hash array with task properties * @param mixed $rev Revision number * * @return array|false Task object as hash array * @see tasklist_driver::get_task_revision() */ public function get_task_revison($prop, $rev) { if (empty($this->bonnie_api)) { return false; } /* $this->_parse_id($prop); $uid = $prop['uid']; $list_id = $prop['list']; list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($prop); // call Bonnie API $result = $this->bonnie_api->get('task', $uid, $rev, $mailbox, $msguid); if (is_array($result) && $result['uid'] == $uid && !empty($result['xml'])) { $format = kolab_format::factory('task'); $format->load($result['xml']); $rec = $format->to_array(); $format->get_attachments($rec, true); if ($format->is_valid()) { $rec = self::_to_rcube_task($rec, $list_id, false); $rec['rev'] = $result['rev']; return $rec; } } */ return false; } /** * Command the backend to restore a certain revision of a task. * This shall replace the current object with an older version. * * @param mixed $prop UID string or hash array with task properties * @param mixed $rev Revision number * * @return bool True on success, False on failure * @see tasklist_driver::restore_task_revision() */ public function restore_task_revision($prop, $rev) { if (empty($this->bonnie_api)) { return false; } /* $this->_parse_id($prop); $uid = $prop['uid']; $list_id = $prop['list']; list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($prop); $folder = $this->get_folder($list_id); $success = false; if ($folder && ($raw_msg = $this->bonnie_api->rawdata('task', $uid, $rev, $mailbox))) { $imap = $this->rc->get_storage(); // insert $raw_msg as new message if ($imap->save_message($folder->name, $raw_msg, null, false)) { $success = true; // delete old revision from imap and cache $imap->delete_message($msguid, $folder->name); $folder->cache->set($msguid, false); } } return $success; */ return false; } /** * Get a list of property changes beteen two revisions of a task object * * @param array $prop Hash array with task properties * @param mixed $rev1 Revision: "from" * @param mixed $rev2 Revision: "to" * * @return array|false List of property changes, each as a hash array * @see tasklist_driver::get_task_diff() */ public function get_task_diff($prop, $rev1, $rev2) { /* $this->_parse_id($prop); $uid = $prop['uid']; $list_id = $prop['list']; list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($prop); // call Bonnie API $result = $this->bonnie_api->diff('task', $uid, $rev1, $rev2, $mailbox, $msguid, $instance_id); if (is_array($result) && $result['uid'] == $uid) { $result['rev1'] = $rev1; $result['rev2'] = $rev2; $keymap = array( 'start' => 'start', 'due' => 'date', 'dstamp' => 'changed', 'summary' => 'title', 'alarm' => 'alarms', 'attendee' => 'attendees', 'attach' => 'attachments', 'rrule' => 'recurrence', 'related-to' => 'parent_id', 'percent-complete' => 'complete', 'lastmodified-date' => 'changed', ); $prop_keymaps = array( 'attachments' => array('fmttype' => 'mimetype', 'label' => 'name'), 'attendees' => array('partstat' => 'status'), ); $special_changes = array(); // map kolab event properties to keys the client expects array_walk($result['changes'], function(&$change, $i) use ($keymap, $prop_keymaps, $special_changes) { if (array_key_exists($change['property'], $keymap)) { $change['property'] = $keymap[$change['property']]; } if ($change['property'] == 'priority') { $change['property'] = 'flagged'; $change['old'] = $change['old'] == 1 ? $this->plugin->gettext('yes') : null; $change['new'] = $change['new'] == 1 ? $this->plugin->gettext('yes') : null; } // map alarms trigger value if ($change['property'] == 'alarms') { if (is_array($change['old']) && is_array($change['old']['trigger'])) $change['old']['trigger'] = $change['old']['trigger']['value']; if (is_array($change['new']) && is_array($change['new']['trigger'])) $change['new']['trigger'] = $change['new']['trigger']['value']; } // make all property keys uppercase if ($change['property'] == 'recurrence') { $special_changes['recurrence'] = $i; foreach (array('old','new') as $m) { if (is_array($change[$m])) { $props = array(); foreach ($change[$m] as $k => $v) { $props[strtoupper($k)] = $v; } $change[$m] = $props; } } } // map property keys names if (is_array($prop_keymaps[$change['property']])) { foreach ($prop_keymaps[$change['property']] as $k => $dest) { if (is_array($change['old']) && array_key_exists($k, $change['old'])) { $change['old'][$dest] = $change['old'][$k]; unset($change['old'][$k]); } if (is_array($change['new']) && array_key_exists($k, $change['new'])) { $change['new'][$dest] = $change['new'][$k]; unset($change['new'][$k]); } } } if ($change['property'] == 'exdate') { $special_changes['exdate'] = $i; } else if ($change['property'] == 'rdate') { $special_changes['rdate'] = $i; } }); // merge some recurrence changes foreach (array('exdate','rdate') as $prop) { if (array_key_exists($prop, $special_changes)) { $exdate = $result['changes'][$special_changes[$prop]]; if (array_key_exists('recurrence', $special_changes)) { $recurrence = &$result['changes'][$special_changes['recurrence']]; } else { $i = count($result['changes']); $result['changes'][$i] = array('property' => 'recurrence', 'old' => array(), 'new' => array()); $recurrence = &$result['changes'][$i]['recurrence']; } $key = strtoupper($prop); $recurrence['old'][$key] = $exdate['old']; $recurrence['new'][$key] = $exdate['new']; unset($result['changes'][$special_changes[$prop]]); } } return $result; } */ return false; } /** * Helper method to resolved the given task identifier into uid and folder * * @return array (uid,folder,msguid) tuple */ + /* private function _resolve_task_identity($prop) { - /* - $mailbox = $msguid = null; + $mailbox = $msguid = null; - $this->_parse_id($prop); - $uid = $prop['uid']; - $list_id = $prop['list']; + $this->_parse_id($prop); + $uid = $prop['uid']; + $list_id = $prop['list']; - if ($folder = $this->get_folder($list_id)) { - $mailbox = $folder->get_mailbox_id(); + if ($folder = $this->get_folder($list_id)) { + $mailbox = $folder->get_mailbox_id(); - // get task object from storage in order to get the real object uid an msguid - if ($rec = $folder->get_object($uid)) { - $msguid = $rec['_msguid']; - $uid = $rec['uid']; - } - } + // get task object from storage in order to get the real object uid an msguid + if ($rec = $folder->get_object($uid)) { + $msguid = $rec['_msguid']; + $uid = $rec['uid']; + } + } - return array($uid, $mailbox, $msguid); - */ - return []; + return array($uid, $mailbox, $msguid); } + */ /** * Get a list of pending alarms to be displayed to the user * * @param int $time Current time (unix timestamp) * @param mixed $lists List of list IDs to show alarms for (either as array or comma-separated string) * * @return array A list of alarms, each encoded as hash array with task properties * @see tasklist_driver::pending_alarms() */ public function pending_alarms($time, $lists = null) { $interval = 300; $time -= $time % 60; $slot = $time; $slot -= $slot % $interval; $last = $time - max(60, $this->rc->config->get('refresh_interval', 0)); $last -= $last % $interval; // only check for alerts once in 5 minutes if ($last == $slot) { return []; } if ($lists && is_string($lists)) { $lists = explode(',', $lists); } $time = $slot + $interval; $candidates = []; $query = [ ['tags', '=', 'x-has-alarms'], ['tags', '!=', 'x-complete'], ]; $this->_read_lists(); foreach ($this->lists as $lid => $list) { // skip lists with alarms disabled if (empty($list['showalarms']) || ($lists && !in_array($lid, $lists))) { continue; } $folder = $this->get_folder($lid); foreach ($folder->select($query) as $record) { if ((empty($record['valarms']) && empty($record['alarms'])) || $record['status'] == 'COMPLETED' || $record['complete'] == 100 ) { // don't trust the query :-) continue; } $task = $this->_to_rcube_task($record, $lid, false); // add to list if alarm is set $alarm = libcalendaring::get_next_alarm($task, 'task'); if ($alarm && !empty($alarm['time']) && $alarm['time'] <= $time && in_array($alarm['action'], $this->alarm_types)) { $id = $alarm['id']; // use alarm-id as primary identifier $candidates[$id] = [ 'id' => $id, 'title' => $task['title'] ?? null, 'date' => $task['date'] ?? null, 'time' => $task['time'], 'notifyat' => $alarm['time'], 'action' => $alarm['action'] ?? null, ]; } } } // get alarm information stored in local database if (!empty($candidates)) { $alarm_ids = array_map([$this->rc->db, 'quote'], array_keys($candidates)); $result = $this->rc->db->query( "SELECT *" . " FROM " . $this->rc->db->table_name('kolab_alarms', true) . " WHERE `alarm_id` IN (" . implode(',', $alarm_ids) . ")" . " AND `user_id` = ?", $this->rc->user->ID ); while ($result && ($rec = $this->rc->db->fetch_assoc($result))) { $dbdata[$rec['alarm_id']] = $rec; } } $alarms = []; foreach ($candidates as $id => $task) { // skip dismissed if (!empty($dbdata[$id]['dismissed'])) { continue; } // snooze function may have shifted alarm time $notifyat = !empty($dbdata[$id]['notifyat']) ? strtotime($dbdata[$id]['notifyat']) : $task['notifyat']; if ($notifyat <= $time) { $alarms[] = $task; } } return $alarms; } /** * (User) feedback after showing an alarm notification * This should mark the alarm as 'shown' or snooze it for the given amount of time * * @param string $id Task identifier * @param int $snooze Suspend the alarm for this number of seconds */ public function dismiss_alarm($id, $snooze = 0) { // delete old alarm entry $this->rc->db->query( "DELETE FROM " . $this->rc->db->table_name('kolab_alarms', true) . " WHERE `alarm_id` = ? AND `user_id` = ?", $id, $this->rc->user->ID ); // set new notifyat time or unset if not snoozed $notifyat = $snooze > 0 ? date('Y-m-d H:i:s', time() + $snooze) : null; $query = $this->rc->db->query( "INSERT INTO " . $this->rc->db->table_name('kolab_alarms', true) . " (`alarm_id`, `user_id`, `dismissed`, `notifyat`) VALUES (?, ?, ?, ?)", $id, $this->rc->user->ID, $snooze > 0 ? 0 : 1, $notifyat ); return $this->rc->db->affected_rows($query); } /** * Remove alarm dismissal or snooze state * * @param string $id Task identifier */ public function clear_alarms($id) { // delete alarm entry $this->rc->db->query( "DELETE FROM " . $this->rc->db->table_name('kolab_alarms', true) . " WHERE `alarm_id` = ? AND `user_id` = ?", $id, $this->rc->user->ID ); return true; } /** * Extract uid + list identifiers from the given input * * @param array|string $prop Array or a string with task identifier(s) */ private function _parse_id(&$prop) { $id = null; if (is_array($prop)) { // 'uid' + 'list' available, nothing to be done if (!empty($prop['uid']) && !empty($prop['list'])) { return; } // 'id' is given if (!empty($prop['id'])) { if (!empty($prop['list'])) { $list_id = !empty($prop['_fromlist']) ? $prop['_fromlist'] : $prop['list']; if (strpos($prop['id'], $list_id . ':') === 0) { $prop['uid'] = substr($prop['id'], strlen($list_id) + 1); } else { $prop['uid'] = $prop['id']; } } else { $id = $prop['id']; } } } else { $id = strval($prop); $prop = []; } // split 'id' into list + uid if (!empty($id)) { if (strpos($id, ':')) { [$list, $uid] = explode(':', $id, 2); $prop['uid'] = $uid; $prop['list'] = $list; } else { $prop['uid'] = $id; } } } /** * Convert from Kolab_Format to internal representation */ private function _to_rcube_task($record, $list_id, $all = true) { $id_prefix = $list_id . ':'; $task = [ 'id' => $id_prefix . $record['uid'], 'uid' => $record['uid'], 'title' => $record['title'] ?? '', // 'location' => $record['location'], 'description' => $record['description'] ?? '', 'flagged' => !empty($record['priority']) && $record['priority'] == 1, 'complete' => floatval(($record['complete'] ?? 0) / 100), 'status' => $record['status'] ?? null, 'parent_id' => !empty($record['parent_id']) ? $id_prefix . $record['parent_id'] : null, 'recurrence' => $record['recurrence'] ?? [], 'attendees' => $record['attendees'] ?? [], 'organizer' => $record['organizer'] ?? null, 'sequence' => $record['sequence'] ?? null, 'list' => $list_id, 'links' => [], // $record['links'], 'tags' => [], // $record['tags'], ]; // convert from DateTime to internal date format if (isset($record['due']) && $record['due'] instanceof DateTimeInterface) { $due = $this->plugin->lib->adjust_timezone($record['due']); $task['date'] = $due->format('Y-m-d'); if (empty($record['due']->_dateonly)) { $task['time'] = $due->format('H:i'); } } // convert from DateTime to internal date format if (isset($record['start']) && $record['start'] instanceof DateTimeInterface) { $start = $this->plugin->lib->adjust_timezone($record['start']); $task['startdate'] = $start->format('Y-m-d'); if (empty($record['start']->_dateonly)) { $task['starttime'] = $start->format('H:i'); } } if (isset($record['changed']) && $record['changed'] instanceof DateTimeInterface) { $task['changed'] = $record['changed']; } if (isset($record['created']) && $record['created'] instanceof DateTimeInterface) { $task['created'] = $record['created']; } if (isset($record['valarms'])) { $task['valarms'] = $record['valarms']; } elseif (isset($record['alarms'])) { $task['alarms'] = $record['alarms']; } if (!empty($task['attendees'])) { foreach ((array) $task['attendees'] as $i => $attendee) { if (isset($attendee['delegated-from']) && is_array($attendee['delegated-from'])) { $task['attendees'][$i]['delegated-from'] = implode(', ', $attendee['delegated-from']); } if (isset($attendee['delegated-to']) && is_array($attendee['delegated-to'])) { $task['attendees'][$i]['delegated-to'] = implode(', ', $attendee['delegated-to']); } } } if (!empty($record['_attachments'])) { $attachments = []; foreach ($record['_attachments'] as $key => $attachment) { if ($attachment !== false) { if (empty($attachment['name'])) { $attachment['name'] = $key; } $attachments[] = $attachment; } } $task['attachments'] = $attachments; } return $task; } /** * Convert the given task record into a data structure that can be passed to kolab_storage backend for saving * (opposite of self::_to_rcube_event()) */ private function _from_rcube_task($task, $old = []) { $object = $task; $id_prefix = $task['list'] . ':'; $toDT = function ($date) { // Convert DateTime into libcalendaring_datetime return libcalendaring_datetime::createFromFormat( 'Y-m-d\\TH:i:s', $date->format('Y-m-d\\TH:i:s'), $date->getTimezone() ); }; if (!empty($task['date'])) { $object['due'] = $toDT(rcube_utils::anytodatetime($task['date'] . ' ' . ($task['time'] ?? ''), $this->plugin->timezone)); if (empty($task['time'])) { $object['due']->_dateonly = true; } unset($object['date']); } if (!empty($task['startdate'])) { $object['start'] = $toDT(rcube_utils::anytodatetime($task['startdate'] . ' ' . ($task['starttime'] ?? ''), $this->plugin->timezone)); if (empty($task['starttime'])) { $object['start']->_dateonly = true; } unset($object['startdate']); } // as per RFC (and the Kolab schema validation), start and due dates need to be of the same type (#3614) // this should be catched in the client already but just make sure we don't write invalid objects if (!empty($object['start']) && !empty($object['due']) && $object['due']->_dateonly != $object['start']->_dateonly) { $object['start']->_dateonly = true; $object['due']->_dateonly = true; } $object['complete'] = $task['complete'] * 100; if ($task['complete'] == 1.0 && empty($task['complete'])) { $object['status'] = 'COMPLETED'; } if (!empty($task['flagged'])) { $object['priority'] = 1; } else { $object['priority'] = isset($old['priority']) && $old['priority'] > 1 ? $old['priority'] : 0; } // remove list: prefix from parent_id if (!empty($task['parent_id']) && strpos($task['parent_id'], $id_prefix) === 0) { $object['parent_id'] = substr($task['parent_id'], strlen($id_prefix)); } // copy meta data (starting with _) from old object foreach ((array) $old as $key => $val) { if (!isset($object[$key]) && $key[0] == '_') { $object[$key] = $val; } } // copy recurrence rules if the client didn't submit it (#2713) if (!array_key_exists('recurrence', $object) && !empty($old['recurrence'])) { $object['recurrence'] = $old['recurrence']; } unset($task['attachments']); kolab_format::merge_attachments($object, $old); // allow sequence increments if I'm the organizer if ($this->plugin->is_organizer($object) && empty($object['_method'])) { unset($object['sequence']); } elseif (isset($old['sequence']) && empty($object['_method'])) { $object['sequence'] = $old['sequence']; } unset($object['tempid'], $object['raw'], $object['list'], $object['flagged'], $object['tags'], $object['created']); return $object; } /** * Add a single task to the database * * @param array $task Hash array with task properties (see header of tasklist_driver.php) * * @return mixed New task ID on success, False on error */ public function create_task($task) { return $this->edit_task($task); } /** * Update a task entry with the given data * * @param array $task Hash array with task properties (see header of tasklist_driver.php) * * @return bool True on success, False on error */ public function edit_task($task) { $this->_parse_id($task); if (empty($task['list']) || !($folder = $this->get_folder($task['list']))) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Invalid list identifer to save task: " . print_r($task['list'], true), ], true, false ); return false; } // moved from another folder if (!empty($task['_fromlist']) && ($fromfolder = $this->get_folder($task['_fromlist']))) { if (!$fromfolder->move($task['uid'], $folder)) { return false; } unset($task['_fromlist']); } // load previous version of this task to merge if (!empty($task['id'])) { $old = $folder->get_object($task['uid']); if (!$old) { return false; } // merge existing properties if the update isn't complete if (!isset($task['title']) || !isset($task['complete'])) { $task += $this->_to_rcube_task($old, $task['list']); } } // generate new task object from RC input $object = $this->_from_rcube_task($task, $old ?? null); $object['created'] = $old['created'] ?? null; $saved = $folder->save($object, 'task', !empty($old) ? $task['uid'] : null); if (!$saved) { rcube::raise_error( [ 'code' => 600, 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving task object to Kolab server", ], true, false ); return false; } $task = $this->_to_rcube_task($object, $task['list']); $this->tasks[$task['uid']] = $task; return true; } /** * Move a single task to another list * * @param array $task Hash array with task properties * * @return bool True on success, False on error * @see tasklist_driver::move_task() */ public function move_task($task) { $this->_parse_id($task); if (empty($task['list']) || !($folder = $this->get_folder($task['list']))) { return false; } // execute move command if (!empty($task['_fromlist']) && ($fromfolder = $this->get_folder($task['_fromlist']))) { return $fromfolder->move($task['uid'], $folder); } return false; } /** * Remove a single task from the database * * @param array $task Hash array with task properties: * id: Task identifier * @param bool $force Remove record irreversible (mark as deleted otherwise, if supported by the backend) * * @return bool True on success, False on error */ public function delete_task($task, $force = true) { $this->_parse_id($task); if (empty($task['list']) || !($folder = $this->get_folder($task['list']))) { return false; } $status = $folder->delete($task['uid'], $force); return $status; } /** * Restores a single deleted task (if supported) * * @param array $prop Hash array with task properties: * id: Task identifier * @return bool True on success, False on error */ public function undelete_task($prop) { // TODO: implement this return false; } /** * Get attachment properties * * @param string $id Attachment identifier * @param array $task Hash array with event properties: * id: Task identifier * list: List identifier * rev: Revision (optional) * * @return array|null Hash array with attachment properties: * id: Attachment identifier * name: Attachment name * mimetype: MIME content type of the attachment * size: Attachment size */ public function get_attachment($id, $task) { // get old revision of the object if (!empty($task['rev'])) { $task = $this->get_task_revison($task, $task['rev']); } else { $task = $this->get_task($task); } if ($task && !empty($task['attachments'])) { foreach ($task['attachments'] as $att) { if ($att['id'] == $id) { if (!empty($att['data'])) { // This way we don't have to call get_attachment_body() again $att['body'] = &$att['data']; } return $att; } } } return null; } /** * Get attachment body * * @param string $id Attachment identifier * @param array $task Hash array with event properties: * id: Task identifier * list: List identifier * rev: Revision (optional) * * @return string|false Attachment body */ public function get_attachment_body($id, $task) { $this->_parse_id($task); /* // get old revision of event if ($task['rev']) { if (empty($this->bonnie_api)) { return false; } $cid = substr($id, 4); // call Bonnie API and get the raw mime message list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($task); if ($msg_raw = $this->bonnie_api->rawdata('task', $uid, $task['rev'], $mailbox, $msguid)) { // parse the message and find the part with the matching content-id $message = rcube_mime::parse_message($msg_raw); foreach ((array)$message->parts as $part) { if ($part->headers['content-id'] && trim($part->headers['content-id'], '<>') == $cid) { return $part->body; } } } return false; } */ if ($storage = $this->get_folder($task['list'])) { return $storage->get_attachment($id, $task); } return false; } /** * Build a struct representing the given message reference * * @see tasklist_driver::get_message_reference() */ public function get_message_reference($uri_or_headers, $folder = null) { /* if (is_object($uri_or_headers)) { $uri_or_headers = kolab_storage_config::get_message_uri($uri_or_headers, $folder); } if (is_string($uri_or_headers)) { return kolab_storage_config::get_message_reference($uri_or_headers, 'task'); } */ return false; } /** * Find tasks assigned to a specified message * * @see tasklist_driver::get_message_related_tasks() */ public function get_message_related_tasks($headers, $folder) { return []; /* $config = kolab_storage_config::get_instance(); $result = $config->get_message_relations($headers, $folder, 'task'); foreach ($result as $idx => $rec) { $result[$idx] = $this->_to_rcube_task($rec, kolab_storage::folder_id($rec['_mailbox'])); } return $result; */ } /** * */ public function tasklist_edit_form($action, $list, $fieldprop) { $this->_read_lists(); if (!empty($list['id']) && ($list = $this->lists[$list['id']])) { $folder_name = $this->get_folder($list['id'])->name; } else { $folder_name = ''; } $hidden_fields[] = ['name' => 'oldname', 'value' => $folder_name]; // folder name (default field) $input_name = new html_inputfield(['name' => 'name', 'id' => 'taskedit-tasklistname', 'size' => 20]); $fieldprop['name']['value'] = $input_name->show($list['editname'] ?? ''); // General tab $form = [ 'properties' => [ 'name' => $this->rc->gettext('properties'), 'fields' => [], ], ]; foreach (['name', 'showalarms'] as $f) { $form['properties']['fields'][$f] = $fieldprop[$f]; } return kolab_utils::folder_form($form, $folder_name, 'tasklist', $hidden_fields, true); } } diff --git a/plugins/tasklist/drivers/kolab/tasklist_kolab_driver.php b/plugins/tasklist/drivers/kolab/tasklist_kolab_driver.php index 1b6814e8..2f7c59bd 100644 --- a/plugins/tasklist/drivers/kolab/tasklist_kolab_driver.php +++ b/plugins/tasklist/drivers/kolab/tasklist_kolab_driver.php @@ -1,1781 +1,1781 @@ * * 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 tasklist_kolab_driver extends tasklist_driver { // features supported by the backend public $alarms = false; public $attachments = true; public $attendees = true; public $undelete = false; // task undelete action public $alarm_types = ['DISPLAY','AUDIO']; public $search_more_results; private $rc; private $plugin; private $lists; private $folders = []; private $tasks = []; private $tags = []; private $bonnie_api = false; /** * Default constructor */ public function __construct($plugin) { $this->rc = $plugin->rc; $this->plugin = $plugin; if (kolab_storage::$version == '2.0') { $this->alarm_absolute = false; } // tasklist use fully encoded identifiers kolab_storage::$encode_ids = true; // get configuration for the Bonnie API $this->bonnie_api = libkolab::get_bonnie_api(); $this->plugin->register_action('folder-acl', [$this, 'folder_acl']); } /** * Read available calendars for the current user and store them internally */ private function _read_lists($force = false) { // already read sources if (isset($this->lists) && !$force) { return $this->lists; } // get all folders that have type "task" $folders = kolab_storage::sort_folders(kolab_storage::get_folders('task')); $this->lists = $this->folders = []; $delim = $this->rc->get_storage()->get_hierarchy_delimiter(); // find default folder $default_index = 0; foreach ($folders as $i => $folder) { if ($folder->default && strpos($folder->name, $delim) === false) { $default_index = $i; } } // put default folder (aka INBOX) on top of the list if ($default_index > 0) { $default_folder = $folders[$default_index]; unset($folders[$default_index]); array_unshift($folders, $default_folder); } $prefs = $this->rc->config->get('kolab_tasklists', []); foreach ($folders as $folder) { $tasklist = $this->folder_props($folder, $prefs); $this->lists[$tasklist['id']] = $tasklist; $this->folders[$tasklist['id']] = $folder; $this->folders[$folder->name] = $folder; } return $this->lists; } /** * Derive list properties from the given kolab_storage_folder object */ protected function folder_props($folder, $prefs) { if ($folder->get_namespace() == 'personal') { $norename = false; $editable = true; $rights = 'lrswikxtea'; $alarms = true; } else { $alarms = false; $rights = 'lr'; $editable = false; if ($myrights = $folder->get_myrights()) { $rights = $myrights; if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false) { $editable = strpos($rights, 'i') !== false; } } $info = $folder->get_folder_info(); $norename = !$editable || !empty($info['norename']) || !empty($info['protected']); } $list_id = $folder->id; #kolab_storage::folder_id($folder->name); $old_id = kolab_storage::folder_id($folder->name, false); if (!isset($prefs[$list_id]['showalarms']) && isset($prefs[$old_id]['showalarms'])) { $prefs[$list_id]['showalarms'] = $prefs[$old_id]['showalarms']; } return [ 'id' => $list_id, 'name' => $folder->get_name(), 'listname' => $folder->get_foldername(), 'editname' => $folder->get_foldername(), 'color' => $folder->get_color('0000CC'), 'showalarms' => $prefs[$list_id]['showalarms'] ?? $alarms, 'editable' => $editable, 'rights' => $rights, 'norename' => $norename, 'active' => $folder->is_active(), 'owner' => $folder->get_owner(), 'parentfolder' => $folder->get_parent(), 'default' => $folder->default, 'virtual' => $folder instanceof kolab_storage_folder_virtual, 'children' => true, // TODO: determine if that folder indeed has child folders 'subscribed' => (bool)$folder->is_subscribed(), 'removable' => !$folder->default, 'subtype' => $folder->subtype, 'group' => $folder->default ? 'default' : $folder->get_namespace(), 'class' => trim($folder->get_namespace() . ($folder->default ? ' default' : '')), 'caldavuid' => $folder->get_uid(), 'history' => !empty($this->bonnie_api), ]; } /** * Get a list of available task lists from this source * * @param int $filter Bitmask defining filter criterias. * See FILTER_* constants for possible values. * @param array|null $tree Folders tree */ public function get_lists($filter = 0, &$tree = null) { $this->_read_lists(); // attempt to create a default list for this user if (empty($this->lists) && !isset($this->search_more_results)) { $prop = ['name' => 'Tasks', 'color' => '0000CC', 'default' => true]; if ($this->create_list($prop)) { $this->_read_lists(true); } } $folders = $this->filter_folders($filter); // include virtual folders for a full folder tree if (!is_null($tree)) { $folders = kolab_storage::folder_hierarchy($folders, $tree); } $delim = $this->rc->get_storage()->get_hierarchy_delimiter(); $prefs = $this->rc->config->get('kolab_tasklists', []); $lists = []; foreach ($folders as $folder) { $list_id = $folder->id; // kolab_storage::folder_id($folder->name); $imap_path = explode($delim, $folder->name); // find parent do { array_pop($imap_path); $parent_id = kolab_storage::folder_id(implode($delim, $imap_path)); } while (count($imap_path) > 1 && !$this->folders[$parent_id]); // restore "real" parent ID if ($parent_id && !$this->folders[$parent_id]) { $parent_id = kolab_storage::folder_id($folder->get_parent()); } $fullname = $folder->get_name(); $listname = $folder->get_foldername(); // special handling for virtual folders if ($folder instanceof kolab_storage_folder_user) { $lists[$list_id] = [ 'id' => $list_id, 'name' => $fullname, 'listname' => $listname, 'title' => $folder->get_title(), 'virtual' => true, 'editable' => false, 'rights' => 'l', 'group' => 'other virtual', 'class' => 'user', 'parent' => $parent_id, ]; } elseif ($folder instanceof kolab_storage_folder_virtual) { $lists[$list_id] = [ 'id' => $list_id, 'name' => $fullname, 'listname' => $listname, 'virtual' => true, 'editable' => false, 'rights' => 'l', 'group' => $folder->get_namespace(), 'class' => 'folder', 'parent' => $parent_id, ]; } else { if (!$this->lists[$list_id]) { $this->lists[$list_id] = $this->folder_props($folder, $prefs); $this->folders[$list_id] = $folder; } $this->lists[$list_id]['parent'] = $parent_id; $lists[$list_id] = $this->lists[$list_id]; } } return $lists; } /** * Get list of folders according to specified filters * * @param int $filter Bitmask defining restrictions. See FILTER_* constants for possible values. * * @return array List of task folders */ protected function filter_folders($filter) { $this->_read_lists(); $folders = []; foreach ($this->lists as $id => $list) { if (!empty($this->folders[$id])) { $folder = $this->folders[$id]; if ($folder->get_namespace() == 'personal') { $folder->editable = true; } elseif ($rights = $folder->get_myrights()) { if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false) { $folder->editable = strpos($rights, 'i') !== false; } } $folders[] = $folder; } } $plugin = $this->rc->plugins->exec_hook('tasklist_list_filter', [ 'list' => $folders, 'filter' => $filter, 'tasklists' => $folders, ]); if ($plugin['abort'] || !$filter) { return $plugin['tasklists']; } $personal = $filter & self::FILTER_PERSONAL; $shared = $filter & self::FILTER_SHARED; $tasklists = []; foreach ($folders as $folder) { if (($filter & self::FILTER_WRITEABLE) && !$folder->editable) { continue; } /* if (($filter & self::FILTER_INSERTABLE) && !$folder->insert) { continue; } if (($filter & self::FILTER_ACTIVE) && !$folder->is_active()) { continue; } if (($filter & self::FILTER_PRIVATE) && $folder->subtype != 'private') { continue; } if (($filter & self::FILTER_CONFIDENTIAL) && $folder->subtype != 'confidential') { continue; } */ if ($personal || $shared) { $ns = $folder->get_namespace(); if (!(($personal && $ns == 'personal') || ($shared && $ns == 'shared'))) { continue; } } $tasklists[$folder->id] = $folder; } return $tasklists; } /** * Get the kolab_calendar instance for the given calendar ID * * @param string $id List identifier (encoded imap folder name) * * @return kolab_storage_folder|null Object nor null if list doesn't exist */ protected function get_folder($id) { $this->_read_lists(); // create list and folder instance if necesary if (empty($this->lists[$id])) { $folder = kolab_storage::get_folder(kolab_storage::id_decode($id)); if ($folder && $folder->type) { $this->folders[$id] = $folder; $this->lists[$id] = $this->folder_props($folder, $this->rc->config->get('kolab_tasklists', [])); } } return $this->folders[$id] ?? null; } /** * Create a new list assigned to the current user * * @param array $prop Hash array with list properties * name: List name * color: The color of the list * showalarms: True if alarms are enabled * * @return string|false ID of the new list on success, False on error */ public function create_list(&$prop) { $prop['type'] = 'task' . ($prop['default'] ? '.default' : ''); $prop['active'] = true; // activate folder by default $prop['subscribed'] = true; $folder = kolab_storage::folder_update($prop); if ($folder === false) { $this->last_error = kolab_storage::$last_error; return false; } // create ID $id = kolab_storage::folder_id($folder); $prefs['kolab_tasklists'] = $this->rc->config->get('kolab_tasklists', []); if (isset($prop['showalarms'])) { $prefs['kolab_tasklists'][$id]['showalarms'] = $prop['showalarms'] ? true : false; } if ($prefs['kolab_tasklists'][$id]) { $this->rc->user->save_prefs($prefs); } // force page reload to properly render folder hierarchy if (!empty($prop['parent'])) { $prop['_reload'] = true; } else { $folder = kolab_storage::get_folder($folder); $prop += $this->folder_props($folder, []); } return $id; } /** * Update properties of an existing tasklist * * @param array $prop Hash array with list properties * id: List Identifier * name: List name * color: The color of the list * showalarms: True if alarms are enabled (if supported) * * @return bool True on success, Fales on failure */ public function edit_list(&$prop) { if ($prop['id'] && ($folder = $this->get_folder($prop['id']))) { $prop['oldname'] = $folder->name; $prop['type'] = 'task'; $newfolder = kolab_storage::folder_update($prop); if ($newfolder === false) { $this->last_error = kolab_storage::$last_error; return false; } // create ID $id = kolab_storage::folder_id($newfolder); // fallback to local prefs $prefs['kolab_tasklists'] = $this->rc->config->get('kolab_tasklists', []); unset($prefs['kolab_tasklists'][$prop['id']]); if (isset($prop['showalarms'])) { $prefs['kolab_tasklists'][$id]['showalarms'] = $prop['showalarms'] ? true : false; } if ($prefs['kolab_tasklists'][$id]) { $this->rc->user->save_prefs($prefs); } // force page reload if folder name/hierarchy changed if ($newfolder != $prop['oldname']) { $prop['_reload'] = true; } $list['id'] = $id; return true; } return false; } /** * Set active/subscribed state of a list * * @param array $prop Hash array with list properties * id: List Identifier * active: True if list is active, false if not * permanent: True if list is to be subscribed permanently * * @return bool True on success, Fales on failure */ public function subscribe_list($prop) { if ($prop['id'] && ($folder = $this->get_folder($prop['id']))) { $ret = false; if (isset($prop['permanent'])) { $ret |= $folder->subscribe(intval($prop['permanent'])); } if (isset($prop['active'])) { $ret |= $folder->activate(intval($prop['active'])); } // apply to child folders, too if (!empty($prop['recursive'])) { foreach ((array) kolab_storage::list_folders($folder->name, '*', 'task') as $subfolder) { if (isset($prop['permanent'])) { ($prop['permanent'] ? kolab_storage::folder_subscribe($subfolder) : kolab_storage::folder_unsubscribe($subfolder)); } if (isset($prop['active'])) { ($prop['active'] ? kolab_storage::folder_activate($subfolder) : kolab_storage::folder_deactivate($subfolder)); } } } return $ret; } return false; } /** * Delete the given list with all its contents * * @param array $prop Hash array with list properties * id: list Identifier * @return bool True on success, Fales on failure */ public function delete_list($prop) { if ($prop['id'] && ($folder = $this->get_folder($prop['id']))) { if (kolab_storage::folder_delete($folder->name)) { return true; } $this->last_error = kolab_storage::$last_error; } return false; } /** * Search for shared or otherwise not listed tasklists the user has access * * @param string $query Search string * @param string $source Section/source to search * * @return array List of tasklists */ public function search_lists($query, $source) { if (!kolab_storage::setup()) { return []; } $this->search_more_results = false; $this->lists = $this->folders = []; // find unsubscribed IMAP folders that have "event" type if ($source == 'folders') { foreach ((array)kolab_storage::search_folders('task', $query, ['other']) as $folder) { $this->folders[$folder->id] = $folder; $this->lists[$folder->id] = $this->folder_props($folder, []); } } // search other user's namespace via LDAP elseif ($source == 'users') { $limit = $this->rc->config->get('autocomplete_max', 15) * 2; // we have slightly more space, so display twice the number foreach (kolab_storage::search_users($query, 0, [], $limit * 10) as $user) { $folders = []; // search for tasks folders shared by this user foreach (kolab_storage::list_user_folders($user, 'task', false) as $foldername) { $folders[] = new kolab_storage_folder($foldername, 'task'); } $count = 0; if (count($folders)) { $userfolder = new kolab_storage_folder_user($user['kolabtargetfolder'], '', $user); $this->folders[$userfolder->id] = $userfolder; $this->lists[$userfolder->id] = $this->folder_props($userfolder, []); foreach ($folders as $folder) { $this->folders[$folder->id] = $folder; $this->lists[$folder->id] = $this->folder_props($folder, []); $count++; } } if ($count >= $limit) { $this->search_more_results = true; break; } } } return $this->get_lists(); } /** * Get a list of tags to assign tasks to * * @return array List of tags */ public function get_tags() { $config = kolab_storage_config::get_instance(); $tags = $config->get_tags(); $backend_tags = array_map(function ($v) { return $v['name']; }, $tags); return array_values(array_unique(array_merge($this->tags, $backend_tags))); } /** * Get number of tasks matching the given filter * * @param array $lists List of lists to count tasks of * * @return array Hash array with counts grouped by status (all|flagged|completed|today|tomorrow|nodate) */ public function count_tasks($lists = null) { if (empty($lists)) { $lists = $this->_read_lists(); $lists = array_keys($lists); } elseif (is_string($lists)) { $lists = explode(',', $lists); } $today_date = new DateTime('now', $this->plugin->timezone); $today = $today_date->format('Y-m-d'); $tomorrow_date = new DateTime('now + 1 day', $this->plugin->timezone); $tomorrow = $tomorrow_date->format('Y-m-d'); $counts = ['all' => 0, 'today' => 0, 'tomorrow' => 0, 'later' => 0, 'overdue' => 0]; foreach ($lists as $list_id) { if (!$folder = $this->get_folder($list_id)) { continue; } foreach ($folder->select([['tags','!~','x-complete']], true) as $record) { $rec = $this->_to_rcube_task($record, $list_id, false); if ($this->is_complete($rec)) { // don't count complete tasks continue; } $counts['all']++; if (empty($rec['date'])) { $counts['later']++; } elseif ($rec['date'] == $today) { $counts['today']++; } elseif ($rec['date'] == $tomorrow) { $counts['tomorrow']++; } elseif ($rec['date'] < $today) { $counts['overdue']++; } elseif ($rec['date'] > $tomorrow) { $counts['later']++; } } } // avoid session race conditions that will loose temporary subscriptions $this->plugin->rc->session->nowrite = true; return $counts; } /** * Get all task records matching the given filter * * @param array $filter Hash array with filter criterias: * - mask: Bitmask representing the filter selection (check against tasklist::FILTER_MASK_* constants) * - from: Date range start as string (Y-m-d) * - to: Date range end as string (Y-m-d) * - search: Search query string * - uid: Task UIDs * @param array $lists List of lists to get tasks from * * @return array List of tasks records matchin the criteria */ public function list_tasks($filter, $lists = null) { if (empty($lists)) { $lists = $this->_read_lists(); $lists = array_keys($lists); } elseif (is_string($lists)) { $lists = explode(',', $lists); } $config = kolab_storage_config::get_instance(); $results = []; // query Kolab storage $query = []; if (!empty($filter['mask']) && $filter['mask'] & tasklist::FILTER_MASK_COMPLETE) { $query[] = ['tags','~','x-complete']; } elseif (empty($filter['since'])) { $query[] = ['tags','!~','x-complete']; } // full text search (only works with cache enabled) if (!empty($filter['search'])) { $search = mb_strtolower($filter['search']); foreach (rcube_utils::normalize_string($search, true) as $word) { $query[] = ['words', '~', $word]; } } if (!empty($filter['since'])) { $query[] = ['changed', '>=', $filter['since']]; } if (!empty($filter['uid'])) { $query[] = ['uid', '=', (array) $filter['uid']]; } foreach ($lists as $list_id) { if (!$folder = $this->get_folder($list_id)) { continue; } foreach ($folder->select($query) as $record) { // TODO: post-filter tasks returned from storage $record['list_id'] = $list_id; $results[] = $record; } } $config->apply_tags($results, true); $config->apply_links($results); foreach (array_keys($results) as $idx) { $results[$idx] = $this->_to_rcube_task($results[$idx], $results[$idx]['list_id']); } // avoid session race conditions that will loose temporary subscriptions $this->plugin->rc->session->nowrite = true; return $results; } /** * Return data of a specific task * * @param mixed $prop Hash array with task properties or task UID * @param int $filter Bitmask defining filter criterias for folders. * See FILTER_* constants for possible values. * * @return array|false Hash array with task properties or false if not found */ public function get_task($prop, $filter = 0) { $this->_parse_id($prop); $id = $prop['uid']; $list_id = $prop['list']; $folders = $list_id ? [$list_id => $this->get_folder($list_id)] : $this->get_lists($filter); // find task in the available folders foreach ($folders as $list_id => $folder) { if (is_array($folder)) { $folder = $this->folders[$list_id]; } if (is_numeric($list_id) || !$folder) { continue; } if (empty($this->tasks[$id]) && ($object = $folder->get_object($id))) { $this->load_tags($object); $this->tasks[$id] = $this->_to_rcube_task($object, $list_id); break; } } return $this->tasks[$id] ?? false; } /** * Get all decendents of the given task record * * @param mixed $prop Hash array with task properties or task UID * @param bool $recursive True if all childrens children should be fetched * * @return array List of all child task IDs */ public function get_childs($prop, $recursive = false) { if (is_string($prop)) { $task = $this->get_task($prop); $prop = ['uid' => $task['uid'], 'list' => $task['list']]; } else { $this->_parse_id($prop); } $childs = []; $list_id = $prop['list']; $task_ids = [$prop['uid']]; $folder = $this->get_folder($list_id); // query for childs (recursively) while ($folder && !empty($task_ids)) { $query_ids = []; foreach ($task_ids as $task_id) { $query = [['tags','=','x-parent:' . $task_id]]; foreach ($folder->select($query) as $record) { // don't rely on kolab_storage_folder filtering if ($record['parent_id'] == $task_id) { $childs[] = $list_id . ':' . $record['uid']; $query_ids[] = $record['uid']; } } } if (!$recursive) { break; } $task_ids = $query_ids; } return $childs; } /** * Provide a list of revisions for the given task * * @param array $prop Hash array with task properties * * @return array|false List of changes, each as a hash array * @see tasklist_driver::get_task_changelog() */ public function get_task_changelog($prop) { if (empty($this->bonnie_api)) { return false; } [$uid, $mailbox, $msguid] = $this->_resolve_task_identity($prop); $result = $uid && $mailbox ? $this->bonnie_api->changelog('task', $uid, $mailbox, $msguid) : null; if (is_array($result) && $result['uid'] == $uid) { return $result['changes']; } return false; } /** * Return full data of a specific revision of an event * * @param mixed $prop UID string or hash array with task properties * @param mixed $rev Revision number * * @return array|false Task object as hash array * @see tasklist_driver::get_task_revision() */ public function get_task_revison($prop, $rev) { if (empty($this->bonnie_api)) { return false; } $this->_parse_id($prop); $uid = $prop['uid']; $list_id = $prop['list']; [$uid, $mailbox, $msguid] = $this->_resolve_task_identity($prop); // call Bonnie API $result = $this->bonnie_api->get('task', $uid, $rev, $mailbox, $msguid); if (is_array($result) && $result['uid'] == $uid && !empty($result['xml'])) { $format = kolab_format::factory('task'); $format->load($result['xml']); $rec = $format->to_array(); $format->get_attachments($rec, true); if ($format->is_valid()) { $rec = self::_to_rcube_task($rec, $list_id, false); $rec['rev'] = $result['rev']; return $rec; } } return false; } /** * Command the backend to restore a certain revision of a task. * This shall replace the current object with an older version. * * @param mixed $prop UID string or hash array with task properties * @param mixed $rev Revision number * * @return bool True on success, False on failure * @see tasklist_driver::restore_task_revision() */ public function restore_task_revision($prop, $rev) { if (empty($this->bonnie_api)) { return false; } $this->_parse_id($prop); $uid = $prop['uid']; $list_id = $prop['list']; [$uid, $mailbox, $msguid] = $this->_resolve_task_identity($prop); $folder = $this->get_folder($list_id); $success = false; if ($folder && ($raw_msg = $this->bonnie_api->rawdata('task', $uid, $rev, $mailbox))) { $imap = $this->rc->get_storage(); // insert $raw_msg as new message if ($imap->save_message($folder->name, $raw_msg, null, false)) { $success = true; // delete old revision from imap and cache $imap->delete_message($msguid, $folder->name); $folder->cache->set($msguid, false); } } return $success; } /** * Get a list of property changes beteen two revisions of a task object * * @param array $prop Hash array with task properties * @param mixed $rev1 Revision "from" * @param mixed $rev2 Revision "to" * * @return array|false List of property changes, each as a hash array * @see tasklist_driver::get_task_diff() */ public function get_task_diff($prop, $rev1, $rev2) { $this->_parse_id($prop); $uid = $prop['uid']; $list_id = $prop['list']; [$uid, $mailbox, $msguid] = $this->_resolve_task_identity($prop); // call Bonnie API $result = $this->bonnie_api->diff('task', $uid, $rev1, $rev2, $mailbox, $msguid); if (is_array($result) && $result['uid'] == $uid) { $result['rev1'] = $rev1; $result['rev2'] = $rev2; $keymap = [ 'start' => 'start', 'due' => 'date', 'dstamp' => 'changed', 'summary' => 'title', 'alarm' => 'alarms', 'attendee' => 'attendees', 'attach' => 'attachments', 'rrule' => 'recurrence', 'related-to' => 'parent_id', 'percent-complete' => 'complete', 'lastmodified-date' => 'changed', ]; $prop_keymaps = [ 'attachments' => ['fmttype' => 'mimetype', 'label' => 'name'], 'attendees' => ['partstat' => 'status'], ]; $special_changes = []; // map kolab event properties to keys the client expects - array_walk($result['changes'], function (&$change, $i) use ($keymap, $prop_keymaps, $special_changes) { + array_walk($result['changes'], function (&$change, $i) use ($keymap, $prop_keymaps, &$special_changes) { if (array_key_exists($change['property'], $keymap)) { $change['property'] = $keymap[$change['property']]; } if ($change['property'] == 'priority') { $change['property'] = 'flagged'; $change['old'] = $change['old'] == 1 ? $this->plugin->gettext('yes') : null; $change['new'] = $change['new'] == 1 ? $this->plugin->gettext('yes') : null; } // map alarms trigger value if ($change['property'] == 'alarms') { if (is_array($change['old']) && is_array($change['old']['trigger'])) { $change['old']['trigger'] = $change['old']['trigger']['value']; } if (is_array($change['new']) && is_array($change['new']['trigger'])) { $change['new']['trigger'] = $change['new']['trigger']['value']; } } // make all property keys uppercase if ($change['property'] == 'recurrence') { $special_changes['recurrence'] = $i; foreach (['old','new'] as $m) { if (is_array($change[$m])) { $props = []; foreach ($change[$m] as $k => $v) { $props[strtoupper($k)] = $v; } $change[$m] = $props; } } } // map property keys names if (is_array($prop_keymaps[$change['property']])) { foreach ($prop_keymaps[$change['property']] as $k => $dest) { if (is_array($change['old']) && array_key_exists($k, $change['old'])) { $change['old'][$dest] = $change['old'][$k]; unset($change['old'][$k]); } if (is_array($change['new']) && array_key_exists($k, $change['new'])) { $change['new'][$dest] = $change['new'][$k]; unset($change['new'][$k]); } } } if ($change['property'] == 'exdate') { $special_changes['exdate'] = $i; } elseif ($change['property'] == 'rdate') { $special_changes['rdate'] = $i; } }); // merge some recurrence changes foreach (['exdate','rdate'] as $prop) { if (array_key_exists($prop, $special_changes)) { $exdate = $result['changes'][$special_changes[$prop]]; if (array_key_exists('recurrence', $special_changes)) { $recurrence = &$result['changes'][$special_changes['recurrence']]; } else { $i = count($result['changes']); $result['changes'][$i] = ['property' => 'recurrence', 'old' => [], 'new' => []]; $recurrence = &$result['changes'][$i]['recurrence']; } $key = strtoupper($prop); $recurrence['old'][$key] = $exdate['old']; $recurrence['new'][$key] = $exdate['new']; unset($result['changes'][$special_changes[$prop]]); } } return $result; } return false; } /** * Helper method to resolved the given task identifier into uid and folder * * @return array (uid,folder,msguid) tuple */ private function _resolve_task_identity($prop) { $mailbox = $msguid = null; $this->_parse_id($prop); $uid = $prop['uid']; $list_id = $prop['list']; if ($folder = $this->get_folder($list_id)) { $mailbox = $folder->get_mailbox_id(); // get task object from storage in order to get the real object uid an msguid if ($rec = $folder->get_object($uid)) { $msguid = $rec['_msguid']; $uid = $rec['uid']; } } return [$uid, $mailbox, $msguid]; } /** * Get a list of pending alarms to be displayed to the user * * @param int $time Current time (unix timestamp) * @param mixed $lists List of list IDs to show alarms for (either as array or comma-separated string) * * @return array A list of alarms, each encoded as hash array with task properties * @see tasklist_driver::pending_alarms() */ public function pending_alarms($time, $lists = null) { $interval = 300; $time -= $time % 60; $slot = $time; $slot -= $slot % $interval; $last = $time - max(60, $this->rc->config->get('refresh_interval', 0)); $last -= $last % $interval; // only check for alerts once in 5 minutes if ($last == $slot) { return []; } if ($lists && is_string($lists)) { $lists = explode(',', $lists); } $time = $slot + $interval; $dbdata = []; $candidates = []; $query = [ ['tags', '=', 'x-has-alarms'], ['tags', '!=', 'x-complete'], ]; $this->_read_lists(); foreach ($this->lists as $lid => $list) { // skip lists with alarms disabled if (!$list['showalarms'] || ($lists && !in_array($lid, $lists))) { continue; } $folder = $this->get_folder($lid); foreach ($folder->select($query) as $record) { if (!($record['valarms'] || $record['alarms']) || $record['status'] == 'COMPLETED' || $record['complete'] == 100) { // don't trust query :-) continue; } $task = $this->_to_rcube_task($record, $lid, false); // add to list if alarm is set $alarm = libcalendaring::get_next_alarm($task, 'task'); if ($alarm && $alarm['time'] && $alarm['time'] <= $time && in_array($alarm['action'], $this->alarm_types)) { $id = $alarm['id']; // use alarm-id as primary identifier $candidates[$id] = [ 'id' => $id, 'title' => $task['title'], 'date' => $task['date'], 'time' => $task['time'], 'notifyat' => $alarm['time'], 'action' => $alarm['action'], ]; } } } // get alarm information stored in local database if (!empty($candidates)) { $alarm_ids = array_map([$this->rc->db, 'quote'], array_keys($candidates)); $result = $this->rc->db->query( "SELECT *" . " FROM " . $this->rc->db->table_name('kolab_alarms', true) . " WHERE `alarm_id` IN (" . implode(',', $alarm_ids) . ")" . " AND `user_id` = ?", $this->rc->user->ID ); while ($result && ($rec = $this->rc->db->fetch_assoc($result))) { $dbdata[$rec['alarm_id']] = $rec; } } $alarms = []; foreach ($candidates as $id => $task) { // skip dismissed if (!empty($dbdata[$id]['dismissed'])) { continue; } // snooze function may have shifted alarm time $notifyat = !empty($dbdata[$id]['notifyat']) ? strtotime($dbdata[$id]['notifyat']) : $task['notifyat']; if ($notifyat <= $time) { $alarms[] = $task; } } return $alarms; } /** * (User) feedback after showing an alarm notification * This should mark the alarm as 'shown' or snooze it for the given amount of time * * @param string $id Task identifier * @param int $snooze Suspend the alarm for this number of seconds */ public function dismiss_alarm($id, $snooze = 0) { // delete old alarm entry $this->rc->db->query( "DELETE FROM " . $this->rc->db->table_name('kolab_alarms', true) . " WHERE `alarm_id` = ? AND `user_id` = ?", $id, $this->rc->user->ID ); // set new notifyat time or unset if not snoozed $notifyat = $snooze > 0 ? date('Y-m-d H:i:s', time() + $snooze) : null; $query = $this->rc->db->query( "INSERT INTO " . $this->rc->db->table_name('kolab_alarms', true) . " (`alarm_id`, `user_id`, `dismissed`, `notifyat`) VALUES (?, ?, ?, ?)", $id, $this->rc->user->ID, $snooze > 0 ? 0 : 1, $notifyat ); return $this->rc->db->affected_rows($query); } /** * Remove alarm dismissal or snooze state * * @param string $id Task identifier */ public function clear_alarms($id) { // delete alarm entry $this->rc->db->query( "DELETE FROM " . $this->rc->db->table_name('kolab_alarms', true) . " WHERE `alarm_id` = ? AND `user_id` = ?", $id, $this->rc->user->ID ); return true; } /** * Get task tags */ private function load_tags(&$object) { // this task hasn't been migrated yet if (!empty($object['categories'])) { // OPTIONAL: call kolab_storage_config::apply_tags() to migrate the object $object['tags'] = (array)$object['categories']; if (!empty($object['tags'])) { $this->tags = array_merge($this->tags, $object['tags']); } } else { $config = kolab_storage_config::get_instance(); $tags = $config->get_tags($object['uid']); $object['tags'] = array_map(function ($v) { return $v['name']; }, $tags); } } /** * Update task tags */ private function save_tags($uid, $tags) { $config = kolab_storage_config::get_instance(); $config->save_tags($uid, $tags); } /** * Find messages linked with a task record */ private function get_links($uid) { $config = kolab_storage_config::get_instance(); return $config->get_object_links($uid); } /** * */ private function save_links($uid, $links) { $config = kolab_storage_config::get_instance(); return $config->save_object_links($uid, (array) $links); } /** * Extract uid + list identifiers from the given input * * @param array|string $prop Array or string with task identifier(s) */ private function _parse_id(&$prop) { $id_ = null; if (is_array($prop)) { // 'uid' + 'list' available, nothing to be done if (!empty($prop['uid']) && !empty($prop['list'])) { return; } // 'id' is given if (!empty($prop['id'])) { if (!empty($prop['list'])) { $list_id = $prop['_fromlist'] ?: $prop['list']; if (strpos($prop['id'], $list_id . ':') === 0) { $prop['uid'] = substr($prop['id'], strlen($list_id) + 1); } else { $prop['uid'] = $prop['id']; } } else { $id_ = $prop['id']; } } } else { $id_ = strval($prop); $prop = []; } // split 'id' into list + uid if (!empty($id_)) { [$list, $uid] = explode(':', $id_, 2); if (!empty($uid)) { $prop['uid'] = $uid; $prop['list'] = $list; } else { $prop['uid'] = $id_; } } } /** * Convert from Kolab_Format to internal representation */ private function _to_rcube_task($record, $list_id, $all = true) { $id_prefix = $list_id . ':'; $task = [ 'id' => $id_prefix . $record['uid'], 'uid' => $record['uid'], 'title' => $record['title'] ?? null, // 'location' => $record['location'], 'description' => $record['description'] ?? null, 'flagged' => ($record['priority'] ?? null) == 1, 'complete' => floatval(($record['complete'] ?? null) / 100), 'status' => $record['status'] ?? null, 'parent_id' => ($record['parent_id'] ?? null) ? $id_prefix . $record['parent_id'] : null, 'recurrence' => $record['recurrence'] ?? null, 'attendees' => $record['attendees'] ?? null, 'organizer' => $record['organizer'] ?? null, 'sequence' => $record['sequence'] ?? null, 'tags' => $record['tags'] ?? null, 'list' => $list_id, 'links' => $record['links'] ?? null, ]; // we can sometimes skip this expensive operation if ($all && !array_key_exists('links', $task)) { $task['links'] = $this->get_links($task['uid']); } // convert from DateTime to internal date format if (($record['due'] ?? null) instanceof DateTimeInterface) { $due = $this->plugin->lib->adjust_timezone($record['due']); $task['date'] = $due->format('Y-m-d'); if (empty($record['due']->_dateonly)) { $task['time'] = $due->format('H:i'); } } // convert from DateTime to internal date format if (($record['start'] ?? null) instanceof DateTimeInterface) { $start = $this->plugin->lib->adjust_timezone($record['start']); $task['startdate'] = $start->format('Y-m-d'); if (empty($record['start']->_dateonly)) { $task['starttime'] = $start->format('H:i'); } } if (($record['changed'] ?? null) instanceof DateTimeInterface) { $task['changed'] = $record['changed']; } if (($record['created'] ?? null) instanceof DateTimeInterface) { $task['created'] = $record['created']; } if (!empty($record['valarms'])) { $task['valarms'] = $record['valarms']; } elseif (!empty($record['alarms'])) { $task['alarms'] = $record['alarms']; } if (!empty($task['attendees'])) { foreach ((array)$task['attendees'] as $i => $attendee) { if (isset($attendee['delegated-from']) && is_array($attendee['delegated-from'])) { $task['attendees'][$i]['delegated-from'] = implode(', ', $attendee['delegated-from']); } if (isset($attendee['delegated-to']) && is_array($attendee['delegated-to'])) { $task['attendees'][$i]['delegated-to'] = implode(', ', $attendee['delegated-to']); } } } if (!empty($record['_attachments'])) { $attachments = []; foreach ($record['_attachments'] as $key => $attachment) { if ($attachment !== false) { if (empty($attachment['name'])) { $attachment['name'] = $key; } $attachments[] = $attachment; } } $task['attachments'] = $attachments; } return $task; } /** * Convert the given task record into a data structure that can be passed to kolab_storage backend for saving * (opposite of self::_to_rcube_event()) */ private function _from_rcube_task($task, $old = []) { $object = $task; $id_prefix = $task['list'] . ':'; $toDT = function ($date) { // Convert DateTime into libcalendaring_datetime return libcalendaring_datetime::createFromFormat( 'Y-m-d\\TH:i:s', $date->format('Y-m-d\\TH:i:s'), $date->getTimezone() ); }; if (!empty($task['date'])) { $object['due'] = $toDT(rcube_utils::anytodatetime($task['date'] . ' ' . $task['time'], $this->plugin->timezone)); if (empty($task['time'])) { $object['due']->_dateonly = true; } unset($object['date']); } if (!empty($task['startdate'])) { $object['start'] = $toDT(rcube_utils::anytodatetime($task['startdate'] . ' ' . $task['starttime'], $this->plugin->timezone)); if (empty($task['starttime'])) { $object['start']->_dateonly = true; } unset($object['startdate']); } // as per RFC (and the Kolab schema validation), start and due dates need to be of the same type (#3614) // this should be catched in the client already but just make sure we don't write invalid objects if (!empty($object['start']) && !empty($object['due']) && $object['due']->_dateonly != $object['start']->_dateonly) { $object['start']->_dateonly = true; $object['due']->_dateonly = true; } $object['complete'] = $task['complete'] * 100; if ($task['complete'] == 1.0 && empty($task['complete'])) { $object['status'] = 'COMPLETED'; } if (!empty($task['flagged'])) { $object['priority'] = 1; } else { $object['priority'] = ($old['priority'] ?? 0) > 1 ? $old['priority'] : 0; } // remove list: prefix from parent_id if (!empty($task['parent_id']) && strpos($task['parent_id'], $id_prefix) === 0) { $object['parent_id'] = substr($task['parent_id'], strlen($id_prefix)); } // copy meta data (starting with _) from old object foreach ((array)$old as $key => $val) { if (!isset($object[$key]) && $key[0] == '_') { $object[$key] = $val; } } // copy recurrence rules if the client didn't submit it (#2713) if (!array_key_exists('recurrence', $object) && $old['recurrence']) { $object['recurrence'] = $old['recurrence']; } unset($task['attachments']); kolab_format::merge_attachments($object, $old); // allow sequence increments if I'm the organizer if ($this->plugin->is_organizer($object) && empty($object['_method'])) { unset($object['sequence']); } elseif (isset($old['sequence']) && empty($object['_method'])) { $object['sequence'] = $old['sequence']; } unset($object['tempid'], $object['raw'], $object['list'], $object['flagged'], $object['tags'], $object['created']); return $object; } /** * Add a single task to the database * * @param array $task Hash array with task properties (see header of tasklist_driver.php) * * @return mixed New task ID on success, False on error */ public function create_task($task) { return $this->edit_task($task); } /** * Update an task entry with the given data * * @param array $task Hash array with task properties (see header of tasklist_driver.php) * * @return bool True on success, False on error */ public function edit_task($task) { $this->_parse_id($task); $list_id = $task['list']; if (!$list_id || !($folder = $this->get_folder($list_id))) { rcube::raise_error( [ 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Invalid list identifer to save task: " . print_r($list_id, true)], true, false ); return false; } // email links and tags are stored separately $links = $task['links'] ?? null; $tags = $task['tags'] ?? null; unset($task['tags'], $task['links']); // moved from another folder if (($task['_fromlist'] ?? false) && ($fromfolder = $this->get_folder($task['_fromlist']))) { if (!$fromfolder->move($task['uid'], $folder)) { return false; } unset($task['_fromlist']); } // load previous version of this task to merge $old = null; if (!empty($task['id'])) { $old = $folder->get_object($task['uid']); if (!$old || PEAR::isError($old)) { return false; } // merge existing properties if the update isn't complete if (!isset($task['title']) || !isset($task['complete'])) { $task += $this->_to_rcube_task($old, $list_id); } } // generate new task object from RC input $object = $this->_from_rcube_task($task, $old); $saved = $folder->save($object, 'task', $task['uid']); if (!$saved) { rcube::raise_error( [ 'code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Error saving task object to Kolab server"], true, false ); $saved = false; } else { // save links in configuration.relation object $this->save_links($object['uid'], $links); // save tags in configuration.relation object $this->save_tags($object['uid'], $tags); $task = $this->_to_rcube_task($object, $list_id); $task['tags'] = (array) $tags; $this->tasks[$task['uid']] = $task; } return $saved; } /** * Move a single task to another list * * @param array $task Hash array with task properties: * * @return bool True on success, False on error * @see tasklist_driver::move_task() */ public function move_task($task) { $this->_parse_id($task); $list_id = $task['list']; if (!$list_id || !($folder = $this->get_folder($list_id))) { return false; } // execute move command if ($task['_fromlist'] && ($fromfolder = $this->get_folder($task['_fromlist']))) { return $fromfolder->move($task['uid'], $folder); } return false; } /** * Remove a single task from the database * * @param array $task Hash array with task properties: * id: Task identifier * @param bool $force Remove record irreversible (mark as deleted otherwise, if supported by the backend) * * @return bool True on success, False on error */ public function delete_task($task, $force = true) { $this->_parse_id($task); $list_id = $task['list']; if (!$list_id || !($folder = $this->get_folder($list_id))) { return false; } $status = $folder->delete($task['uid']); if ($status) { // remove tag assignments // @TODO: don't do this when undelete feature will be implemented $this->save_tags($task['uid'], null); } return $status; } /** * Restores a single deleted task (if supported) * * @param array $prop Hash array with task properties: * id: Task identifier * @return bool True on success, False on error */ public function undelete_task($prop) { // TODO: implement this return false; } /** * Get attachment properties * * @param string $id Attachment identifier * @param array $task Hash array with event properties: * id: Task identifier * list: List identifier * rev: Revision (optional) * * @return array|null Hash array with attachment properties: * id: Attachment identifier * name: Attachment name * mimetype: MIME content type of the attachment * size: Attachment size */ public function get_attachment($id, $task) { // get old revision of the object if ($task['rev']) { $task = $this->get_task_revison($task, $task['rev']); } else { $task = $this->get_task($task); } if ($task && !empty($task['attachments'])) { foreach ($task['attachments'] as $att) { if ($att['id'] == $id) { return $att; } } } return null; } /** * Get attachment body * * @param string $id Attachment identifier * @param array $task Hash array with event properties: * id: Task identifier * list: List identifier * rev: Revision (optional) * * @return string|false Attachment body */ public function get_attachment_body($id, $task) { $this->_parse_id($task); // get old revision of event if ($task['rev']) { if (empty($this->bonnie_api)) { return false; } $cid = substr($id, 4); // call Bonnie API and get the raw mime message [$uid, $mailbox, $msguid] = $this->_resolve_task_identity($task); if ($msg_raw = $this->bonnie_api->rawdata('task', $uid, $task['rev'], $mailbox, $msguid)) { // parse the message and find the part with the matching content-id $message = rcube_mime::parse_message($msg_raw); foreach ((array)$message->parts as $part) { if ($part->headers['content-id'] && trim($part->headers['content-id'], '<>') == $cid) { return $part->body; } } } return false; } if ($storage = $this->get_folder($task['list'])) { return $storage->get_attachment($task['uid'], $id); } return false; } /** * Build a struct representing the given message reference * * @see tasklist_driver::get_message_reference() */ public function get_message_reference($uri_or_headers, $folder = null) { if (is_object($uri_or_headers)) { $uri_or_headers = kolab_storage_config::get_message_uri($uri_or_headers, $folder); } if (is_string($uri_or_headers)) { return kolab_storage_config::get_message_reference($uri_or_headers, 'task'); } return false; } /** * Find tasks assigned to a specified message * * @see tasklist_driver::get_message_related_tasks() */ public function get_message_related_tasks($headers, $folder) { $config = kolab_storage_config::get_instance(); $result = $config->get_message_relations($headers, $folder, 'task'); foreach ($result as $idx => $rec) { $result[$idx] = $this->_to_rcube_task($rec, kolab_storage::folder_id($rec['_mailbox'])); } return $result; } /** * */ public function tasklist_edit_form($action, $list, $fieldprop) { $this->_read_lists(); if ($list['id'] && ($list = $this->lists[$list['id']])) { $folder_name = $this->get_folder($list['id'])->name; // UTF7 } else { $folder_name = ''; } $storage = $this->rc->get_storage(); $delim = $storage->get_hierarchy_delimiter(); $form = []; $options = []; if (strlen($folder_name)) { $path_imap = explode($delim, $folder_name); array_pop($path_imap); // pop off name part $path_imap = implode($delim, $path_imap); $options = $storage->folder_info($folder_name); } else { $path_imap = ''; } $hidden_fields[] = ['name' => 'oldname', 'value' => $folder_name]; // folder name (default field) $input_name = new html_inputfield(['name' => 'name', 'id' => 'taskedit-tasklistname', 'size' => 20]); $disabled = !empty($options['norename']) || !empty($options['protected']); $fieldprop['name']['value'] = $input_name->show($list['editname'], ['disabled' => $disabled]); // prevent user from moving folder if ($disabled) { $hidden_fields[] = ['name' => 'parent', 'value' => $path_imap]; } else { $select = kolab_storage::folder_selector('task', ['name' => 'parent', 'id' => 'taskedit-parentfolder'], $folder_name); $fieldprop['parent'] = [ 'id' => 'taskedit-parentfolder', 'label' => $this->plugin->gettext('parentfolder'), 'value' => $select->show($path_imap), ]; } // General tab $form['properties'] = [ 'name' => $this->rc->gettext('properties'), 'fields' => [], ]; foreach (['name','parent','showalarms'] as $f) { $form['properties']['fields'][$f] = $fieldprop[$f]; } return kolab_utils::folder_form($form, $folder_name, 'tasklist', $hidden_fields); } } diff --git a/plugins/tasklist/tasklist.php b/plugins/tasklist/tasklist.php index 6b143fb5..e9236291 100644 --- a/plugins/tasklist/tasklist.php +++ b/plugins/tasklist/tasklist.php @@ -1,2526 +1,2527 @@ * * 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 . */ #[AllowDynamicProperties] class tasklist extends rcube_plugin { public const FILTER_MASK_TODAY = 1; public const FILTER_MASK_TOMORROW = 2; public const FILTER_MASK_WEEK = 4; public const FILTER_MASK_LATER = 8; public const FILTER_MASK_NODATE = 16; public const FILTER_MASK_OVERDUE = 32; public const FILTER_MASK_FLAGGED = 64; public const FILTER_MASK_COMPLETE = 128; public const FILTER_MASK_ASSIGNED = 256; public const FILTER_MASK_MYTASKS = 512; public const SESSION_KEY = 'tasklist_temp'; public static $filter_masks = [ '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 = ['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 = []; private $message_tasks = []; private $task_titles = []; private $task_tree = []; /** * Plugin initialization. */ public function init() { $this->require_plugin('libcalendaring'); $this->require_plugin('libkolab'); // load plugin configuration $this->load_config(); $this->rc = rcube::get_instance(); $this->lib = libcalendaring::get_instance(); $this->timezone = $this->lib->timezone; $this->register_task('tasks'); $this->add_hook('startup', [$this, 'startup']); $this->add_hook('user_delete', [$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'], ['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', [$this, 'tasklist_view']); $this->register_action('task', [$this, 'task_action']); $this->register_action('tasklist', [$this, 'tasklist_action']); $this->register_action('counts', [$this, 'fetch_counts']); $this->register_action('fetch', [$this, 'fetch_tasks']); $this->register_action('print', [$this, 'print_tasks']); $this->register_action('dialog-ui', [$this, 'mail_message2task']); $this->register_action('get-attachment', [$this, 'attachment_get']); $this->register_action('upload', [$this, 'attachment_upload']); $this->register_action('import', [$this, 'import_tasks']); $this->register_action('export', [$this, 'export_tasks']); $this->register_action('mailimportitip', [$this, 'mail_import_itip']); $this->register_action('mailimportattach', [$this, 'mail_import_attachment']); $this->register_action('itip-status', [$this, 'task_itip_status']); $this->register_action('itip-remove', [$this, 'task_itip_remove']); $this->register_action('itip-decline-reply', [$this, 'mail_itip_decline_reply']); $this->register_action('itip-delegate', [$this, 'mail_itip_delegate']); $this->add_hook('refresh', [$this, 'refresh']); $this->collapsed_tasks = array_filter(explode(',', $this->rc->config->get('tasklist_collapsed_tasks', ''))); } elseif ($args['task'] == 'mail') { if ($args['action'] == 'show' || $args['action'] == 'preview') { if ($this->rc->config->get('tasklist_mail_embed', true)) { $this->add_hook('message_load', [$this, 'mail_message_load']); } $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'] != 'task')) { $this->api->add_content( html::tag( 'li', ['role' => 'menuitem'], $this->api->output->button([ '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'])) { // A hack to replace "Edit/Share List" label with "Edit list", for non-Kolab drivers if ($args['task'] == 'tasks' && $this->rc->config->get('tasklist_driver', 'database') !== 'kolab') { $merge = ['tasklist.editlist' => $this->gettext('edlist')]; $this->rc->load_language(null, [], $merge); $this->rc->output->command('add_label', $merge); } $this->load_ui(); $this->ui->init(); } // add hooks for alarms handling $this->add_hook('pending_alarms', [$this, 'pending_alarms']); $this->add_hook('dismiss_alarms', [$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 = $got_msg = false; $refresh = []; // 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']; } elseif ($this->is_organizer($rec)) { $rec['_notify'] = 1; } } // no break 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(['id' => $rec['id'], 'list' => $rec['_fromlist']], true) as $cid) { $child = ['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(['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 = ['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 = ['id' => $oldrec['parent_id'], 'list' => $rec['list']]; if ($parent = $this->driver->get_task($parent)) { $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(['tasklist_collapsed_tasks' => implode(',', 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, $rec) { // convert date cols if (in_array($change['property'], ['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(['id' => $change['old'], 'list' => $rec['list']]))) { $change['old_'] = $old_parent['title']; } if (!empty($change['new']) && ($new_parent = $this->driver->get_task(['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(['name' => 'objectrestoresuccess', 'vars' => ['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); } elseif (!$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'); } elseif ($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 (empty($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(['name' => 'sentresponseto', 'vars' => ['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 (!empty($refresh)) { if (!empty($refresh['id'])) { $this->encode_task($refresh); } elseif (is_array($refresh)) { foreach ($refresh as $i => $r) { $this->encode_task($refresh[$i]); } } $this->rc->output->command('plugin.update_task', $refresh); } elseif ($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(['accepted','declined','delegated']); $this->itip->set_rsvp_status(['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 (['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 (['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 (['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('/^(' . implode('|', $fillwords) . ')\s*/i', '', $raw); $raw = preg_replace($locwords, $normwords, $raw); // find date pattern $date_pattern = '!^(\d+[./-]\s*)?((?:\d+[./-])|' . implode('|', $datewords) . ')\.?(\s+\d{4})?[:;,]?\s+!i'; if (preg_match($date_pattern, $raw, $m)) { $date_str .= $m[1] . $m[2] . $m[3]; $raw = preg_replace([$date_pattern, '/^(' . implode('|', $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))) { + if (strlen($date_str) && strtotime($date_str)) { + $date = new DateTime($date_str, $this->timezone); $rec['date'] = $date->format('Y-m-d'); if (!empty($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 = []; 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 (isset($rec['recurrence']) && is_array($rec['recurrence'])) { $refdate = null; if (!empty($rec['date'])) { $refdate = new DateTime($rec['date'] . ' ' . ($rec['time'] ?? ''), $this->timezone); } elseif (!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 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'] = ''; } } $handler = new kolab_attachments_handler(); $rec['attachments'] = $handler->attachments_set(self::SESSION_KEY, $rec['id'], $rec['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'] = []; } if (!empty($rec['attendees'])) { foreach ((array) $rec['attendees'] as $i => $attendee) { if (isset($attendee['rsvp']) && 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'] = ['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) { $handler = new kolab_attachments_handler(); $handler->attachments_cleanup(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) && !empty($rec['recurrence'])) { $engine = libcalendaring::get_recurrence(); $rrule = $rec['recurrence']; $updates = []; // compute the next occurrence of date attributes foreach (['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_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'] = []; 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_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) { $is_cancelled = false; 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 = []; foreach ((array)$old['attendees'] as $attendee) { $old_attendees[] = $attendee['email']; } // send to every attendee $sent = 0; $current = []; 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'] = [$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 $a Event A * @param array $b Event B * * @return array List of differing task properties */ public static function task_diff($a, $b) { $diff = []; $ignore = ['changed' => 1, 'attachments' => 1]; foreach (array_unique(array_merge(array_keys($a), array_keys($b))) as $key) { - if (!$ignore[$key] && $a[$key] != $b[$key]) { + if (empty($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; $jsenv = []; 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 += ['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 += $jsenv[$insert_id] ?? []; + $list += $jsenv[$insert_id] ?? []; // @phpstan-ignore-line } $this->rc->output->command('plugin.insert_tasklist', $list); $success = true; } break; case 'edit': $list['oldid'] = $list['id']; if ($success = $this->driver->edit_list($list)) { $this->rc->output->command('plugin.update_tasklist', $list); } 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 = []; $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 += $jsenv[$id] ?? []; + $prop += $jsenv[$id] ?? []; // @phpstan-ignore-line $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 { $lists = []; 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 = ['mask' => $mask, 'search' => $search]; $data = $this->tasks_data($this->driver->list_tasks($filter, $lists)); $this->rc->output->command('plugin.data_ready', [ '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([ 'plugin.tasklist_print' => [$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 = ['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 = []; 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, [$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'] ?? 0); $rec['complete'] = floatval($rec['complete'] ?? 0); if (!empty($rec['created']) && is_object($rec['created'])) { $rec['created_'] = $this->rc->format_date($rec['created']); $rec['created'] = $rec['created']->format('U'); } if (!empty($rec['changed']) && is_object($rec['changed'])) { $rec['changed_'] = $this->rc->format_date($rec['changed']); $rec['changed'] = $rec['changed']->format('U'); } else { $rec['changed'] = null; } if (!empty($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 (!empty($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'], !empty($rec['time']) || !empty($rec['starttime'])); } if (!empty($rec['attachments'])) { foreach ((array) $rec['attachments'] as $k => $attachment) { $rec['attachments'][$k]['classname'] = rcube_utils::file2class($attachment['mimetype'], $attachment['name']); unset($rec['attachments'][$k]['data']); } } // 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 (!isset($rec['tags']) || !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 isset($task['description']) && 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 = []; $parent_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 = $this->task_tree[$parent_id] ?? null; } if (count($parent_titles)) { $rec['parent_title'] = implode(' » ', array_filter($parent_titles)); } } /** * Compute the filter mask of the given task * * @param array $rec 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 libcalendaring_datetime('now', $this->timezone); $today = $today_date->format('Y-m-d'); $tomorrow_date = new libcalendaring_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 = !empty($rec['startdate']) ? $rec['startdate'] : '1900-00-00'; $duedate = !empty($rec['date']) ? $rec['date'] : '3000-00-00'; if (!empty($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; } elseif ($rec['date'] < $today) { $mask |= self::FILTER_MASK_OVERDUE; } if (empty($rec['recurrence']) || $duedate < $today || $start > $weeklimit) { if ($duedate <= $today || (!empty($rec['startdate']) && $start <= $today)) { $mask |= self::FILTER_MASK_TODAY; } elseif (($start > $today && $start <= $tomorrow) || ($duedate > $today && $duedate <= $tomorrow)) { $mask |= self::FILTER_MASK_TOMORROW; } elseif (($start > $tomorrow && $start <= $weeklimit) || ($duedate > $tomorrow && $duedate <= $weeklimit)) { $mask |= self::FILTER_MASK_WEEK; } elseif ($start > $weeklimit || $duedate > $weeklimit) { $mask |= self::FILTER_MASK_LATER; } } elseif (!empty($rec['startdate']) || !empty($rec['date'])) { $date = new libcalendaring_datetime(!empty($rec['startdate']) ? $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_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; } elseif ($date == $tomorrow) { $mask |= self::FILTER_MASK_TOMORROW; } elseif ($date > $tomorrow && $date <= $weeklimit) { $mask |= self::FILTER_MASK_WEEK; } elseif ($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; } elseif (/*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 = [ '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 */ public 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']; $errors = 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, $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(['name' => 'importsuccess', 'vars' => ['nr' => $count]]), 'confirmation'); $this->rc->output->command('plugin.import_success', ['source' => $source, 'refetch' => true]); } elseif (!$errors) { $this->rc->output->command('display_message', $this->gettext('importnone'), 'notice'); $this->rc->output->command('plugin.import_success', ['source' => $source]); } else { $this->rc->output->command('plugin.import_error', ['message' => $this->gettext('importerror') . (!empty($msg) ? ': ' . $msg : '')]); } } else { if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) { $msg = $this->rc->gettext(['name' => 'filesizeerror', 'vars' => [ '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', ['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 */ public 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 = []; $filter = []; // get message UIDs for filter if ($source && ($list = $lists[$source])) { $filename = html_entity_decode($list['name']) ?: $source; $filter = [$source => true]; } elseif ($task_id) { $filename = 'tasks'; foreach (explode(',', $task_id) as $id) { [$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) ? ['uid' => $uids] : null; $_tasks = $this->driver->list_tasks($_filter, $list_id); if (!empty($_tasks)) { $tasks = array_merge($tasks, $_tasks); } } // Set file name $filename = 'tasks'; if ($source && count($tasks) == 1) { $filename = $tasks[0]['title'] ?: 'task'; } $filename .= '.ics'; $filename = $browser->ie ? rawurlencode($filename) : addcslashes($filename, '"'); $tasks = array_map([$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', [ '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']) ? [$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 = ['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 elseif ($attachment) { if (empty($attachment['body'])) { $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 = (int) rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET); $mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GET); $task = []; $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'] = [$msgref]; } // copy mail attachments to task elseif (!empty($message->attachments) && $this->driver->attachments) { $handler = new kolab_attachments_handler(); $task['attachments'] = $handler->copy_mail_attachments(self::SESSION_KEY, $task['id'], $message); } $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 = []; foreach ($this->message_tasks as $task) { $checkbox = new html_checkbox([ '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, ['value' => $task['id']]) . ' ' . html::a([ 'href' => $this->rc->url([ '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', implode("\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([ '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, [$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; $first = 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([ 'name' => 'importsuccess', 'vars' => ['nr' => $success], ]), 'confirmation'); } elseif ($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; $reply_sender = null; $organizer = null; $delegate = null; $existing = null; $deleted = null; $dontsave = false; $metadata = []; 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] ?? null; $dontsave = $_REQUEST['_folder'] === '' && $task['_method'] == 'REQUEST'; // select default list except user explicitly selected 'none' if (!$list && !$dontsave) { $list = $this->get_default_tasklist($lists); } $metadata = [ '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'], ['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'][] = [ '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 = []; 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 elseif (!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 elseif (($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 elseif ($status == 'declined' && $delete) { $deleted = $this->driver->delete_task($existing, true); $success = true; } // import the (newer) task elseif ($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); } elseif (!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'); } - } elseif (!$existing && ($status != 'declined' || $this->rc->config->get('kolab_invitation_tasklists'))) { + } elseif ($status != 'declined' || $this->rc->config->get('kolab_invitation_tasklists')) { $success = $this->driver->create_task($task); } elseif ($status == 'declined') { $error_msg = null; } } elseif ($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(['name' => $message, 'vars' => ['list' => $list['name'] ?? '']]), 'confirmation'); } $metadata['rsvp'] = !empty($metadata['rsvp']) ? 1 : 0; $metadata['after_action'] = $this->rc->config->get('calendar_itip_after_action', 0); $this->rc->output->command('plugin.itip_message_processed', $metadata); $error_msg = null; } elseif ($error_msg) { $this->rc->output->command('display_message', $error_msg, 'error'); } // send iTip reply if ($task['_method'] == 'REQUEST' && $organizer && !$noreply && !$error_msg && (empty($emails) || !in_array(strtolower($organizer['email']), $emails)) ) { $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(['name' => 'sentresponseto', 'vars' => ['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 */ public 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(['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']); } } $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 ($object['due'] && 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 ($object['start'] && 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; } elseif (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 (empty($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 (empty($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; } } diff --git a/plugins/tasklist/tasklist_ui.php b/plugins/tasklist/tasklist_ui.php index df25f981..40f9109d 100644 --- a/plugins/tasklist/tasklist_ui.php +++ b/plugins/tasklist/tasklist_ui.php @@ -1,646 +1,647 @@ * * 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 tasklist_ui { private $rc; private $plugin; private $ready = false; private $action; private $list; private $gui_objects = []; public function __construct($plugin) { $this->plugin = $plugin; $this->rc = $plugin->rc; } /** * Calendar UI initialization and requests handlers */ public function init() { if ($this->ready) { return; } // add taskbar button $this->plugin->add_button([ 'command' => 'tasks', 'class' => 'button-tasklist', 'classsel' => 'button-tasklist button-selected', 'innerclass' => 'button-inner', 'label' => 'tasklist.navtitle', 'type' => 'link', ], 'taskbar'); $this->plugin->include_stylesheet($this->plugin->local_skin_path() . '/tasklist.css'); if ($this->rc->task == 'mail' || $this->rc->task == 'tasks') { $this->plugin->include_script('tasklist_base.js'); // copy config to client $this->rc->output->set_env('tasklist_settings', $this->load_settings()); // initialize attendees autocompletion $this->rc->autocomplete_init(); } $this->ready = true; } /** * */ public function load_settings() { $settings = []; $settings['invite_shared'] = (int)$this->rc->config->get('calendar_allow_invite_shared', 0); $settings['itip_notify'] = (int)$this->rc->config->get('calendar_itip_send_option', 3); $settings['sort_col'] = $this->rc->config->get('tasklist_sort_col', ''); $settings['sort_order'] = $this->rc->config->get('tasklist_sort_order', 'asc'); // get user identity to create default attendee 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(); $settings['identity'] = [ 'name' => $identity['name'], 'email' => strtolower($identity['email']), 'emails' => ';' . strtolower(implode(';', $identity['emails'])), ]; if ($list = rcube_utils::get_input_value('_list', rcube_utils::INPUT_GPC)) { $settings['selected_list'] = $list; } if ($list && ($id = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC))) { $settings['selected_id'] = $id; // check if the referenced task is completed $task = $this->plugin->driver->get_task(['id' => $id, 'list' => $list]); if ($task && $this->plugin->driver->is_complete($task)) { $settings['selected_filter'] = 'complete'; } } elseif ($filter = rcube_utils::get_input_value('_filter', rcube_utils::INPUT_GPC)) { $settings['selected_filter'] = $filter; } return $settings; } /** * Render a HTML select box for user identity selection */ public function identity_select($attrib = []) { $attrib['name'] = 'identity'; $select = new html_select($attrib); $identities = $this->rc->user->list_emails(); foreach ($identities as $ident) { $select->add(format_email_recipient($ident['email'], $ident['name']), $ident['identity_id']); } return $select->show(null); } /** * Register handler methods for the template engine */ public function init_templates() { $this->plugin->register_handler('plugin.tasklists', [$this, 'tasklists']); $this->plugin->register_handler('plugin.tasklist_select', [$this, 'tasklist_select']); $this->plugin->register_handler('plugin.status_select', [$this, 'status_select']); $this->plugin->register_handler('plugin.searchform', [$this->rc->output, 'search_form']); $this->plugin->register_handler('plugin.quickaddform', [$this, 'quickadd_form']); $this->plugin->register_handler('plugin.tasks', [$this, 'tasks_resultview']); $this->plugin->register_handler('plugin.tags_editline', [$this, 'tags_editline']); $this->plugin->register_handler('plugin.alarm_select', [$this, 'alarm_select']); $this->plugin->register_handler('plugin.recurrence_form', [$this->plugin->lib, 'recurrence_form']); $this->plugin->register_handler('plugin.attendees_list', [$this, 'attendees_list']); $this->plugin->register_handler('plugin.attendees_form', [$this, 'attendees_form']); $this->plugin->register_handler('plugin.identity_select', [$this, 'identity_select']); $this->plugin->register_handler('plugin.edit_attendees_notify', [$this, 'edit_attendees_notify']); $this->plugin->register_handler('plugin.task_rsvp_buttons', [$this->plugin->itip, 'itip_rsvp_buttons']); $this->plugin->register_handler('plugin.object_changelog_table', ['libkolab', 'object_changelog_table']); $this->plugin->register_handler('plugin.tasks_export_form', [$this, 'tasks_export_form']); $this->plugin->register_handler('plugin.tasks_import_form', [$this, 'tasks_import_form']); kolab_attachments_handler::ui(); $this->plugin->include_script('tasklist.js'); $this->plugin->api->include_script('libkolab/libkolab.js'); } /** * */ public function tasklists($attrib = []) { $tree = true; $jsenv = []; $lists = $this->plugin->driver->get_lists(0, $tree); if (empty($attrib['id'])) { $attrib['id'] = 'rcmtasklistslist'; } // walk folder tree + // @phpstan-ignore-next-line FIXME: does it make sense? if (is_object($tree)) { $html = $this->list_tree_html($tree, $lists, $jsenv, $attrib); } else { // fall-back to flat folder listing $attrib['class'] = ($attrib['class'] ?? '') . ' flat'; $html = ''; foreach ((array) $lists as $id => $prop) { if (!empty($attrib['activeonly']) && empty($prop['active'])) { continue; } $html .= html::tag( 'li', [ 'id' => 'rcmlitasklist' . rcube_utils::html_identifier($id), 'class' => $prop['group'] ?? null, ], $this->tasklist_list_item($id, $prop, $jsenv, !empty($attrib['activeonly'])) ); } } $this->rc->output->include_script('treelist.js'); $this->rc->output->set_env('source', rcube_utils::get_input_value('source', rcube_utils::INPUT_GET)); $this->rc->output->set_env('tasklists', $jsenv); $this->register_gui_object('tasklistslist', $attrib['id']); return html::tag('ul', $attrib, $html, html::$common_attrib); } /** * Return html for a structured list
        for the folder tree */ public function list_tree_html($node, $data, &$jsenv, $attrib) { $out = ''; foreach ($node->children as $folder) { $id = $folder->id; $prop = $data[$id]; $is_collapsed = false; // TODO: determine this somehow? $content = $this->tasklist_list_item($id, $prop, $jsenv, !empty($attrib['activeonly'])); if (!empty($folder->children)) { $content .= html::tag( 'ul', - ['style' => ($is_collapsed ? "display:none;" : null)], + ['style' => ($is_collapsed ? "display:none;" : null)], // @phpstan-ignore-line $this->list_tree_html($folder, $data, $jsenv, $attrib) ); } if (strlen($content)) { $out .= html::tag( 'li', [ 'id' => 'rcmlitasklist' . rcube_utils::html_identifier($id), 'class' => $prop['group'] . ($prop['virtual'] ? ' virtual' : ''), ], $content ); } } return $out; } /** * Helper method to build a tasklist item (HTML content and js data) */ public function tasklist_list_item($id, $prop, &$jsenv, $activeonly = false) { // enrich list properties with settings from the driver if (empty($prop['virtual'])) { unset($prop['user_id']); $prop['alarms'] = $this->plugin->driver->alarms; $prop['undelete'] = $this->plugin->driver->undelete; $prop['sortable'] = $this->plugin->driver->sortable; $prop['attachments'] = $this->plugin->driver->attachments; $prop['attendees'] = $this->plugin->driver->attendees; $prop['caldavurl'] = $this->plugin->driver->tasklist_caldav_url($prop); $jsenv[$id] = $prop; } $classes = ['tasklist']; $title = ''; if (!empty($prop['title'])) { $title = $prop['title']; } elseif (empty($prop['listname']) || $prop['name'] != $prop['listname'] || strlen($prop['name']) > 25) { - html_entity_decode($prop['name'], ENT_COMPAT, RCUBE_CHARSET); + $title = html_entity_decode($prop['name'], ENT_COMPAT, RCUBE_CHARSET); } if (!empty($prop['virtual'])) { $classes[] = 'virtual'; } elseif (empty($prop['editable'])) { $classes[] = 'readonly'; } if (!empty($prop['subscribed'])) { $classes[] = 'subscribed'; } if (!empty($prop['class'])) { $classes[] = $prop['class']; } if (!$activeonly || !empty($prop['active'])) { $label_id = 'tl:' . $id; $chbox = html::tag('input', [ 'type' => 'checkbox', 'name' => '_list[]', 'value' => $id, 'checked' => !empty($prop['active']), 'title' => $this->plugin->gettext('activate'), 'aria-labelledby' => $label_id, ]); $actions = ''; if (!empty($prop['removable'])) { $actions .= html::a(['href' => '#', 'class' => 'remove', 'title' => $this->plugin->gettext('removelist')], ' '); } $actions .= html::a(['href' => '#', 'class' => 'quickview', 'title' => $this->plugin->gettext('focusview'), 'role' => 'checkbox', 'aria-checked' => 'false'], ' '); if (isset($prop['subscribed'])) { $actions .= html::a(['href' => '#', 'class' => 'subscribed', 'title' => $this->plugin->gettext('tasklistsubscribe'), 'role' => 'checkbox', 'aria-checked' => $prop['subscribed'] ? 'true' : 'false'], ' '); } return html::div( implode(' ', $classes), html::a( ['class' => 'listname', 'title' => $title, 'href' => '#', 'id' => $label_id], !empty($prop['listname']) ? $prop['listname'] : $prop['name'] ) . (!empty($prop['virtual']) ? '' : $chbox . html::span('actions', $actions)) ); } return ''; } /** * Render HTML form for task status selector */ public function status_select($attrib = []) { $attrib['name'] = 'status'; $select = new html_select($attrib); $select->add('---', ''); $select->add($this->plugin->gettext('status-needs-action'), 'NEEDS-ACTION'); $select->add($this->plugin->gettext('status-in-process'), 'IN-PROCESS'); $select->add($this->plugin->gettext('status-completed'), 'COMPLETED'); $select->add($this->plugin->gettext('status-cancelled'), 'CANCELLED'); return $select->show(null); } /** * Render a HTML select box for list selection */ public function tasklist_select($attrib = []) { if (empty($attrib['name'])) { $attrib['name'] = 'list'; } $attrib['is_escaped'] = true; $select = new html_select($attrib); $default = null; if (!empty($attrib['extra'])) { foreach ((array) $attrib['extra'] as $id => $name) { $select->add($name, $id); } } foreach ((array) $this->plugin->driver->get_lists() as $id => $prop) { if (!empty($prop['editable']) || strpos($prop['rights'], 'i') !== false) { $select->add($prop['name'], $id); if (!$default || !empty($prop['default'])) { $default = $id; } } } return $select->show($default); } public function tasklist_editform($action, $list = []) { $this->action = $action; $this->list = $list; $this->rc->output->set_env('pagetitle', $this->plugin->gettext('arialabeltasklistform')); $this->rc->output->add_handler('folderform', [$this, 'tasklistform']); $this->rc->output->send('libkolab.folderform'); } public function tasklistform($attrib) { $fields = [ 'name' => [ 'id' => 'taskedit-tasklistname', 'label' => $this->plugin->gettext('listname'), 'value' => html::tag('input', ['id' => 'taskedit-tasklistname', 'name' => 'name', 'type' => 'text', 'class' => 'text', 'size' => 40]), ], /* 'color' => array( 'id' => 'taskedit-color', 'label' => $this->plugin->gettext('color'), 'value' => html::tag('input', array('id' => 'taskedit-color', 'name' => 'color', 'type' => 'text', 'class' => 'text colorpicker', 'size' => 6)), ), */ 'showalarms' => [ 'id' => 'taskedit-showalarms', 'label' => $this->plugin->gettext('showalarms'), 'value' => html::tag('input', ['id' => 'taskedit-showalarms', 'name' => 'showalarms', 'type' => 'checkbox', 'value' => 1]), ], ]; return html::tag( 'form', $attrib + ['action' => "#", 'method' => "post", 'id' => 'tasklisteditform'], $this->plugin->driver->tasklist_edit_form($this->action, $this->list, $fields) ); } /** * Render HTML form for alarm configuration */ public function alarm_select($attrib = []) { $attrib['_type'] = 'task'; return $this->plugin->lib->alarm_select($attrib, $this->plugin->driver->alarm_types, $this->plugin->driver->alarm_absolute); } /** * */ public function quickadd_form($attrib) { $attrib += ['action' => $this->rc->url('add'), 'method' => 'post', 'id' => 'quickaddform']; $label = html::label(['for' => 'quickaddinput', 'class' => 'voice'], $this->plugin->gettext('quickaddinput')); $input = new html_inputfield(['name' => 'text', 'id' => 'quickaddinput']); $button = html::tag('input', [ 'type' => 'submit', 'value' => '+', 'title' => $this->plugin->gettext('createtask'), 'class' => 'button mainaction', ]); $this->register_gui_object('quickaddform', $attrib['id']); return html::tag('form', $attrib, $label . $input->show() . $button); } /** * The result view */ public function tasks_resultview($attrib) { $attrib += ['id' => 'rcmtaskslist']; $this->register_gui_object('resultlist', $attrib['id']); unset($attrib['name']); return html::tag('ul', $attrib, ''); } /** * Interactive UI element to add/remove tags */ public function tags_editline($attrib) { $attrib += ['id' => 'rcmtasktagsedit']; $this->register_gui_object('edittagline', $attrib['id']); $input = new html_inputfield([ 'name' => 'tags[]', 'class' => 'tag', 'size' => !empty($attrib['size']) ? $attrib['size'] : null, 'tabindex' => $attrib['tabindex'] ?? null, ]); unset($attrib['tabindex']); return html::div($attrib, $input->show('')); } /** * */ public function attendees_list($attrib = []) { // add "noreply" checkbox to attendees table only $invitations = strpos($attrib['id'], 'attend') !== false; $invite = new html_checkbox(['value' => 1, 'id' => 'edit-attendees-invite']); $table = new html_table(['cols' => 4 + intval($invitations), 'border' => 0, 'cellpadding' => 0, 'class' => 'rectable']); // $table->add_header('role', $this->plugin->gettext('role')); $table->add_header('name', $this->plugin->gettext($attrib['coltitle'] ?: 'attendee')); $table->add_header('confirmstate', $this->plugin->gettext('confirmstate')); if ($invitations) { $table->add_header( ['class' => 'invite', 'title' => $this->plugin->gettext('sendinvitations')], $invite->show(1) . html::label('edit-attendees-invite', html::span('inner', $this->plugin->gettext('sendinvitations'))) ); } $table->add_header('options', ''); // hide invite column if disabled by config $itip_notify = (int)$this->rc->config->get('calendar_itip_send_option', 3); if ($invitations && !($itip_notify & 2)) { $css = sprintf('#%s td.invite, #%s th.invite { display:none !important }', $attrib['id'], $attrib['id']); $this->rc->output->add_footer(html::tag('style', ['type' => 'text/css'], $css)); } return $table->show($attrib); } /** * */ public function attendees_form($attrib = []) { $input = new html_inputfield([ 'name' => 'participant', 'id' => 'edit-attendee-name', 'size' => !empty($attrib['size']) ? $attrib['size'] : null, 'class' => 'form-control', ]); $textarea = new html_textarea([ 'name' => 'comment', 'id' => 'edit-attendees-comment', 'rows' => 4, 'cols' => 55, 'title' => $this->plugin->gettext('itipcommenttitle'), 'class' => 'form-control', ]); return html::div( $attrib, html::div( 'form-searchbar', $input->show() . " " . html::tag('input', ['type' => 'button', 'class' => 'button', 'id' => 'edit-attendee-add', 'value' => $this->plugin->gettext('addattendee')]) // . " " . html::tag('input', array('type' => 'button', 'class' => 'button', 'id' => 'edit-attendee-schedule', 'value' => $this->plugin->gettext('scheduletime').'...')) ) . html::p('attendees-commentbox', html::label('edit-attendees-comment', $this->plugin->gettext('itipcomment')) . $textarea->show()) ); } /** * */ public function edit_attendees_notify($attrib = []) { $checkbox = new html_checkbox(['name' => '_notify', 'id' => 'edit-attendees-donotify', 'value' => 1, 'class' => 'pretty-checkbox']); return html::div($attrib, html::label(null, $checkbox->show(1) . ' ' . $this->plugin->gettext('sendnotifications'))); } /** * Form for uploading and importing tasks */ public function tasks_import_form($attrib = []) { if (empty($attrib['id'])) { $attrib['id'] = 'rcmImportForm'; } // Get max filesize, enable upload progress bar $max_filesize = $this->rc->upload_init(); $accept = '.ics, text/calendar, text/x-vcalendar, application/ics'; if (class_exists('ZipArchive', false)) { $accept .= ', .zip, application/zip'; } $input = new html_inputfield([ 'id' => 'importfile', 'type' => 'file', 'name' => '_data', 'size' => !empty($attrib['uploadfieldsize']) ? $attrib['uploadfieldsize'] : null, 'accept' => $accept, ]); $html = html::div( 'form-section form-group row', html::label(['class' => 'col-sm-4 col-form-label', 'for' => 'importfile'], rcube::Q($this->rc->gettext('importfromfile'))) . html::div('col-sm-8', $input->show() . html::div('hint', $this->rc->gettext(['name' => 'maxuploadsize', 'vars' => ['size' => $max_filesize]]))) ); $html .= html::div( 'form-section form-group row', html::label(['for' => 'task-import-list', 'class' => 'col-sm-4 col-form-label'], $this->plugin->gettext('list')) . html::div('col-sm-8', $this->tasklist_select(['name' => 'source', 'id' => 'task-import-list', 'editable' => true])) ); $this->rc->output->add_gui_object('importform', $attrib['id']); $this->rc->output->add_label('import', 'importerror'); return html::tag('p', null, $this->plugin->gettext('importtext')) . html::tag( 'form', [ 'action' => $this->rc->url(['task' => 'tasklist', 'action' => 'import']), 'method' => 'post', 'enctype' => 'multipart/form-data', 'id' => $attrib['id'], ], $html ); } /** * Form to select options for exporting tasks */ public function tasks_export_form($attrib = []) { if (empty($attrib['id'])) { $attrib['id'] = 'rcmTaskExportForm'; } $html = html::div( 'form-section form-group row', html::label(['for' => 'task-export-list', 'class' => 'col-sm-4 col-form-label'], $this->plugin->gettext('list')) . html::div('col-sm-8', $this->tasklist_select([ 'name' => 'source', 'id' => 'task-export-list', 'extra' => ['' => '- ' . $this->plugin->gettext('currentview') . ' -'], ])) ); $checkbox = new html_checkbox(['name' => 'attachments', 'id' => 'task-export-attachments', 'value' => 1, 'class' => 'form-check-input pretty-checkbox']); $html .= html::div( 'form-section row form-check', html::label(['for' => 'task-export-attachments', 'class' => 'col-sm-4 col-form-label'], $this->plugin->gettext('exportattachments')) . html::div('col-sm-8', $checkbox->show(1)) ); $this->register_gui_object('exportform', $attrib['id']); return html::tag( 'form', [ 'action' => $this->rc->url(['task' => 'tasklist', 'action' => 'export']), 'method' => 'post', 'id' => $attrib['id'], ], $html ); } /** * Wrapper for rcube_output_html::add_gui_object() */ public function register_gui_object($name, $id) { $this->gui_objects[$name] = $id; $this->rc->output->add_gui_object($name, $id); } /** * Getter for registered gui objects. * (for manual registration when loading the inline UI) */ public function get_gui_objects() { return $this->gui_objects; } }