diff --git a/config/config.ini.sample b/config/config.ini.sample index 8fcdf20..ba6ecd7 100644 --- a/config/config.ini.sample +++ b/config/config.ini.sample @@ -1,93 +1,93 @@ ;; Kolab Free/Busy Service configuration ; Logging configuration [log] driver = file ; supported drivers: file, syslog path = ./logs name = freebusy level = 300 ; (100 = Debug, 200 = Info, 300 = Warn, 400 = Error, 500 = Critical) ;; ;; try local filesystem first (F/B has been generated externally) ;; [directory "local"] type = static filter = "@example.org" fbsource = file:/var/lib/kolab-freebusy/%s.ifb ;; ;; check if primary email address hits a cache file (saves LDAP lookups) ;; [directory "local-cache"] type = static fbsource = file:/var/cache/kolab-freebusy/%s.ifb expires = 10m ;; ;; local Kolab directory server ;; [directory "kolab-people"] type = ldap host = "ldap://localhost:389" bind_dn = "uid=kolab-service,ou=Special Users,dc=example,dc=org" bind_pw = "SomePassword" ; base_dn and filter can use these variables: ; %dc = domain root dn, %u = username part, %s = the full username base_dn = "ou=People,dc=example,dc=org" filter = "(&(objectClass=kolabInetOrgPerson)(|(mail=%s)(alias=%s))" -attributes = mail +mail_attributes = mail lc_attributes = mail primary_domain = "example.org" ; set domain_* options to enforce the resolving of the domain root dn (%dc) through LDAP domain_base_dn = "cn=kolab,cn=config" domain_filter = "(&(objectclass=domainrelatedobject)(associateddomain=%s))" ; %mail is replaced by the user's mail attribute found in LDAP fbsource = imaps://%mail:CyrusAdminPassword@imap.example.org/?proxy_auth=cyrus-admin loglevel = 300 cacheto = /var/cache/kolab-freebusy/%mail.ifb expires = 10m ;; -;; resolve Kolab resources from LDAP and fetch calendar from IMAP +;; Resolve Kolab resources from LDAP and fetch calendar from IMAP ;; [directory "kolab-resources"] type = ldap host = "ldap://localhost:389" bind_dn = "uid=kolab-service,ou=Special Users,dc=example,dc=org" bind_pw = "SomePassword" base_dn = "ou=Resources,dc=example,dc=org" filter = "(&(objectClass=kolabsharedfolder)(kolabfoldertype=event)(mail=%s))" -attributes = mail, kolabtargetfolder +mail_attributes = mail primary_domain = "example.org" ; Use the Free/Busy daemon that separates the abuse of credentials ;fbsource = "fbdaemon://localhost:?folder=%kolabtargetfolder" ;timeout = 10 ; abort after 10 seconds fbsource = "imap://cyrus-admin:CyrusAdminPassword@imap.lhm.klab.cc/%kolabtargetfolder?acl=lrs" cacheto = /var/cache/kolab-freebusy/%mail.ifb expires = 10m loglevel = 300 ;; ;; For collections, aggregate the free/busy data from all its members ;; [directory "kolab-resource-collections"] type = ldap host = "ldap://localhost:389" bind_dn = "uid=kolab-service,ou=Special Users,dc=example,dc=org" bind_pw = "SomePassword" base_dn = "ou=Resources,dc=example,dc=org" filter = "(&(objectClass=kolabgroupofuniquenames)(mail=%s))" -attributes = uniquemember, mail +mail_attributes = mail resolve_dn = uniquemember resolve_attribute = mail ; the 'aggregate' source takes one parameter ; denoting the attribute holding all member email addresses fbsource = "aggregate://%uniquemember" ; consider these directories for getting the member's free/busy data directories = kolab-resources cacheto = /var/cache/kolab-freebusy/%mail.ifb expires = 10m loglevel = 200 ; Info diff --git a/lib/Kolab/FreeBusy/DirectoryLDAP.php b/lib/Kolab/FreeBusy/DirectoryLDAP.php index 9e6366a..c011f0c 100644 --- a/lib/Kolab/FreeBusy/DirectoryLDAP.php +++ b/lib/Kolab/FreeBusy/DirectoryLDAP.php @@ -1,168 +1,176 @@ * * 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 . */ namespace Kolab\FreeBusy; // PEAR modules operate in global namespace use \Net_LDAP3; use \Kolab\Config; use \Monolog\Logger as Monolog; /** * Implementation of an address lookup using an LDAP directory */ class DirectoryLDAP extends Directory { private $ldap; private $logger; private $ready = false; /** * Default constructor loading directory configuration */ public function __construct($config) { $this->config = $config; $host = parse_url($config['host']); $ldap_config = array( 'hosts' => array($config['host']), 'port' => $host['port'] ?: 389, 'use_tls' => $host['scheme'] == 'tls', 'root_dn' => $config['root_dn'] ?: $config['base_dn'], 'log_hook' => array($this, 'log'), ) + $config; // instantiate Net_LDAP3 and connect with logger $this->logger = Logger::get('ldap', intval($config['loglevel'])); $this->ldap = new Net_LDAP3($ldap_config); // connect + bind to LDAP server if ($this->ldap->connect()) { $this->ready = $this->ldap->bind($config['bind_dn'], $config['bind_pw']); } if ($this->ready) { $this->logger->addInfo("Connected to $config[host] with '$config[bind_dn]'"); } else { $this->logger->addWarning("Connectiion to $config[host] with '$config[bind_dn]' failed!"); } } /** * Callback for Net_LDAP3 logging */ public function log($level, $msg) { // map PHP log levels to Monolog levels static $loglevels = array( LOG_DEBUG => Monolog::DEBUG, LOG_NOTICE => Monolog::NOTICE, LOG_INFO => Monolog::INFO, LOG_WARNING => Monolog::WARNING, LOG_ERR => Monolog::ERROR, LOG_CRIT => Monolog::CRITICAL, LOG_ALERT => Monolog::ALERT, LOG_EMERG => Monolog::EMERGENCY, ); $msg = is_array($msg) ? join('; ', $msg) : strval($msg); $this->logger->addRecord($loglevels[$level], $msg); } /** * @see Directory::resolve() */ public function resolve($user) { $result = array('s' => $user); if ($this->ready) { // extract domain name list($u, $d) = explode('@', $user); if (empty($d)) $d = $this->config['primary_domain']; // resolve domain root dn if (!empty($this->config['domain_filter'])) { $dc = $this->ldap->domain_root_dn($d); } else { $dc = 'dc=' . str_replace('.', ',dc=', $d); } + // result attributes + $attribs = array_unique(array_merge( + Config::convert($this->config['mail_attributes'], Config::ARR), + Config::convert($this->config['attributes'], Config::ARR), // deprecated + Config::convert($this->config['resolve_dn'], Config::ARR), + Config::convert($this->config['resolve_attribute'], Config::ARR) + )); + // search with configured base_dn and filter $replaces = array('%dc' => $dc, '%u' => $u); $base_dn = strtr($this->config['base_dn'], $replaces); $filter = str_replace('%s', Net_LDAP3::quote_string($user), strtr($this->config['filter'], $replaces)); - $ldapresult = $this->ldap->search($base_dn, $filter, 'sub', Config::convert($this->config['attributes'], Config::ARR)); + $ldapresult = $this->ldap->search($base_dn, $filter, 'sub', $attribs); // got a valid result if ($ldapresult && $ldapresult->count()) { $ldapresult->rewind(); $entry = Net_LDAP3::normalize_entry($ldapresult->current()); // get the first entry $this->logger->addInfo("Found " . $ldapresult->count() . " entries for $filter", $entry); // convert entry attributes to strings and add them to the final result hash array $result += self::_compact_entry($entry); // resolve DN attribute into the actual record if (!empty($this->config['resolve_dn']) && array_key_exists($this->config['resolve_dn'], $result)) { $k = $this->config['resolve_dn']; $member_attr = $this->config['resolve_attribute'] ?: 'mail'; foreach ((array)$result[$k] as $i => $member_dn) { if ($member_rec = $this->ldap->get_entry($member_dn, array($member_attr))) { $member_rec = self::_compact_entry(Net_LDAP3::normalize_entry($member_rec)); $result[$k][$i] = $member_rec[$member_attr]; } } } return $result; } $this->logger->addInfo("No entry found for $filter"); } return false; } /** * Helper method to convert entry attributes to simple values */ private static function _compact_entry($entry) { $result = array(); foreach ($entry as $k => $v) { if (is_array($v) && count($v) > 1) { $result[$k] = array_map('strval', $v); } else if (!empty($v)) { $result[$k] = strval(is_array($v) ? $v[0] : $v); } } return $result; } } diff --git a/lib/Kolab/FreeBusy/SourceIMAP.php b/lib/Kolab/FreeBusy/SourceIMAP.php index 2b9c910..f8b0c1f 100644 --- a/lib/Kolab/FreeBusy/SourceIMAP.php +++ b/lib/Kolab/FreeBusy/SourceIMAP.php @@ -1,368 +1,378 @@ * * 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 . */ namespace Kolab\FreeBusy; use Kolab\Config; use Sabre\VObject; use Sabre\VObject\Component\VCalendar; use Sabre\VObject\FreeBusyGenerator; use Sabre\VObject\ParseException; /** * Implementation of a Free/Busy data source reading from IMAP * (not yet implemented!) */ class SourceIMAP extends Source { private $folders = array(); public function __construct($config) { - parent::__construct($config + array('mail_attributes' => 'mail')); + if (empty($config['mail_attributes'])) { + if (!empty($config['attributes'])) { + Logger::get('imap')->addWarning("Use of deprecated 'attributes' option. Switch to 'mail_attributes'!"); + $config['mail_attributes'] = $config['attributes']; + } + else { + $config['mail_attributes'] = 'mail'; + } + } + + parent::__construct($config); // load the Roundcube framework with its autoloader require_once KOLAB_FREEBUSY_ROOT . '/lib/Roundcube/bootstrap.php'; $rcube = \rcube::get_instance(\rcube::INIT_WITH_DB | \rcube::INIT_WITH_PLUGINS); // Load plugins $rcube->plugins->init($rcube); $rcube->plugins->load_plugins(array(), array('libkolab','libcalendaring')); // get libvcalendar instance $this->libvcal = \libcalendaring::get_ical(); } /** * @see Source::getFreeBusyData() */ public function getFreeBusyData($user, $extended) { $log = Logger::get('imap', intval($this->config['loglevel'])); $config = $this->getUserConfig($user); parse_str(strval($config['query']), $param); $config += $param; // log this... $log->addInfo("Fetching data for ", $config); // caching is enabled if (!empty($config['cacheto'])) { // check for cached data if ($cached = $this->getCached($config)) { $log->addInfo("Deliver cached data from " . $config['cacheto']); return $cached; } // touch cache file to avoid multiple requests generating the same data if (file_exists($config['cacheto'])) { touch($config['cacheto']); } else { file_put_contents($config['cacheto'], Utils::dummyVFreebusy($user['mail'])); $tempfile = $config['cacheto']; } } // compose a list of user email addresses $user_email = array(); foreach (Config::convert($this->config['mail_attributes'], Config::ARR) as $key) { if (!empty($user[$key])) { $user_email = array_merge($user_email, (array)$user[$key]); } } // synchronize with IMAP and read Kolab event objects if ($imap = $this->imap_login($config)) { // target folder is specified in source URI if ($config['path'] && $config['path'] != '/') { $folders = array(\kolab_storage::get_folder(substr($config['path'], 1))); $read_all = true; } else { // list all folders of type 'event' $folders = \kolab_storage::get_folders('event', false); $read_all = false; } $utc = new \DateTimezone('UTC'); $dtstart = Utils::periodStartDT(); $dtend = Utils::periodEndDT(); $calendar = new VObject\Component\VCalendar(); $seen = array(); $this->libvcal->set_timezone($utc); $log->addInfo("Getting events from IMAP in range", array($dtstart->format('c'), $dtend->format('c'))); $query = array(array('dtstart','<=',$dtend), array('dtend','>=',$dtstart)); foreach ($folders as $folder) { $count = 0; $namespace = $folder->get_namespace(); $log->debug('Reading Kolab folder: ' . $folder->name, $folder->get_folder_info()); // skip other user's shared calendars if (!$read_all && $namespace == 'other') { continue; } // set ACL (temporarily) if ($config['acl']) { $folder->_old_acl = $folder->get_myrights(); $imap->set_acl($folder->name, $config['user'], $config['acl']); } foreach ($folder->select($query) as $event) { //$log->debug('Processing event', $event); if ($event['cancelled']) { continue; } $event['namespace'] = $namespace; // only consider shared namespace events if user is a confirmed participant (or organizer) // skip declined events if (!$this->check_participation($event, $user_email, $status) || ($status != 'ACCEPTED' && $status != 'TENTATIVE') ) { $log->debug('Skip shared/declined event', array($event['uid'], $event['title'])); continue; } // translate all-day dates into absolute UTC times // FIXME: use server timezone? if ($event['allday']) { $utc = new \DateTimeZone('UTC'); if (!empty($event['start'])) { $event['start']->setTimeZone($utc); $event['start']->setTime(0,0,0); } if (!empty($event['end'])) { $event['end']->setTimeZone($utc); $event['end']->setTime(23,59,59); } } // avoid duplicate entries $key = $event['start']->format('c') . '/' . $event['end']->format('c'); if ($seen[$key]++) { $log->debug('Skipping duplicate event at ' . $key, array($event['uid'], $event['title'])); continue; } // copied from libvcalendar::_to_ical() $ve = $this->to_vevent($event, $calendar, $user_email); if ($event['recurrence']) { if ($exdates = $event['recurrence']['EXDATE']) unset($event['recurrence']['EXDATE']); if ($rdates = $event['recurrence']['RDATE']) unset($event['recurrence']['RDATE']); if ($event['recurrence']['FREQ']) $ve->add('RRULE', \libcalendaring::to_rrule($event['recurrence'])); // consider recurrence exceptions if (is_array($event['recurrence']['EXCEPTIONS'])) { foreach ($event['recurrence']['EXCEPTIONS'] as $i => $exception) { $exception['namespace'] = $namespace; // register exdate for this occurrence if ($exception['recurrence_date'] instanceof \DateTime) { $exdates[] = $exception['recurrence_date']; } // add exception to vcalendar container if (!$exception['cancelled'] && $this->check_participation($exception, $user_email, $status) && $status != 'DECLINED') { $vex = $this->to_vevent($exception, $calendar, $user_email); $vex->UID = $event['uid'] . '-' . $i; $calendar->add($vex); $log->debug("Adding event exception for processing:\n" . $vex->serialize()); } } } // add EXDATEs each one per line (for Thunderbird Lightning) if ($exdates) { foreach ($exdates as $ex) { if ($ex instanceof \DateTime) { $exd = clone $event['start']; $exd->setDate($ex->format('Y'), $ex->format('n'), $ex->format('j')); $exd->setTimeZone($utc); $ve->add($this->libvcal->datetime_prop($calendar, 'EXDATE', $exd, true)); } } } // add RDATEs if (!empty($rdates)) { foreach ((array)$rdates as $rdate) { $ve->add($this->libvcal->datetime_prop($calendar, 'RDATE', $rdate)); } } } // append to vcalendar container $calendar->add($ve); $count++; $log->debug("Adding event for processing:\n" . $ve->serialize()); } $log->addInfo("Added $count events from folder " . $folder->name); } $this->imap_disconnect($imap, $config, $folders); // feed the calendar object into the free/busy generator // we must specify a start and end date, because recurring events are expanded. nice! $fbgen = new FreeBusyGenerator($dtstart, $dtend, $calendar); // get the freebusy report $freebusy = $fbgen->getResult(); $freebusy->PRODID = Utils::PRODID; $freebusy->METHOD = 'PUBLISH'; $freebusy->VFREEBUSY->UID = date('YmdHi') . '-' . substr(md5($user_email[0]), 0, 16); $freebusy->VFREEBUSY->ORGANIZER = 'mailto:' . $user_email[0]; // serialize to VCALENDAR format return $freebusy->serialize(); } // remove (temporary) cache file again else if ($tempfile) { unlink($tempfile); } return false; } /** * Helper method to establish connection to the configured IMAP backend */ private function imap_login($config) { $rcube = \rcube::get_instance(); $imap = $rcube->get_storage(); $host = $config['host']; $port = $config['port'] ?: ($config['scheme'] == 'imaps' ? 993 : 143); // detect ssl|tls method if ($config['scheme'] == 'imaps' || $port == 993) { $ssl = 'imaps'; } elseif ($config['scheme'] == 'tls') { $ssl = 'tls'; } else { $ssl = false; } // enable proxy authentication if (!empty($config['proxy_auth'])) { $imap->set_options(array('auth_cid' => $config['proxy_auth'], 'auth_pw' => $config['pass'])); } // authenticate user in IMAP if (!$imap->connect($host, $config['user'], $config['pass'], $port, $ssl)) { Logger::get('imap')->addWarning("Failed to connect to IMAP server: " . $imap->get_error_code(), $config); return false; } // fake user object to rcube framework $rcube->set_user(new \rcube_user('0', array('username' => $config['user']))); return $imap; } /** * Cleanup and close IMAP connection */ private function imap_disconnect($imap, $config, $folders) { // reset ACL if ($config['acl'] && !empty($folders)) { foreach ($folders as $folder) { $imap->set_acl($folder->name, $config['user'], $folder->_old_acl); } } $imap->close(); } /** * Helper method to build a Sabre/VObject from the gieven event data */ private function to_vevent($event, $cal, $user_email) { // copied from libvcalendar::_to_ical() $ve = $cal->create('VEVENT'); $ve->UID = $event['uid']; if (!empty($event['start'])) $ve->add($this->libvcal->datetime_prop($cal, 'DTSTART', $event['start'], false, false)); if (!empty($event['end'])) $ve->add($this->libvcal->datetime_prop($cal, 'DTEND', $event['end'], false, false)); if (!empty($event['free_busy'])) $ve->add('TRANSP', $event['free_busy'] == 'free' ? 'TRANSPARENT' : 'OPAQUE'); if ($this->check_participation($event, $user_email, $status) && $status) { $ve->add('STATUS', $status); } return $ve; } /** * Helper method to check the participation status of the requested user */ private function check_participation($event, $user_email, &$status = null) { if (is_array($event['organizer']) && !empty($event['organizer']['email'])) { if (in_array($event['organizer']['email'], $user_email)) { $is_organizer = true; } } if (!$is_organizer && is_array($event['attendees'])) { foreach ($event['attendees'] as $attendee) { if (in_array($attendee['email'], $user_email)) { $status = $attendee['status']; return true; } } } if ($is_organizer || $event['namespace'] == 'personal') { $status = 'ACCEPTED'; if ($event['free_busy'] == 'tentative') { $status = 'TENTATIVE'; } else if (!empty($event['status'])) { $status = $event['status']; } return true; } return false; } }