summaryrefslogtreecommitdiff
path: root/lib/Kolab/FreeBusy/SourceAggregator.php
blob: 05f09719ab45537debacfd38a40a93ede27918ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
<?php

/**
 * This file is part of the Kolab Server Free/Busy Service
 *
 * @author Thomas Bruederli <bruederli@kolabsys.com>
 *
 * Copyright (C) 2014, Kolab Systems AG <contact@kolabsys.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

namespace Kolab\FreeBusy;


use Kolab\Config;
use Sabre\VObject;
use Sabre\VObject\Reader;
use Sabre\VObject\ParseException;

/**
 * Implementation of a Free/Busy data source aggregating multiple free/busy data sources
 */
class SourceAggregator extends Source
{
	/**
	 * @see Source::getFreeBusyData()
	 */
	public function getFreeBusyData($user, $extended)
	{
		$log = Logger::get('aggregate', intval($this->config['loglevel']));
		# $config = $this->getUserConfig($user);

		$attr = str_replace('%', '', strval($this->config['path'] ?: $this->config['host']));
		if (!empty($user[$attr])) {
			$members = (array)$user[$attr];
			$busy_periods = array();
			$log->debug("Aggregate data for members", $members);

			foreach ($members as $i => $member) {
				$busy_times[$i] = array();

				if ($member_data = $this->getDataFor($member)) {
					try {
						$vobject = Reader::read($member_data, Reader::OPTION_FORGIVING | Reader::OPTION_IGNORE_INVALID_LINES);
					}
					catch (Exception $e) {
						$log->addError("Error parsing freebusy data", $e);
						#continue;
					}

					// extract busy periods
					if ($vobject && $vobject->name == 'VCALENDAR') {
						$vfb = reset($vobject->select('VFREEBUSY'));
						foreach ((array)$vfb->children as $prop) {
							switch ($prop->name) {
							case 'FREEBUSY':
								// The freebusy component can hold more than 1 value, separated by commas.
								$periods = explode(',', $prop->value);
								$fbtype = strval($prop['FBTYPE']) ?: 'BUSY';

								foreach ($periods as $period) {
									// Every period is formatted as [start]/[end]. The start is an
									// absolute UTC time, the end may be an absolute UTC time, or
									// duration (relative) value.
									list($busy_start, $busy_end) = explode('/', $period);

									$busy_start = VObject\DateTimeParser::parse($busy_start);
									$busy_end = VObject\DateTimeParser::parse($busy_end);
									if ($busy_end instanceof \DateInterval) {
										$tmp = clone $busy_start;
										$tmp->add($busy_end);
										$busy_end = $tmp;
									}

									if ($busy_end && $busy_end > $busy_start) {
										$busy_times[$i][] = array($busy_start, $busy_end, $fbtype);
									}
								}
								break;
							}
						}
					}
				}
			}

			$calendar = VObject\Component::create('VCALENDAR');
			$calendar->PRODID = Utils::PRODID;
			$calendar->METHOD = 'PUBLISH';
			$calendar->CALSCALE = 'GREGORIAN';

			$vfreebusy = VObject\Component::create('VFREEBUSY');
			$vfreebusy->UID = date('YmdHi') . '-' . substr(md5($user['s']), 0, 16);
			$vfreebusy->ORGANIZER = 'mailto:' . $user['s'];

			$dtstart = VObject\Property::create('DTSTART');
			$dtstart->setDateTime(Utils::periodStartDT(), VObject\Property\DateTime::UTC);
			$vfreebusy->add($dtstart);

			$dtend = VObject\Property::create('DTEND');
			$dtend->setDateTime(Utils::periodEndDT(), VObject\Property\DateTime::UTC);
			$vfreebusy->add($dtend);

			$dtstamp = VObject\Property::create('DTSTAMP');
			$dtstamp->setDateTime(new \DateTime('now'), VObject\Property\DateTime::UTC);
			$vfreebusy->add($dtstamp);

			$calendar->add($vfreebusy);

			// add aggregated busy periods
			foreach ($this->aggregatedBusyTimes($busy_times) as $busy) {
				$busy[0]->setTimeZone(new \DateTimeZone('UTC'));
				$busy[1]->setTimeZone(new \DateTimeZone('UTC'));

				$prop = VObject\Property::create(
					'FREEBUSY',
					$busy[0]->format('Ymd\\THis\\Z') . '/' . $busy[1]->format('Ymd\\THis\\Z')
				);
				$prop['FBTYPE'] = $busy[2];
				$vfreebusy->add($prop);
			}

			// serialize to VCALENDAR format
			return $calendar->serialize();
		}

		return null;
	}

	/**
	 * Compose a full url from the given config (previously extracted with parse_url())
	 */
	private function getDataFor($subject)
	{
		$conf = Config::get_instance();
		$log = Logger::get('aggregate', intval($this->config['loglevel']));

		$directories = $this->config['directories'] ?
			Config::arr($this->config['directories']) :
			array_keys($config->directory);

		$log->addDebug('Fetch data for ' . $subject . ' in direcotories', $directories);

		// iterate over directories
		// same as in public_html/index.php
		foreach ($directories as $key) {
			if ($dirconfig = $conf->directory[$key]) {
				$log->addDebug("Trying directory $key", $dirconfig);

				$directory = Directory::factory($dirconfig);
				if ($directory && ($fbdata = $directory->getFreeBusyData($subject, false))) {
					$log->addInfo("Found valid data for subject $subject in directory $key");
					return $fbdata;
				}
			}
		}

		return null;
	}
	
	/**
	 * Compare overlapping times and only keep those busy by ALL members
	 */
	private function aggregatedBusyTimes($busy_times)
	{
		$result = array();

		// 1. sort member busy times by the number of entries
		usort($busy_times, function($a, $b) { return count($a) - count($b); });

		// 2. compare busy slots from the first member with all the others.
		// a time slot it only considered busy (for the entire collection) if ALL members are busy.
		$member_times = array_shift($busy_times);

		// if the collection only has one member, that one rules
		if (!count($busy_times)) {
			return $member_times;
		}

		foreach ($member_times as $busy_candidate) {
			$start = $busy_candidate[0];
			$end   = $busy_candidate[1];
			$type  = $busy_candidate[2];

			foreach ($busy_times as $other_member_times) {
				$members_is_busy = false;
				foreach ($other_member_times as $busy_time) {
					// check for overlap with current candidate
					if ($busy_time[1] > $start && $busy_time[0] < $end) {
						$members_is_busy = true;

						// reduce candidate to the overlapping range
						if ($busy_time[0] > $start) {
							$start = $busy_time[0];
						}
						if ($busy_time[1] < $end) {
							$end = $busy_time[1];
						}
						if ($busy_time[2] == 'BUSY') {
							$type = $busy_time[2];
						}
					}
				}

				// skip this candidate if one of the member is not busy
				if (!$members_is_busy) {
					continue 2;
				}
			}
			
			// if we end up here, the slot if busy for all members: add to result
			if ($start < $end) {
				$result[] = array($start, $end, $type);
			}
		}

		return $result;
	}
}