Completed
Pull Request — master (#5881)
by Georg
17:44
created
apps/dav/lib/Command/MoveCalendar.php 1 patch
Indentation   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -35,128 +35,128 @@
 block discarded – undo
35 35
 
36 36
 class MoveCalendar extends Command {
37 37
 
38
-	/** @var IUserManager */
39
-	protected $userManager;
40
-
41
-	/** @var IGroupManager $groupManager */
42
-	private $groupManager;
43
-
44
-	/** @var \OCP\IDBConnection */
45
-	protected $dbConnection;
46
-
47
-	/** @var IL10N */
48
-	protected $l10n;
49
-
50
-	/** @var SymfonyStyle */
51
-	private $io;
52
-
53
-	/** @var CalDavBackend */
54
-	private $caldav;
55
-
56
-	const URI_USERS = 'principals/users/';
57
-
58
-	/**
59
-	 * @param IUserManager $userManager
60
-	 * @param IGroupManager $groupManager
61
-	 * @param IDBConnection $dbConnection
62
-	 * @param IL10N $l10n
63
-	 */
64
-	function __construct(IUserManager $userManager, IGroupManager $groupManager, IDBConnection $dbConnection, IL10N $l10n) {
65
-		parent::__construct();
66
-		$this->userManager = $userManager;
67
-		$this->groupManager = $groupManager;
68
-		$this->dbConnection = $dbConnection;
69
-		$this->l10n = $l10n;
70
-	}
71
-
72
-	protected function configure() {
73
-		$this
74
-			->setName('dav:move-calendar')
75
-			->setDescription('Move a calendar from an user to another')
76
-			->addArgument('name',
77
-				InputArgument::REQUIRED,
78
-				'Name of the calendar to move')
79
-			->addArgument('userorigin',
80
-				InputArgument::REQUIRED,
81
-				'User who currently owns the calendar')
82
-			->addArgument('userdestination',
83
-				InputArgument::REQUIRED,
84
-				'User who will receive the calendar')
85
-			->addOption('force', 'f', InputOption::VALUE_NONE, "Force the migration by removing shares with groups that the destination user is not in");
86
-	}
87
-
88
-	protected function execute(InputInterface $input, OutputInterface $output) {
89
-		$userOrigin = $input->getArgument('userorigin');
90
-		$userDestination = $input->getArgument('userdestination');
91
-
92
-		$this->io = new SymfonyStyle($input, $output);
93
-
94
-		if (in_array('system', [$userOrigin, $userDestination], true)) {
95
-			throw new \InvalidArgumentException("User can't be system");
96
-		}
97
-
98
-		if (!$this->userManager->userExists($userOrigin)) {
99
-			throw new \InvalidArgumentException("User <$userOrigin> is unknown.");
100
-		}
101
-
102
-
103
-		if (!$this->userManager->userExists($userDestination)) {
104
-			throw new \InvalidArgumentException("User <$userDestination> is unknown.");
105
-		}
106
-
107
-		$principalBackend = new Principal(
108
-			$this->userManager,
109
-			$this->groupManager
110
-		);
111
-		$random = \OC::$server->getSecureRandom();
112
-		$dispatcher = \OC::$server->getEventDispatcher();
113
-
114
-		$name = $input->getArgument('name');
115
-		$this->caldav = new CalDavBackend($this->dbConnection, $principalBackend, $this->userManager, $random, $dispatcher);
116
-
117
-		$calendar = $this->caldav->getCalendarByUri(self::URI_USERS . $userOrigin, $name);
118
-
119
-		if (null === $calendar) {
120
-			/**  If we got no matching calendar with URI, let's try the display names */
121
-			$suggestedUris = $this->caldav->findCalendarsUrisByDisplayName($name, self::URI_USERS . $userOrigin);
122
-			if (count($suggestedUris) > 0) {
123
-				$this->io->note('No calendar with this URI was found, but you may want to try with these?');
124
-				$this->io->listing($suggestedUris);
125
-			}
126
-			throw new \InvalidArgumentException("User <$userOrigin> has no calendar named <$name>.");
127
-		}
128
-
129
-		if (null !== $this->caldav->getCalendarByUri(self::URI_USERS . $userDestination, $name)) {
130
-			throw new \InvalidArgumentException("User <$userDestination> already has a calendar named <$name>.");
131
-		}
132
-
133
-		$this->checkShares($calendar, $userDestination, $input->getOption('force'));
134
-
135
-		$this->caldav->moveCalendar($name, self::URI_USERS . $userOrigin, self::URI_USERS . $userDestination);
136
-
137
-		$this->io->success("Calendar <$name> was moved from user <$userOrigin> to <$userDestination>");
138
-	}
139
-
140
-	/**
141
-	 * Check that user destination is member of the groups which whom the calendar was shared
142
-	 * If we ask to force the migration, the share with the group is dropped
143
-	 *
144
-	 * @param $calendar
145
-	 * @param $userDestination
146
-	 * @param bool $force
147
-	 */
148
-	private function checkShares($calendar, $userDestination, $force = false)
149
-	{
150
-		$shares = $this->caldav->getShares($calendar['id']);
151
-		foreach ($shares as $share) {
152
-			list($prefix, $group) = str_split($share['href'], 28);
153
-			if ('principal:principals/groups/' === $prefix && !$this->groupManager->isInGroup($userDestination, $group)) {
154
-				if ($force) {
155
-					$this->caldav->updateShares(new Calendar($this->caldav, $calendar, $this->l10n), [], ['href' => 'principal:principals/groups/' . $group]);
156
-				} else {
157
-					throw new \InvalidArgumentException("User <$userDestination> is not part of the group <$group> with which the calendar <" . $calendar['uri'] . "> was shared. You may use -f to move the calendar while deleting this share.");
158
-				}
159
-			}
160
-		}
161
-	}
38
+    /** @var IUserManager */
39
+    protected $userManager;
40
+
41
+    /** @var IGroupManager $groupManager */
42
+    private $groupManager;
43
+
44
+    /** @var \OCP\IDBConnection */
45
+    protected $dbConnection;
46
+
47
+    /** @var IL10N */
48
+    protected $l10n;
49
+
50
+    /** @var SymfonyStyle */
51
+    private $io;
52
+
53
+    /** @var CalDavBackend */
54
+    private $caldav;
55
+
56
+    const URI_USERS = 'principals/users/';
57
+
58
+    /**
59
+     * @param IUserManager $userManager
60
+     * @param IGroupManager $groupManager
61
+     * @param IDBConnection $dbConnection
62
+     * @param IL10N $l10n
63
+     */
64
+    function __construct(IUserManager $userManager, IGroupManager $groupManager, IDBConnection $dbConnection, IL10N $l10n) {
65
+        parent::__construct();
66
+        $this->userManager = $userManager;
67
+        $this->groupManager = $groupManager;
68
+        $this->dbConnection = $dbConnection;
69
+        $this->l10n = $l10n;
70
+    }
71
+
72
+    protected function configure() {
73
+        $this
74
+            ->setName('dav:move-calendar')
75
+            ->setDescription('Move a calendar from an user to another')
76
+            ->addArgument('name',
77
+                InputArgument::REQUIRED,
78
+                'Name of the calendar to move')
79
+            ->addArgument('userorigin',
80
+                InputArgument::REQUIRED,
81
+                'User who currently owns the calendar')
82
+            ->addArgument('userdestination',
83
+                InputArgument::REQUIRED,
84
+                'User who will receive the calendar')
85
+            ->addOption('force', 'f', InputOption::VALUE_NONE, "Force the migration by removing shares with groups that the destination user is not in");
86
+    }
87
+
88
+    protected function execute(InputInterface $input, OutputInterface $output) {
89
+        $userOrigin = $input->getArgument('userorigin');
90
+        $userDestination = $input->getArgument('userdestination');
91
+
92
+        $this->io = new SymfonyStyle($input, $output);
93
+
94
+        if (in_array('system', [$userOrigin, $userDestination], true)) {
95
+            throw new \InvalidArgumentException("User can't be system");
96
+        }
97
+
98
+        if (!$this->userManager->userExists($userOrigin)) {
99
+            throw new \InvalidArgumentException("User <$userOrigin> is unknown.");
100
+        }
101
+
102
+
103
+        if (!$this->userManager->userExists($userDestination)) {
104
+            throw new \InvalidArgumentException("User <$userDestination> is unknown.");
105
+        }
106
+
107
+        $principalBackend = new Principal(
108
+            $this->userManager,
109
+            $this->groupManager
110
+        );
111
+        $random = \OC::$server->getSecureRandom();
112
+        $dispatcher = \OC::$server->getEventDispatcher();
113
+
114
+        $name = $input->getArgument('name');
115
+        $this->caldav = new CalDavBackend($this->dbConnection, $principalBackend, $this->userManager, $random, $dispatcher);
116
+
117
+        $calendar = $this->caldav->getCalendarByUri(self::URI_USERS . $userOrigin, $name);
118
+
119
+        if (null === $calendar) {
120
+            /**  If we got no matching calendar with URI, let's try the display names */
121
+            $suggestedUris = $this->caldav->findCalendarsUrisByDisplayName($name, self::URI_USERS . $userOrigin);
122
+            if (count($suggestedUris) > 0) {
123
+                $this->io->note('No calendar with this URI was found, but you may want to try with these?');
124
+                $this->io->listing($suggestedUris);
125
+            }
126
+            throw new \InvalidArgumentException("User <$userOrigin> has no calendar named <$name>.");
127
+        }
128
+
129
+        if (null !== $this->caldav->getCalendarByUri(self::URI_USERS . $userDestination, $name)) {
130
+            throw new \InvalidArgumentException("User <$userDestination> already has a calendar named <$name>.");
131
+        }
132
+
133
+        $this->checkShares($calendar, $userDestination, $input->getOption('force'));
134
+
135
+        $this->caldav->moveCalendar($name, self::URI_USERS . $userOrigin, self::URI_USERS . $userDestination);
136
+
137
+        $this->io->success("Calendar <$name> was moved from user <$userOrigin> to <$userDestination>");
138
+    }
139
+
140
+    /**
141
+     * Check that user destination is member of the groups which whom the calendar was shared
142
+     * If we ask to force the migration, the share with the group is dropped
143
+     *
144
+     * @param $calendar
145
+     * @param $userDestination
146
+     * @param bool $force
147
+     */
148
+    private function checkShares($calendar, $userDestination, $force = false)
149
+    {
150
+        $shares = $this->caldav->getShares($calendar['id']);
151
+        foreach ($shares as $share) {
152
+            list($prefix, $group) = str_split($share['href'], 28);
153
+            if ('principal:principals/groups/' === $prefix && !$this->groupManager->isInGroup($userDestination, $group)) {
154
+                if ($force) {
155
+                    $this->caldav->updateShares(new Calendar($this->caldav, $calendar, $this->l10n), [], ['href' => 'principal:principals/groups/' . $group]);
156
+                } else {
157
+                    throw new \InvalidArgumentException("User <$userDestination> is not part of the group <$group> with which the calendar <" . $calendar['uri'] . "> was shared. You may use -f to move the calendar while deleting this share.");
158
+                }
159
+            }
160
+        }
161
+    }
162 162
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 1 patch
Indentation   +2340 added lines, -2340 removed lines patch added patch discarded remove patch
@@ -73,2345 +73,2345 @@
 block discarded – undo
73 73
  */
74 74
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
75 75
 
76
-	const PERSONAL_CALENDAR_URI = 'personal';
77
-	const PERSONAL_CALENDAR_NAME = 'Personal';
78
-
79
-	/**
80
-	 * We need to specify a max date, because we need to stop *somewhere*
81
-	 *
82
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
83
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
84
-	 * in 2038-01-19 to avoid problems when the date is converted
85
-	 * to a unix timestamp.
86
-	 */
87
-	const MAX_DATE = '2038-01-01';
88
-
89
-	const ACCESS_PUBLIC = 4;
90
-	const CLASSIFICATION_PUBLIC = 0;
91
-	const CLASSIFICATION_PRIVATE = 1;
92
-	const CLASSIFICATION_CONFIDENTIAL = 2;
93
-
94
-	/**
95
-	 * List of CalDAV properties, and how they map to database field names
96
-	 * Add your own properties by simply adding on to this array.
97
-	 *
98
-	 * Note that only string-based properties are supported here.
99
-	 *
100
-	 * @var array
101
-	 */
102
-	public $propertyMap = [
103
-		'{DAV:}displayname'                          => 'displayname',
104
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
105
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
106
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
107
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
108
-	];
109
-
110
-	/**
111
-	 * List of subscription properties, and how they map to database field names.
112
-	 *
113
-	 * @var array
114
-	 */
115
-	public $subscriptionPropertyMap = [
116
-		'{DAV:}displayname'                                           => 'displayname',
117
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
118
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
119
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
120
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
121
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
122
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
123
-	];
124
-
125
-	/** @var array properties to index */
126
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
127
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
128
-		'ORGANIZER'];
129
-
130
-	/** @var array parameters to index */
131
-	public static $indexParameters = [
132
-		'ATTENDEE' => ['CN'],
133
-		'ORGANIZER' => ['CN'],
134
-	];
135
-
136
-	/**
137
-	 * @var string[] Map of uid => display name
138
-	 */
139
-	protected $userDisplayNames;
140
-
141
-	/** @var IDBConnection */
142
-	private $db;
143
-
144
-	/** @var Backend */
145
-	private $sharingBackend;
146
-
147
-	/** @var Principal */
148
-	private $principalBackend;
149
-
150
-	/** @var IUserManager */
151
-	private $userManager;
152
-
153
-	/** @var ISecureRandom */
154
-	private $random;
155
-
156
-	/** @var ILogger */
157
-	private $logger;
158
-
159
-	/** @var EventDispatcherInterface */
160
-	private $dispatcher;
161
-
162
-	/** @var bool */
163
-	private $legacyEndpoint;
164
-
165
-	/** @var string */
166
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
167
-
168
-	/**
169
-	 * CalDavBackend constructor.
170
-	 *
171
-	 * @param IDBConnection $db
172
-	 * @param Principal $principalBackend
173
-	 * @param IUserManager $userManager
174
-	 * @param IGroupManager $groupManager
175
-	 * @param ISecureRandom $random
176
-	 * @param ILogger $logger
177
-	 * @param EventDispatcherInterface $dispatcher
178
-	 * @param bool $legacyEndpoint
179
-	 */
180
-	public function __construct(IDBConnection $db,
181
-								Principal $principalBackend,
182
-								IUserManager $userManager,
183
-								IGroupManager $groupManager,
184
-								ISecureRandom $random,
185
-								ILogger $logger,
186
-								EventDispatcherInterface $dispatcher,
187
-								$legacyEndpoint = false) {
188
-		$this->db = $db;
189
-		$this->principalBackend = $principalBackend;
190
-		$this->userManager = $userManager;
191
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
192
-		$this->random = $random;
193
-		$this->logger = $logger;
194
-		$this->dispatcher = $dispatcher;
195
-		$this->legacyEndpoint = $legacyEndpoint;
196
-	}
197
-
198
-	/**
199
-	 * Return the number of calendars for a principal
200
-	 *
201
-	 * By default this excludes the automatically generated birthday calendar
202
-	 *
203
-	 * @param $principalUri
204
-	 * @param bool $excludeBirthday
205
-	 * @return int
206
-	 */
207
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
208
-		$principalUri = $this->convertPrincipal($principalUri, true);
209
-		$query = $this->db->getQueryBuilder();
210
-		$query->select($query->createFunction('COUNT(*)'))
211
-			->from('calendars')
212
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
213
-
214
-		if ($excludeBirthday) {
215
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
216
-		}
217
-
218
-		return (int)$query->execute()->fetchColumn();
219
-	}
220
-
221
-	/**
222
-	 * Returns a list of calendars for a principal.
223
-	 *
224
-	 * Every project is an array with the following keys:
225
-	 *  * id, a unique id that will be used by other functions to modify the
226
-	 *    calendar. This can be the same as the uri or a database key.
227
-	 *  * uri, which the basename of the uri with which the calendar is
228
-	 *    accessed.
229
-	 *  * principaluri. The owner of the calendar. Almost always the same as
230
-	 *    principalUri passed to this method.
231
-	 *
232
-	 * Furthermore it can contain webdav properties in clark notation. A very
233
-	 * common one is '{DAV:}displayname'.
234
-	 *
235
-	 * Many clients also require:
236
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
237
-	 * For this property, you can just return an instance of
238
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
239
-	 *
240
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
241
-	 * ACL will automatically be put in read-only mode.
242
-	 *
243
-	 * @param string $principalUri
244
-	 * @return array
245
-	 */
246
-	function getCalendarsForUser($principalUri) {
247
-		$principalUriOriginal = $principalUri;
248
-		$principalUri = $this->convertPrincipal($principalUri, true);
249
-		$fields = array_values($this->propertyMap);
250
-		$fields[] = 'id';
251
-		$fields[] = 'uri';
252
-		$fields[] = 'synctoken';
253
-		$fields[] = 'components';
254
-		$fields[] = 'principaluri';
255
-		$fields[] = 'transparent';
256
-
257
-		// Making fields a comma-delimited list
258
-		$query = $this->db->getQueryBuilder();
259
-		$query->select($fields)->from('calendars')
260
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
261
-				->orderBy('calendarorder', 'ASC');
262
-		$stmt = $query->execute();
263
-
264
-		$calendars = [];
265
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
266
-
267
-			$components = [];
268
-			if ($row['components']) {
269
-				$components = explode(',',$row['components']);
270
-			}
271
-
272
-			$calendar = [
273
-				'id' => $row['id'],
274
-				'uri' => $row['uri'],
275
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
276
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
277
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
278
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
279
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
280
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
281
-			];
282
-
283
-			foreach($this->propertyMap as $xmlName=>$dbName) {
284
-				$calendar[$xmlName] = $row[$dbName];
285
-			}
286
-
287
-			$this->addOwnerPrincipal($calendar);
288
-
289
-			if (!isset($calendars[$calendar['id']])) {
290
-				$calendars[$calendar['id']] = $calendar;
291
-			}
292
-		}
293
-
294
-		$stmt->closeCursor();
295
-
296
-		// query for shared calendars
297
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
298
-		$principals = array_map(function($principal) {
299
-			return urldecode($principal);
300
-		}, $principals);
301
-		$principals[]= $principalUri;
302
-
303
-		$fields = array_values($this->propertyMap);
304
-		$fields[] = 'a.id';
305
-		$fields[] = 'a.uri';
306
-		$fields[] = 'a.synctoken';
307
-		$fields[] = 'a.components';
308
-		$fields[] = 'a.principaluri';
309
-		$fields[] = 'a.transparent';
310
-		$fields[] = 's.access';
311
-		$query = $this->db->getQueryBuilder();
312
-		$result = $query->select($fields)
313
-			->from('dav_shares', 's')
314
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
315
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
316
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
317
-			->setParameter('type', 'calendar')
318
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
319
-			->execute();
320
-
321
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
322
-		while($row = $result->fetch()) {
323
-			if ($row['principaluri'] === $principalUri) {
324
-				continue;
325
-			}
326
-
327
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
328
-			if (isset($calendars[$row['id']])) {
329
-				if ($readOnly) {
330
-					// New share can not have more permissions then the old one.
331
-					continue;
332
-				}
333
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
334
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
335
-					// Old share is already read-write, no more permissions can be gained
336
-					continue;
337
-				}
338
-			}
339
-
340
-			list(, $name) = Uri\split($row['principaluri']);
341
-			$uri = $row['uri'] . '_shared_by_' . $name;
342
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
343
-			$components = [];
344
-			if ($row['components']) {
345
-				$components = explode(',',$row['components']);
346
-			}
347
-			$calendar = [
348
-				'id' => $row['id'],
349
-				'uri' => $uri,
350
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
351
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
352
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
353
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
354
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
355
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
356
-				$readOnlyPropertyName => $readOnly,
357
-			];
358
-
359
-			foreach($this->propertyMap as $xmlName=>$dbName) {
360
-				$calendar[$xmlName] = $row[$dbName];
361
-			}
362
-
363
-			$this->addOwnerPrincipal($calendar);
364
-
365
-			$calendars[$calendar['id']] = $calendar;
366
-		}
367
-		$result->closeCursor();
368
-
369
-		return array_values($calendars);
370
-	}
371
-
372
-	public function getUsersOwnCalendars($principalUri) {
373
-		$principalUri = $this->convertPrincipal($principalUri, true);
374
-		$fields = array_values($this->propertyMap);
375
-		$fields[] = 'id';
376
-		$fields[] = 'uri';
377
-		$fields[] = 'synctoken';
378
-		$fields[] = 'components';
379
-		$fields[] = 'principaluri';
380
-		$fields[] = 'transparent';
381
-		// Making fields a comma-delimited list
382
-		$query = $this->db->getQueryBuilder();
383
-		$query->select($fields)->from('calendars')
384
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
385
-			->orderBy('calendarorder', 'ASC');
386
-		$stmt = $query->execute();
387
-		$calendars = [];
388
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
389
-			$components = [];
390
-			if ($row['components']) {
391
-				$components = explode(',',$row['components']);
392
-			}
393
-			$calendar = [
394
-				'id' => $row['id'],
395
-				'uri' => $row['uri'],
396
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
397
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
398
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
399
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
400
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
401
-			];
402
-			foreach($this->propertyMap as $xmlName=>$dbName) {
403
-				$calendar[$xmlName] = $row[$dbName];
404
-			}
405
-
406
-			$this->addOwnerPrincipal($calendar);
407
-
408
-			if (!isset($calendars[$calendar['id']])) {
409
-				$calendars[$calendar['id']] = $calendar;
410
-			}
411
-		}
412
-		$stmt->closeCursor();
413
-		return array_values($calendars);
414
-	}
415
-
416
-
417
-	private function getUserDisplayName($uid) {
418
-		if (!isset($this->userDisplayNames[$uid])) {
419
-			$user = $this->userManager->get($uid);
420
-
421
-			if ($user instanceof IUser) {
422
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
423
-			} else {
424
-				$this->userDisplayNames[$uid] = $uid;
425
-			}
426
-		}
427
-
428
-		return $this->userDisplayNames[$uid];
429
-	}
76
+    const PERSONAL_CALENDAR_URI = 'personal';
77
+    const PERSONAL_CALENDAR_NAME = 'Personal';
78
+
79
+    /**
80
+     * We need to specify a max date, because we need to stop *somewhere*
81
+     *
82
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
83
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
84
+     * in 2038-01-19 to avoid problems when the date is converted
85
+     * to a unix timestamp.
86
+     */
87
+    const MAX_DATE = '2038-01-01';
88
+
89
+    const ACCESS_PUBLIC = 4;
90
+    const CLASSIFICATION_PUBLIC = 0;
91
+    const CLASSIFICATION_PRIVATE = 1;
92
+    const CLASSIFICATION_CONFIDENTIAL = 2;
93
+
94
+    /**
95
+     * List of CalDAV properties, and how they map to database field names
96
+     * Add your own properties by simply adding on to this array.
97
+     *
98
+     * Note that only string-based properties are supported here.
99
+     *
100
+     * @var array
101
+     */
102
+    public $propertyMap = [
103
+        '{DAV:}displayname'                          => 'displayname',
104
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
105
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
106
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
107
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
108
+    ];
109
+
110
+    /**
111
+     * List of subscription properties, and how they map to database field names.
112
+     *
113
+     * @var array
114
+     */
115
+    public $subscriptionPropertyMap = [
116
+        '{DAV:}displayname'                                           => 'displayname',
117
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
118
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
119
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
120
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
121
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
122
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
123
+    ];
124
+
125
+    /** @var array properties to index */
126
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
127
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
128
+        'ORGANIZER'];
129
+
130
+    /** @var array parameters to index */
131
+    public static $indexParameters = [
132
+        'ATTENDEE' => ['CN'],
133
+        'ORGANIZER' => ['CN'],
134
+    ];
135
+
136
+    /**
137
+     * @var string[] Map of uid => display name
138
+     */
139
+    protected $userDisplayNames;
140
+
141
+    /** @var IDBConnection */
142
+    private $db;
143
+
144
+    /** @var Backend */
145
+    private $sharingBackend;
146
+
147
+    /** @var Principal */
148
+    private $principalBackend;
149
+
150
+    /** @var IUserManager */
151
+    private $userManager;
152
+
153
+    /** @var ISecureRandom */
154
+    private $random;
155
+
156
+    /** @var ILogger */
157
+    private $logger;
158
+
159
+    /** @var EventDispatcherInterface */
160
+    private $dispatcher;
161
+
162
+    /** @var bool */
163
+    private $legacyEndpoint;
164
+
165
+    /** @var string */
166
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
167
+
168
+    /**
169
+     * CalDavBackend constructor.
170
+     *
171
+     * @param IDBConnection $db
172
+     * @param Principal $principalBackend
173
+     * @param IUserManager $userManager
174
+     * @param IGroupManager $groupManager
175
+     * @param ISecureRandom $random
176
+     * @param ILogger $logger
177
+     * @param EventDispatcherInterface $dispatcher
178
+     * @param bool $legacyEndpoint
179
+     */
180
+    public function __construct(IDBConnection $db,
181
+                                Principal $principalBackend,
182
+                                IUserManager $userManager,
183
+                                IGroupManager $groupManager,
184
+                                ISecureRandom $random,
185
+                                ILogger $logger,
186
+                                EventDispatcherInterface $dispatcher,
187
+                                $legacyEndpoint = false) {
188
+        $this->db = $db;
189
+        $this->principalBackend = $principalBackend;
190
+        $this->userManager = $userManager;
191
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
192
+        $this->random = $random;
193
+        $this->logger = $logger;
194
+        $this->dispatcher = $dispatcher;
195
+        $this->legacyEndpoint = $legacyEndpoint;
196
+    }
197
+
198
+    /**
199
+     * Return the number of calendars for a principal
200
+     *
201
+     * By default this excludes the automatically generated birthday calendar
202
+     *
203
+     * @param $principalUri
204
+     * @param bool $excludeBirthday
205
+     * @return int
206
+     */
207
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
208
+        $principalUri = $this->convertPrincipal($principalUri, true);
209
+        $query = $this->db->getQueryBuilder();
210
+        $query->select($query->createFunction('COUNT(*)'))
211
+            ->from('calendars')
212
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
213
+
214
+        if ($excludeBirthday) {
215
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
216
+        }
217
+
218
+        return (int)$query->execute()->fetchColumn();
219
+    }
220
+
221
+    /**
222
+     * Returns a list of calendars for a principal.
223
+     *
224
+     * Every project is an array with the following keys:
225
+     *  * id, a unique id that will be used by other functions to modify the
226
+     *    calendar. This can be the same as the uri or a database key.
227
+     *  * uri, which the basename of the uri with which the calendar is
228
+     *    accessed.
229
+     *  * principaluri. The owner of the calendar. Almost always the same as
230
+     *    principalUri passed to this method.
231
+     *
232
+     * Furthermore it can contain webdav properties in clark notation. A very
233
+     * common one is '{DAV:}displayname'.
234
+     *
235
+     * Many clients also require:
236
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
237
+     * For this property, you can just return an instance of
238
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
239
+     *
240
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
241
+     * ACL will automatically be put in read-only mode.
242
+     *
243
+     * @param string $principalUri
244
+     * @return array
245
+     */
246
+    function getCalendarsForUser($principalUri) {
247
+        $principalUriOriginal = $principalUri;
248
+        $principalUri = $this->convertPrincipal($principalUri, true);
249
+        $fields = array_values($this->propertyMap);
250
+        $fields[] = 'id';
251
+        $fields[] = 'uri';
252
+        $fields[] = 'synctoken';
253
+        $fields[] = 'components';
254
+        $fields[] = 'principaluri';
255
+        $fields[] = 'transparent';
256
+
257
+        // Making fields a comma-delimited list
258
+        $query = $this->db->getQueryBuilder();
259
+        $query->select($fields)->from('calendars')
260
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
261
+                ->orderBy('calendarorder', 'ASC');
262
+        $stmt = $query->execute();
263
+
264
+        $calendars = [];
265
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
266
+
267
+            $components = [];
268
+            if ($row['components']) {
269
+                $components = explode(',',$row['components']);
270
+            }
271
+
272
+            $calendar = [
273
+                'id' => $row['id'],
274
+                'uri' => $row['uri'],
275
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
276
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
277
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
278
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
279
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
280
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
281
+            ];
282
+
283
+            foreach($this->propertyMap as $xmlName=>$dbName) {
284
+                $calendar[$xmlName] = $row[$dbName];
285
+            }
286
+
287
+            $this->addOwnerPrincipal($calendar);
288
+
289
+            if (!isset($calendars[$calendar['id']])) {
290
+                $calendars[$calendar['id']] = $calendar;
291
+            }
292
+        }
293
+
294
+        $stmt->closeCursor();
295
+
296
+        // query for shared calendars
297
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
298
+        $principals = array_map(function($principal) {
299
+            return urldecode($principal);
300
+        }, $principals);
301
+        $principals[]= $principalUri;
302
+
303
+        $fields = array_values($this->propertyMap);
304
+        $fields[] = 'a.id';
305
+        $fields[] = 'a.uri';
306
+        $fields[] = 'a.synctoken';
307
+        $fields[] = 'a.components';
308
+        $fields[] = 'a.principaluri';
309
+        $fields[] = 'a.transparent';
310
+        $fields[] = 's.access';
311
+        $query = $this->db->getQueryBuilder();
312
+        $result = $query->select($fields)
313
+            ->from('dav_shares', 's')
314
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
315
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
316
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
317
+            ->setParameter('type', 'calendar')
318
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
319
+            ->execute();
320
+
321
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
322
+        while($row = $result->fetch()) {
323
+            if ($row['principaluri'] === $principalUri) {
324
+                continue;
325
+            }
326
+
327
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
328
+            if (isset($calendars[$row['id']])) {
329
+                if ($readOnly) {
330
+                    // New share can not have more permissions then the old one.
331
+                    continue;
332
+                }
333
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
334
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
335
+                    // Old share is already read-write, no more permissions can be gained
336
+                    continue;
337
+                }
338
+            }
339
+
340
+            list(, $name) = Uri\split($row['principaluri']);
341
+            $uri = $row['uri'] . '_shared_by_' . $name;
342
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
343
+            $components = [];
344
+            if ($row['components']) {
345
+                $components = explode(',',$row['components']);
346
+            }
347
+            $calendar = [
348
+                'id' => $row['id'],
349
+                'uri' => $uri,
350
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
351
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
352
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
353
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
354
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
355
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
356
+                $readOnlyPropertyName => $readOnly,
357
+            ];
358
+
359
+            foreach($this->propertyMap as $xmlName=>$dbName) {
360
+                $calendar[$xmlName] = $row[$dbName];
361
+            }
362
+
363
+            $this->addOwnerPrincipal($calendar);
364
+
365
+            $calendars[$calendar['id']] = $calendar;
366
+        }
367
+        $result->closeCursor();
368
+
369
+        return array_values($calendars);
370
+    }
371
+
372
+    public function getUsersOwnCalendars($principalUri) {
373
+        $principalUri = $this->convertPrincipal($principalUri, true);
374
+        $fields = array_values($this->propertyMap);
375
+        $fields[] = 'id';
376
+        $fields[] = 'uri';
377
+        $fields[] = 'synctoken';
378
+        $fields[] = 'components';
379
+        $fields[] = 'principaluri';
380
+        $fields[] = 'transparent';
381
+        // Making fields a comma-delimited list
382
+        $query = $this->db->getQueryBuilder();
383
+        $query->select($fields)->from('calendars')
384
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
385
+            ->orderBy('calendarorder', 'ASC');
386
+        $stmt = $query->execute();
387
+        $calendars = [];
388
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
389
+            $components = [];
390
+            if ($row['components']) {
391
+                $components = explode(',',$row['components']);
392
+            }
393
+            $calendar = [
394
+                'id' => $row['id'],
395
+                'uri' => $row['uri'],
396
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
397
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
398
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
399
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
400
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
401
+            ];
402
+            foreach($this->propertyMap as $xmlName=>$dbName) {
403
+                $calendar[$xmlName] = $row[$dbName];
404
+            }
405
+
406
+            $this->addOwnerPrincipal($calendar);
407
+
408
+            if (!isset($calendars[$calendar['id']])) {
409
+                $calendars[$calendar['id']] = $calendar;
410
+            }
411
+        }
412
+        $stmt->closeCursor();
413
+        return array_values($calendars);
414
+    }
415
+
416
+
417
+    private function getUserDisplayName($uid) {
418
+        if (!isset($this->userDisplayNames[$uid])) {
419
+            $user = $this->userManager->get($uid);
420
+
421
+            if ($user instanceof IUser) {
422
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
423
+            } else {
424
+                $this->userDisplayNames[$uid] = $uid;
425
+            }
426
+        }
427
+
428
+        return $this->userDisplayNames[$uid];
429
+    }
430 430
 	
431
-	/**
432
-	 * @return array
433
-	 */
434
-	public function getPublicCalendars() {
435
-		$fields = array_values($this->propertyMap);
436
-		$fields[] = 'a.id';
437
-		$fields[] = 'a.uri';
438
-		$fields[] = 'a.synctoken';
439
-		$fields[] = 'a.components';
440
-		$fields[] = 'a.principaluri';
441
-		$fields[] = 'a.transparent';
442
-		$fields[] = 's.access';
443
-		$fields[] = 's.publicuri';
444
-		$calendars = [];
445
-		$query = $this->db->getQueryBuilder();
446
-		$result = $query->select($fields)
447
-			->from('dav_shares', 's')
448
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
449
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
450
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
451
-			->execute();
452
-
453
-		while($row = $result->fetch()) {
454
-			list(, $name) = Uri\split($row['principaluri']);
455
-			$row['displayname'] = $row['displayname'] . "($name)";
456
-			$components = [];
457
-			if ($row['components']) {
458
-				$components = explode(',',$row['components']);
459
-			}
460
-			$calendar = [
461
-				'id' => $row['id'],
462
-				'uri' => $row['publicuri'],
463
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
464
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
465
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
466
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
467
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
468
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
469
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
470
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
471
-			];
472
-
473
-			foreach($this->propertyMap as $xmlName=>$dbName) {
474
-				$calendar[$xmlName] = $row[$dbName];
475
-			}
476
-
477
-			$this->addOwnerPrincipal($calendar);
478
-
479
-			if (!isset($calendars[$calendar['id']])) {
480
-				$calendars[$calendar['id']] = $calendar;
481
-			}
482
-		}
483
-		$result->closeCursor();
484
-
485
-		return array_values($calendars);
486
-	}
487
-
488
-	/**
489
-	 * @param string $uri
490
-	 * @return array
491
-	 * @throws NotFound
492
-	 */
493
-	public function getPublicCalendar($uri) {
494
-		$fields = array_values($this->propertyMap);
495
-		$fields[] = 'a.id';
496
-		$fields[] = 'a.uri';
497
-		$fields[] = 'a.synctoken';
498
-		$fields[] = 'a.components';
499
-		$fields[] = 'a.principaluri';
500
-		$fields[] = 'a.transparent';
501
-		$fields[] = 's.access';
502
-		$fields[] = 's.publicuri';
503
-		$query = $this->db->getQueryBuilder();
504
-		$result = $query->select($fields)
505
-			->from('dav_shares', 's')
506
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
507
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
508
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
509
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
510
-			->execute();
511
-
512
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
513
-
514
-		$result->closeCursor();
515
-
516
-		if ($row === false) {
517
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
518
-		}
519
-
520
-		list(, $name) = Uri\split($row['principaluri']);
521
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
522
-		$components = [];
523
-		if ($row['components']) {
524
-			$components = explode(',',$row['components']);
525
-		}
526
-		$calendar = [
527
-			'id' => $row['id'],
528
-			'uri' => $row['publicuri'],
529
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
530
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
531
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
532
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
533
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
534
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
535
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
536
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
537
-		];
538
-
539
-		foreach($this->propertyMap as $xmlName=>$dbName) {
540
-			$calendar[$xmlName] = $row[$dbName];
541
-		}
542
-
543
-		$this->addOwnerPrincipal($calendar);
544
-
545
-		return $calendar;
546
-
547
-	}
548
-
549
-	/**
550
-	 * @param string $principal
551
-	 * @param string $uri
552
-	 * @return array|null
553
-	 */
554
-	public function getCalendarByUri($principal, $uri) {
555
-		$fields = array_values($this->propertyMap);
556
-		$fields[] = 'id';
557
-		$fields[] = 'uri';
558
-		$fields[] = 'synctoken';
559
-		$fields[] = 'components';
560
-		$fields[] = 'principaluri';
561
-		$fields[] = 'transparent';
562
-
563
-		// Making fields a comma-delimited list
564
-		$query = $this->db->getQueryBuilder();
565
-		$query->select($fields)->from('calendars')
566
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
567
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
568
-			->setMaxResults(1);
569
-		$stmt = $query->execute();
570
-
571
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
572
-		$stmt->closeCursor();
573
-		if ($row === false) {
574
-			return null;
575
-		}
576
-
577
-		$components = [];
578
-		if ($row['components']) {
579
-			$components = explode(',',$row['components']);
580
-		}
581
-
582
-		$calendar = [
583
-			'id' => $row['id'],
584
-			'uri' => $row['uri'],
585
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
586
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
587
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
588
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
589
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
590
-		];
591
-
592
-		foreach($this->propertyMap as $xmlName=>$dbName) {
593
-			$calendar[$xmlName] = $row[$dbName];
594
-		}
595
-
596
-		$this->addOwnerPrincipal($calendar);
597
-
598
-		return $calendar;
599
-	}
600
-
601
-	public function getCalendarById($calendarId) {
602
-		$fields = array_values($this->propertyMap);
603
-		$fields[] = 'id';
604
-		$fields[] = 'uri';
605
-		$fields[] = 'synctoken';
606
-		$fields[] = 'components';
607
-		$fields[] = 'principaluri';
608
-		$fields[] = 'transparent';
609
-
610
-		// Making fields a comma-delimited list
611
-		$query = $this->db->getQueryBuilder();
612
-		$query->select($fields)->from('calendars')
613
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
614
-			->setMaxResults(1);
615
-		$stmt = $query->execute();
616
-
617
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
618
-		$stmt->closeCursor();
619
-		if ($row === false) {
620
-			return null;
621
-		}
622
-
623
-		$components = [];
624
-		if ($row['components']) {
625
-			$components = explode(',',$row['components']);
626
-		}
627
-
628
-		$calendar = [
629
-			'id' => $row['id'],
630
-			'uri' => $row['uri'],
631
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
632
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
633
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
634
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
635
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
636
-		];
637
-
638
-		foreach($this->propertyMap as $xmlName=>$dbName) {
639
-			$calendar[$xmlName] = $row[$dbName];
640
-		}
641
-
642
-		$this->addOwnerPrincipal($calendar);
643
-
644
-		return $calendar;
645
-	}
646
-
647
-	/**
648
-	 * Creates a new calendar for a principal.
649
-	 *
650
-	 * If the creation was a success, an id must be returned that can be used to reference
651
-	 * this calendar in other methods, such as updateCalendar.
652
-	 *
653
-	 * @param string $principalUri
654
-	 * @param string $calendarUri
655
-	 * @param array $properties
656
-	 * @return int
657
-	 * @suppress SqlInjectionChecker
658
-	 */
659
-	function createCalendar($principalUri, $calendarUri, array $properties) {
660
-		$values = [
661
-			'principaluri' => $this->convertPrincipal($principalUri, true),
662
-			'uri'          => $calendarUri,
663
-			'synctoken'    => 1,
664
-			'transparent'  => 0,
665
-			'components'   => 'VEVENT,VTODO',
666
-			'displayname'  => $calendarUri
667
-		];
668
-
669
-		// Default value
670
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
671
-		if (isset($properties[$sccs])) {
672
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
673
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
674
-			}
675
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
676
-		}
677
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
678
-		if (isset($properties[$transp])) {
679
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
680
-		}
681
-
682
-		foreach($this->propertyMap as $xmlName=>$dbName) {
683
-			if (isset($properties[$xmlName])) {
684
-				$values[$dbName] = $properties[$xmlName];
685
-			}
686
-		}
687
-
688
-		$query = $this->db->getQueryBuilder();
689
-		$query->insert('calendars');
690
-		foreach($values as $column => $value) {
691
-			$query->setValue($column, $query->createNamedParameter($value));
692
-		}
693
-		$query->execute();
694
-		$calendarId = $query->getLastInsertId();
695
-
696
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
697
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
698
-			[
699
-				'calendarId' => $calendarId,
700
-				'calendarData' => $this->getCalendarById($calendarId),
701
-		]));
702
-
703
-		return $calendarId;
704
-	}
705
-
706
-	/**
707
-	 * Updates properties for a calendar.
708
-	 *
709
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
710
-	 * To do the actual updates, you must tell this object which properties
711
-	 * you're going to process with the handle() method.
712
-	 *
713
-	 * Calling the handle method is like telling the PropPatch object "I
714
-	 * promise I can handle updating this property".
715
-	 *
716
-	 * Read the PropPatch documentation for more info and examples.
717
-	 *
718
-	 * @param mixed $calendarId
719
-	 * @param PropPatch $propPatch
720
-	 * @return void
721
-	 */
722
-	function updateCalendar($calendarId, PropPatch $propPatch) {
723
-		$supportedProperties = array_keys($this->propertyMap);
724
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
725
-
726
-		/**
727
-		 * @suppress SqlInjectionChecker
728
-		 */
729
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
730
-			$newValues = [];
731
-			foreach ($mutations as $propertyName => $propertyValue) {
732
-
733
-				switch ($propertyName) {
734
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
735
-						$fieldName = 'transparent';
736
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
737
-						break;
738
-					default :
739
-						$fieldName = $this->propertyMap[$propertyName];
740
-						$newValues[$fieldName] = $propertyValue;
741
-						break;
742
-				}
743
-
744
-			}
745
-			$query = $this->db->getQueryBuilder();
746
-			$query->update('calendars');
747
-			foreach ($newValues as $fieldName => $value) {
748
-				$query->set($fieldName, $query->createNamedParameter($value));
749
-			}
750
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
751
-			$query->execute();
752
-
753
-			$this->addChange($calendarId, "", 2);
754
-
755
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
756
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
757
-				[
758
-					'calendarId' => $calendarId,
759
-					'calendarData' => $this->getCalendarById($calendarId),
760
-					'shares' => $this->getShares($calendarId),
761
-					'propertyMutations' => $mutations,
762
-			]));
763
-
764
-			return true;
765
-		});
766
-	}
767
-
768
-	/**
769
-	 * Delete a calendar and all it's objects
770
-	 *
771
-	 * @param mixed $calendarId
772
-	 * @return void
773
-	 */
774
-	function deleteCalendar($calendarId) {
775
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
776
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
777
-			[
778
-				'calendarId' => $calendarId,
779
-				'calendarData' => $this->getCalendarById($calendarId),
780
-				'shares' => $this->getShares($calendarId),
781
-		]));
782
-
783
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
784
-		$stmt->execute([$calendarId]);
785
-
786
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
787
-		$stmt->execute([$calendarId]);
788
-
789
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
790
-		$stmt->execute([$calendarId]);
791
-
792
-		$this->sharingBackend->deleteAllShares($calendarId);
793
-
794
-		$query = $this->db->getQueryBuilder();
795
-		$query->delete($this->dbObjectPropertiesTable)
796
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
797
-			->execute();
798
-	}
799
-
800
-	/**
801
-	 * Delete all of an user's shares
802
-	 *
803
-	 * @param string $principaluri
804
-	 * @return void
805
-	 */
806
-	function deleteAllSharesByUser($principaluri) {
807
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
808
-	}
809
-
810
-	/**
811
-	 * Returns all calendar objects within a calendar.
812
-	 *
813
-	 * Every item contains an array with the following keys:
814
-	 *   * calendardata - The iCalendar-compatible calendar data
815
-	 *   * uri - a unique key which will be used to construct the uri. This can
816
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
817
-	 *     good idea. This is only the basename, or filename, not the full
818
-	 *     path.
819
-	 *   * lastmodified - a timestamp of the last modification time
820
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
821
-	 *   '"abcdef"')
822
-	 *   * size - The size of the calendar objects, in bytes.
823
-	 *   * component - optional, a string containing the type of object, such
824
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
825
-	 *     the Content-Type header.
826
-	 *
827
-	 * Note that the etag is optional, but it's highly encouraged to return for
828
-	 * speed reasons.
829
-	 *
830
-	 * The calendardata is also optional. If it's not returned
831
-	 * 'getCalendarObject' will be called later, which *is* expected to return
832
-	 * calendardata.
833
-	 *
834
-	 * If neither etag or size are specified, the calendardata will be
835
-	 * used/fetched to determine these numbers. If both are specified the
836
-	 * amount of times this is needed is reduced by a great degree.
837
-	 *
838
-	 * @param mixed $calendarId
839
-	 * @return array
840
-	 */
841
-	function getCalendarObjects($calendarId) {
842
-		$query = $this->db->getQueryBuilder();
843
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
844
-			->from('calendarobjects')
845
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
846
-		$stmt = $query->execute();
847
-
848
-		$result = [];
849
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
850
-			$result[] = [
851
-					'id'           => $row['id'],
852
-					'uri'          => $row['uri'],
853
-					'lastmodified' => $row['lastmodified'],
854
-					'etag'         => '"' . $row['etag'] . '"',
855
-					'calendarid'   => $row['calendarid'],
856
-					'size'         => (int)$row['size'],
857
-					'component'    => strtolower($row['componenttype']),
858
-					'classification'=> (int)$row['classification']
859
-			];
860
-		}
861
-
862
-		return $result;
863
-	}
864
-
865
-	/**
866
-	 * Returns information from a single calendar object, based on it's object
867
-	 * uri.
868
-	 *
869
-	 * The object uri is only the basename, or filename and not a full path.
870
-	 *
871
-	 * The returned array must have the same keys as getCalendarObjects. The
872
-	 * 'calendardata' object is required here though, while it's not required
873
-	 * for getCalendarObjects.
874
-	 *
875
-	 * This method must return null if the object did not exist.
876
-	 *
877
-	 * @param mixed $calendarId
878
-	 * @param string $objectUri
879
-	 * @return array|null
880
-	 */
881
-	function getCalendarObject($calendarId, $objectUri) {
882
-
883
-		$query = $this->db->getQueryBuilder();
884
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
885
-				->from('calendarobjects')
886
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
887
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
888
-		$stmt = $query->execute();
889
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
890
-
891
-		if(!$row) return null;
892
-
893
-		return [
894
-				'id'            => $row['id'],
895
-				'uri'           => $row['uri'],
896
-				'lastmodified'  => $row['lastmodified'],
897
-				'etag'          => '"' . $row['etag'] . '"',
898
-				'calendarid'    => $row['calendarid'],
899
-				'size'          => (int)$row['size'],
900
-				'calendardata'  => $this->readBlob($row['calendardata']),
901
-				'component'     => strtolower($row['componenttype']),
902
-				'classification'=> (int)$row['classification']
903
-		];
904
-	}
905
-
906
-	/**
907
-	 * Returns a list of calendar objects.
908
-	 *
909
-	 * This method should work identical to getCalendarObject, but instead
910
-	 * return all the calendar objects in the list as an array.
911
-	 *
912
-	 * If the backend supports this, it may allow for some speed-ups.
913
-	 *
914
-	 * @param mixed $calendarId
915
-	 * @param string[] $uris
916
-	 * @return array
917
-	 */
918
-	function getMultipleCalendarObjects($calendarId, array $uris) {
919
-		if (empty($uris)) {
920
-			return [];
921
-		}
922
-
923
-		$chunks = array_chunk($uris, 100);
924
-		$objects = [];
925
-
926
-		$query = $this->db->getQueryBuilder();
927
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
928
-			->from('calendarobjects')
929
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
930
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
931
-
932
-		foreach ($chunks as $uris) {
933
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
934
-			$result = $query->execute();
935
-
936
-			while ($row = $result->fetch()) {
937
-				$objects[] = [
938
-					'id'           => $row['id'],
939
-					'uri'          => $row['uri'],
940
-					'lastmodified' => $row['lastmodified'],
941
-					'etag'         => '"' . $row['etag'] . '"',
942
-					'calendarid'   => $row['calendarid'],
943
-					'size'         => (int)$row['size'],
944
-					'calendardata' => $this->readBlob($row['calendardata']),
945
-					'component'    => strtolower($row['componenttype']),
946
-					'classification' => (int)$row['classification']
947
-				];
948
-			}
949
-			$result->closeCursor();
950
-		}
951
-		return $objects;
952
-	}
953
-
954
-	/**
955
-	 * Creates a new calendar object.
956
-	 *
957
-	 * The object uri is only the basename, or filename and not a full path.
958
-	 *
959
-	 * It is possible return an etag from this function, which will be used in
960
-	 * the response to this PUT request. Note that the ETag must be surrounded
961
-	 * by double-quotes.
962
-	 *
963
-	 * However, you should only really return this ETag if you don't mangle the
964
-	 * calendar-data. If the result of a subsequent GET to this object is not
965
-	 * the exact same as this request body, you should omit the ETag.
966
-	 *
967
-	 * @param mixed $calendarId
968
-	 * @param string $objectUri
969
-	 * @param string $calendarData
970
-	 * @return string
971
-	 */
972
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
973
-		$extraData = $this->getDenormalizedData($calendarData);
974
-
975
-		$q = $this->db->getQueryBuilder();
976
-		$q->select($q->createFunction('COUNT(*)'))
977
-			->from('calendarobjects')
978
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
979
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
980
-
981
-		$result = $q->execute();
982
-		$count = (int) $result->fetchColumn();
983
-		$result->closeCursor();
984
-
985
-		if ($count !== 0) {
986
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
987
-		}
988
-
989
-		$query = $this->db->getQueryBuilder();
990
-		$query->insert('calendarobjects')
991
-			->values([
992
-				'calendarid' => $query->createNamedParameter($calendarId),
993
-				'uri' => $query->createNamedParameter($objectUri),
994
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
995
-				'lastmodified' => $query->createNamedParameter(time()),
996
-				'etag' => $query->createNamedParameter($extraData['etag']),
997
-				'size' => $query->createNamedParameter($extraData['size']),
998
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
999
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1000
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1001
-				'classification' => $query->createNamedParameter($extraData['classification']),
1002
-				'uid' => $query->createNamedParameter($extraData['uid']),
1003
-			])
1004
-			->execute();
1005
-
1006
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1007
-
1008
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1009
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1010
-			[
1011
-				'calendarId' => $calendarId,
1012
-				'calendarData' => $this->getCalendarById($calendarId),
1013
-				'shares' => $this->getShares($calendarId),
1014
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1015
-			]
1016
-		));
1017
-		$this->addChange($calendarId, $objectUri, 1);
1018
-
1019
-		return '"' . $extraData['etag'] . '"';
1020
-	}
1021
-
1022
-	/**
1023
-	 * Updates an existing calendarobject, based on it's uri.
1024
-	 *
1025
-	 * The object uri is only the basename, or filename and not a full path.
1026
-	 *
1027
-	 * It is possible return an etag from this function, which will be used in
1028
-	 * the response to this PUT request. Note that the ETag must be surrounded
1029
-	 * by double-quotes.
1030
-	 *
1031
-	 * However, you should only really return this ETag if you don't mangle the
1032
-	 * calendar-data. If the result of a subsequent GET to this object is not
1033
-	 * the exact same as this request body, you should omit the ETag.
1034
-	 *
1035
-	 * @param mixed $calendarId
1036
-	 * @param string $objectUri
1037
-	 * @param string $calendarData
1038
-	 * @return string
1039
-	 */
1040
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1041
-		$extraData = $this->getDenormalizedData($calendarData);
1042
-
1043
-		$query = $this->db->getQueryBuilder();
1044
-		$query->update('calendarobjects')
1045
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1046
-				->set('lastmodified', $query->createNamedParameter(time()))
1047
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1048
-				->set('size', $query->createNamedParameter($extraData['size']))
1049
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1050
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1051
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1052
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1053
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1054
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1055
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1056
-			->execute();
1057
-
1058
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1059
-
1060
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1061
-		if (is_array($data)) {
1062
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1063
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1064
-				[
1065
-					'calendarId' => $calendarId,
1066
-					'calendarData' => $this->getCalendarById($calendarId),
1067
-					'shares' => $this->getShares($calendarId),
1068
-					'objectData' => $data,
1069
-				]
1070
-			));
1071
-		}
1072
-		$this->addChange($calendarId, $objectUri, 2);
1073
-
1074
-		return '"' . $extraData['etag'] . '"';
1075
-	}
1076
-
1077
-	/**
1078
-	 * @param int $calendarObjectId
1079
-	 * @param int $classification
1080
-	 */
1081
-	public function setClassification($calendarObjectId, $classification) {
1082
-		if (!in_array($classification, [
1083
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1084
-		])) {
1085
-			throw new \InvalidArgumentException();
1086
-		}
1087
-		$query = $this->db->getQueryBuilder();
1088
-		$query->update('calendarobjects')
1089
-			->set('classification', $query->createNamedParameter($classification))
1090
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1091
-			->execute();
1092
-	}
1093
-
1094
-	/**
1095
-	 * Deletes an existing calendar object.
1096
-	 *
1097
-	 * The object uri is only the basename, or filename and not a full path.
1098
-	 *
1099
-	 * @param mixed $calendarId
1100
-	 * @param string $objectUri
1101
-	 * @return void
1102
-	 */
1103
-	function deleteCalendarObject($calendarId, $objectUri) {
1104
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1105
-		if (is_array($data)) {
1106
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1107
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1108
-				[
1109
-					'calendarId' => $calendarId,
1110
-					'calendarData' => $this->getCalendarById($calendarId),
1111
-					'shares' => $this->getShares($calendarId),
1112
-					'objectData' => $data,
1113
-				]
1114
-			));
1115
-		}
1116
-
1117
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1118
-		$stmt->execute([$calendarId, $objectUri]);
1119
-
1120
-		$this->purgeProperties($calendarId, $data['id']);
1121
-
1122
-		$this->addChange($calendarId, $objectUri, 3);
1123
-	}
1124
-
1125
-	/**
1126
-	 * Performs a calendar-query on the contents of this calendar.
1127
-	 *
1128
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1129
-	 * calendar-query it is possible for a client to request a specific set of
1130
-	 * object, based on contents of iCalendar properties, date-ranges and
1131
-	 * iCalendar component types (VTODO, VEVENT).
1132
-	 *
1133
-	 * This method should just return a list of (relative) urls that match this
1134
-	 * query.
1135
-	 *
1136
-	 * The list of filters are specified as an array. The exact array is
1137
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1138
-	 *
1139
-	 * Note that it is extremely likely that getCalendarObject for every path
1140
-	 * returned from this method will be called almost immediately after. You
1141
-	 * may want to anticipate this to speed up these requests.
1142
-	 *
1143
-	 * This method provides a default implementation, which parses *all* the
1144
-	 * iCalendar objects in the specified calendar.
1145
-	 *
1146
-	 * This default may well be good enough for personal use, and calendars
1147
-	 * that aren't very large. But if you anticipate high usage, big calendars
1148
-	 * or high loads, you are strongly advised to optimize certain paths.
1149
-	 *
1150
-	 * The best way to do so is override this method and to optimize
1151
-	 * specifically for 'common filters'.
1152
-	 *
1153
-	 * Requests that are extremely common are:
1154
-	 *   * requests for just VEVENTS
1155
-	 *   * requests for just VTODO
1156
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1157
-	 *
1158
-	 * ..and combinations of these requests. It may not be worth it to try to
1159
-	 * handle every possible situation and just rely on the (relatively
1160
-	 * easy to use) CalendarQueryValidator to handle the rest.
1161
-	 *
1162
-	 * Note that especially time-range-filters may be difficult to parse. A
1163
-	 * time-range filter specified on a VEVENT must for instance also handle
1164
-	 * recurrence rules correctly.
1165
-	 * A good example of how to interprete all these filters can also simply
1166
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1167
-	 * as possible, so it gives you a good idea on what type of stuff you need
1168
-	 * to think of.
1169
-	 *
1170
-	 * @param mixed $calendarId
1171
-	 * @param array $filters
1172
-	 * @return array
1173
-	 */
1174
-	function calendarQuery($calendarId, array $filters) {
1175
-		$componentType = null;
1176
-		$requirePostFilter = true;
1177
-		$timeRange = null;
1178
-
1179
-		// if no filters were specified, we don't need to filter after a query
1180
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1181
-			$requirePostFilter = false;
1182
-		}
1183
-
1184
-		// Figuring out if there's a component filter
1185
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1186
-			$componentType = $filters['comp-filters'][0]['name'];
1187
-
1188
-			// Checking if we need post-filters
1189
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1190
-				$requirePostFilter = false;
1191
-			}
1192
-			// There was a time-range filter
1193
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1194
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1195
-
1196
-				// If start time OR the end time is not specified, we can do a
1197
-				// 100% accurate mysql query.
1198
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1199
-					$requirePostFilter = false;
1200
-				}
1201
-			}
1202
-
1203
-		}
1204
-		$columns = ['uri'];
1205
-		if ($requirePostFilter) {
1206
-			$columns = ['uri', 'calendardata'];
1207
-		}
1208
-		$query = $this->db->getQueryBuilder();
1209
-		$query->select($columns)
1210
-			->from('calendarobjects')
1211
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1212
-
1213
-		if ($componentType) {
1214
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1215
-		}
1216
-
1217
-		if ($timeRange && $timeRange['start']) {
1218
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1219
-		}
1220
-		if ($timeRange && $timeRange['end']) {
1221
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1222
-		}
1223
-
1224
-		$stmt = $query->execute();
1225
-
1226
-		$result = [];
1227
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1228
-			if ($requirePostFilter) {
1229
-				// validateFilterForObject will parse the calendar data
1230
-				// catch parsing errors
1231
-				try {
1232
-					$matches = $this->validateFilterForObject($row, $filters);
1233
-				} catch(ParseException $ex) {
1234
-					$this->logger->logException($ex, [
1235
-						'app' => 'dav',
1236
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1237
-					]);
1238
-					continue;
1239
-				} catch (InvalidDataException $ex) {
1240
-					$this->logger->logException($ex, [
1241
-						'app' => 'dav',
1242
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1243
-					]);
1244
-					continue;
1245
-				}
1246
-
1247
-				if (!$matches) {
1248
-					continue;
1249
-				}
1250
-			}
1251
-			$result[] = $row['uri'];
1252
-		}
1253
-
1254
-		return $result;
1255
-	}
1256
-
1257
-	/**
1258
-	 * custom Nextcloud search extension for CalDAV
1259
-	 *
1260
-	 * @param string $principalUri
1261
-	 * @param array $filters
1262
-	 * @param integer|null $limit
1263
-	 * @param integer|null $offset
1264
-	 * @return array
1265
-	 */
1266
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1267
-		$calendars = $this->getCalendarsForUser($principalUri);
1268
-		$ownCalendars = [];
1269
-		$sharedCalendars = [];
1270
-
1271
-		$uriMapper = [];
1272
-
1273
-		foreach($calendars as $calendar) {
1274
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1275
-				$ownCalendars[] = $calendar['id'];
1276
-			} else {
1277
-				$sharedCalendars[] = $calendar['id'];
1278
-			}
1279
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1280
-		}
1281
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1282
-			return [];
1283
-		}
1284
-
1285
-		$query = $this->db->getQueryBuilder();
1286
-		// Calendar id expressions
1287
-		$calendarExpressions = [];
1288
-		foreach($ownCalendars as $id) {
1289
-			$calendarExpressions[] = $query->expr()
1290
-				->eq('c.calendarid', $query->createNamedParameter($id));
1291
-		}
1292
-		foreach($sharedCalendars as $id) {
1293
-			$calendarExpressions[] = $query->expr()->andX(
1294
-				$query->expr()->eq('c.calendarid',
1295
-					$query->createNamedParameter($id)),
1296
-				$query->expr()->eq('c.classification',
1297
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1298
-			);
1299
-		}
1300
-
1301
-		if (count($calendarExpressions) === 1) {
1302
-			$calExpr = $calendarExpressions[0];
1303
-		} else {
1304
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1305
-		}
1306
-
1307
-		// Component expressions
1308
-		$compExpressions = [];
1309
-		foreach($filters['comps'] as $comp) {
1310
-			$compExpressions[] = $query->expr()
1311
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1312
-		}
1313
-
1314
-		if (count($compExpressions) === 1) {
1315
-			$compExpr = $compExpressions[0];
1316
-		} else {
1317
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1318
-		}
1319
-
1320
-		if (!isset($filters['props'])) {
1321
-			$filters['props'] = [];
1322
-		}
1323
-		if (!isset($filters['params'])) {
1324
-			$filters['params'] = [];
1325
-		}
1326
-
1327
-		$propParamExpressions = [];
1328
-		foreach($filters['props'] as $prop) {
1329
-			$propParamExpressions[] = $query->expr()->andX(
1330
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1331
-				$query->expr()->isNull('i.parameter')
1332
-			);
1333
-		}
1334
-		foreach($filters['params'] as $param) {
1335
-			$propParamExpressions[] = $query->expr()->andX(
1336
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1337
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1338
-			);
1339
-		}
1340
-
1341
-		if (count($propParamExpressions) === 1) {
1342
-			$propParamExpr = $propParamExpressions[0];
1343
-		} else {
1344
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1345
-		}
1346
-
1347
-		$query->select(['c.calendarid', 'c.uri'])
1348
-			->from($this->dbObjectPropertiesTable, 'i')
1349
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1350
-			->where($calExpr)
1351
-			->andWhere($compExpr)
1352
-			->andWhere($propParamExpr)
1353
-			->andWhere($query->expr()->iLike('i.value',
1354
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1355
-
1356
-		if ($offset) {
1357
-			$query->setFirstResult($offset);
1358
-		}
1359
-		if ($limit) {
1360
-			$query->setMaxResults($limit);
1361
-		}
1362
-
1363
-		$stmt = $query->execute();
1364
-
1365
-		$result = [];
1366
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1367
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1368
-			if (!in_array($path, $result)) {
1369
-				$result[] = $path;
1370
-			}
1371
-		}
1372
-
1373
-		return $result;
1374
-	}
1375
-
1376
-	/**
1377
-	 * used for Nextcloud's calendar API
1378
-	 *
1379
-	 * @param array $calendarInfo
1380
-	 * @param string $pattern
1381
-	 * @param array $searchProperties
1382
-	 * @param array $options
1383
-	 * @param integer|null $limit
1384
-	 * @param integer|null $offset
1385
-	 *
1386
-	 * @return array
1387
-	 */
1388
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1389
-						   array $options, $limit, $offset) {
1390
-		$outerQuery = $this->db->getQueryBuilder();
1391
-		$innerQuery = $this->db->getQueryBuilder();
1392
-
1393
-		$innerQuery->selectDistinct('op.objectid')
1394
-			->from($this->dbObjectPropertiesTable, 'op')
1395
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1396
-				$outerQuery->createNamedParameter($calendarInfo['id'])));
1397
-
1398
-		// only return public items for shared calendars for now
1399
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1400
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1401
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1402
-		}
1403
-
1404
-		$or = $innerQuery->expr()->orX();
1405
-		foreach($searchProperties as $searchProperty) {
1406
-			$or->add($innerQuery->expr()->eq('op.name',
1407
-				$outerQuery->createNamedParameter($searchProperty)));
1408
-		}
1409
-		$innerQuery->andWhere($or);
1410
-
1411
-		if ($pattern !== '') {
1412
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1413
-				$outerQuery->createNamedParameter('%' .
1414
-					$this->db->escapeLikeParameter($pattern) . '%')));
1415
-		}
1416
-
1417
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1418
-			->from('calendarobjects', 'c');
1419
-
1420
-		if (isset($options['timerange'])) {
1421
-			if (isset($options['timerange']['start'])) {
1422
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1423
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1424
-
1425
-			}
1426
-			if (isset($options['timerange']['end'])) {
1427
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1428
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1429
-			}
1430
-		}
1431
-
1432
-		if (isset($options['types'])) {
1433
-			$or = $outerQuery->expr()->orX();
1434
-			foreach($options['types'] as $type) {
1435
-				$or->add($outerQuery->expr()->eq('componenttype',
1436
-					$outerQuery->createNamedParameter($type)));
1437
-			}
1438
-			$outerQuery->andWhere($or);
1439
-		}
1440
-
1441
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1442
-			$outerQuery->createFunction($innerQuery->getSQL())));
1443
-
1444
-		if ($offset) {
1445
-			$outerQuery->setFirstResult($offset);
1446
-		}
1447
-		if ($limit) {
1448
-			$outerQuery->setMaxResults($limit);
1449
-		}
1450
-
1451
-		$result = $outerQuery->execute();
1452
-		$calendarObjects = $result->fetchAll();
1453
-
1454
-		return array_map(function($o) {
1455
-			$calendarData = Reader::read($o['calendardata']);
1456
-			$comps = $calendarData->getComponents();
1457
-			$objects = [];
1458
-			$timezones = [];
1459
-			foreach($comps as $comp) {
1460
-				if ($comp instanceof VTimeZone) {
1461
-					$timezones[] = $comp;
1462
-				} else {
1463
-					$objects[] = $comp;
1464
-				}
1465
-			}
1466
-
1467
-			return [
1468
-				'id' => $o['id'],
1469
-				'type' => $o['componenttype'],
1470
-				'uid' => $o['uid'],
1471
-				'uri' => $o['uri'],
1472
-				'objects' => array_map(function($c) {
1473
-					return $this->transformSearchData($c);
1474
-				}, $objects),
1475
-				'timezones' => array_map(function($c) {
1476
-					return $this->transformSearchData($c);
1477
-				}, $timezones),
1478
-			];
1479
-		}, $calendarObjects);
1480
-	}
1481
-
1482
-	/**
1483
-	 * @param Component $comp
1484
-	 * @return array
1485
-	 */
1486
-	private function transformSearchData(Component $comp) {
1487
-		$data = [];
1488
-		/** @var Component[] $subComponents */
1489
-		$subComponents = $comp->getComponents();
1490
-		/** @var Property[] $properties */
1491
-		$properties = array_filter($comp->children(), function($c) {
1492
-			return $c instanceof Property;
1493
-		});
1494
-		$validationRules = $comp->getValidationRules();
1495
-
1496
-		foreach($subComponents as $subComponent) {
1497
-			$name = $subComponent->name;
1498
-			if (!isset($data[$name])) {
1499
-				$data[$name] = [];
1500
-			}
1501
-			$data[$name][] = $this->transformSearchData($subComponent);
1502
-		}
1503
-
1504
-		foreach($properties as $property) {
1505
-			$name = $property->name;
1506
-			if (!isset($validationRules[$name])) {
1507
-				$validationRules[$name] = '*';
1508
-			}
1509
-
1510
-			$rule = $validationRules[$property->name];
1511
-			if ($rule === '+' || $rule === '*') { // multiple
1512
-				if (!isset($data[$name])) {
1513
-					$data[$name] = [];
1514
-				}
1515
-
1516
-				$data[$name][] = $this->transformSearchProperty($property);
1517
-			} else { // once
1518
-				$data[$name] = $this->transformSearchProperty($property);
1519
-			}
1520
-		}
1521
-
1522
-		return $data;
1523
-	}
1524
-
1525
-	/**
1526
-	 * @param Property $prop
1527
-	 * @return array
1528
-	 */
1529
-	private function transformSearchProperty(Property $prop) {
1530
-		// No need to check Date, as it extends DateTime
1531
-		if ($prop instanceof Property\ICalendar\DateTime) {
1532
-			$value = $prop->getDateTime();
1533
-		} else {
1534
-			$value = $prop->getValue();
1535
-		}
1536
-
1537
-		return [
1538
-			$value,
1539
-			$prop->parameters()
1540
-		];
1541
-	}
1542
-
1543
-	/**
1544
-	 * Searches through all of a users calendars and calendar objects to find
1545
-	 * an object with a specific UID.
1546
-	 *
1547
-	 * This method should return the path to this object, relative to the
1548
-	 * calendar home, so this path usually only contains two parts:
1549
-	 *
1550
-	 * calendarpath/objectpath.ics
1551
-	 *
1552
-	 * If the uid is not found, return null.
1553
-	 *
1554
-	 * This method should only consider * objects that the principal owns, so
1555
-	 * any calendars owned by other principals that also appear in this
1556
-	 * collection should be ignored.
1557
-	 *
1558
-	 * @param string $principalUri
1559
-	 * @param string $uid
1560
-	 * @return string|null
1561
-	 */
1562
-	function getCalendarObjectByUID($principalUri, $uid) {
1563
-
1564
-		$query = $this->db->getQueryBuilder();
1565
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1566
-			->from('calendarobjects', 'co')
1567
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1568
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1569
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1570
-
1571
-		$stmt = $query->execute();
1572
-
1573
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1574
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1575
-		}
1576
-
1577
-		return null;
1578
-	}
1579
-
1580
-	/**
1581
-	 * The getChanges method returns all the changes that have happened, since
1582
-	 * the specified syncToken in the specified calendar.
1583
-	 *
1584
-	 * This function should return an array, such as the following:
1585
-	 *
1586
-	 * [
1587
-	 *   'syncToken' => 'The current synctoken',
1588
-	 *   'added'   => [
1589
-	 *      'new.txt',
1590
-	 *   ],
1591
-	 *   'modified'   => [
1592
-	 *      'modified.txt',
1593
-	 *   ],
1594
-	 *   'deleted' => [
1595
-	 *      'foo.php.bak',
1596
-	 *      'old.txt'
1597
-	 *   ]
1598
-	 * );
1599
-	 *
1600
-	 * The returned syncToken property should reflect the *current* syncToken
1601
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1602
-	 * property This is * needed here too, to ensure the operation is atomic.
1603
-	 *
1604
-	 * If the $syncToken argument is specified as null, this is an initial
1605
-	 * sync, and all members should be reported.
1606
-	 *
1607
-	 * The modified property is an array of nodenames that have changed since
1608
-	 * the last token.
1609
-	 *
1610
-	 * The deleted property is an array with nodenames, that have been deleted
1611
-	 * from collection.
1612
-	 *
1613
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1614
-	 * 1, you only have to report changes that happened only directly in
1615
-	 * immediate descendants. If it's 2, it should also include changes from
1616
-	 * the nodes below the child collections. (grandchildren)
1617
-	 *
1618
-	 * The $limit argument allows a client to specify how many results should
1619
-	 * be returned at most. If the limit is not specified, it should be treated
1620
-	 * as infinite.
1621
-	 *
1622
-	 * If the limit (infinite or not) is higher than you're willing to return,
1623
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1624
-	 *
1625
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1626
-	 * return null.
1627
-	 *
1628
-	 * The limit is 'suggestive'. You are free to ignore it.
1629
-	 *
1630
-	 * @param string $calendarId
1631
-	 * @param string $syncToken
1632
-	 * @param int $syncLevel
1633
-	 * @param int $limit
1634
-	 * @return array
1635
-	 */
1636
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1637
-		// Current synctoken
1638
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1639
-		$stmt->execute([ $calendarId ]);
1640
-		$currentToken = $stmt->fetchColumn(0);
1641
-
1642
-		if (is_null($currentToken)) {
1643
-			return null;
1644
-		}
1645
-
1646
-		$result = [
1647
-			'syncToken' => $currentToken,
1648
-			'added'     => [],
1649
-			'modified'  => [],
1650
-			'deleted'   => [],
1651
-		];
1652
-
1653
-		if ($syncToken) {
1654
-
1655
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1656
-			if ($limit>0) {
1657
-				$query.= " LIMIT " . (int)$limit;
1658
-			}
1659
-
1660
-			// Fetching all changes
1661
-			$stmt = $this->db->prepare($query);
1662
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1663
-
1664
-			$changes = [];
1665
-
1666
-			// This loop ensures that any duplicates are overwritten, only the
1667
-			// last change on a node is relevant.
1668
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1669
-
1670
-				$changes[$row['uri']] = $row['operation'];
1671
-
1672
-			}
1673
-
1674
-			foreach($changes as $uri => $operation) {
1675
-
1676
-				switch($operation) {
1677
-					case 1 :
1678
-						$result['added'][] = $uri;
1679
-						break;
1680
-					case 2 :
1681
-						$result['modified'][] = $uri;
1682
-						break;
1683
-					case 3 :
1684
-						$result['deleted'][] = $uri;
1685
-						break;
1686
-				}
1687
-
1688
-			}
1689
-		} else {
1690
-			// No synctoken supplied, this is the initial sync.
1691
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1692
-			$stmt = $this->db->prepare($query);
1693
-			$stmt->execute([$calendarId]);
1694
-
1695
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1696
-		}
1697
-		return $result;
1698
-
1699
-	}
1700
-
1701
-	/**
1702
-	 * Returns a list of subscriptions for a principal.
1703
-	 *
1704
-	 * Every subscription is an array with the following keys:
1705
-	 *  * id, a unique id that will be used by other functions to modify the
1706
-	 *    subscription. This can be the same as the uri or a database key.
1707
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1708
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1709
-	 *    principalUri passed to this method.
1710
-	 *
1711
-	 * Furthermore, all the subscription info must be returned too:
1712
-	 *
1713
-	 * 1. {DAV:}displayname
1714
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1715
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1716
-	 *    should not be stripped).
1717
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1718
-	 *    should not be stripped).
1719
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1720
-	 *    attachments should not be stripped).
1721
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1722
-	 *     Sabre\DAV\Property\Href).
1723
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1724
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1725
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1726
-	 *    (should just be an instance of
1727
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1728
-	 *    default components).
1729
-	 *
1730
-	 * @param string $principalUri
1731
-	 * @return array
1732
-	 */
1733
-	function getSubscriptionsForUser($principalUri) {
1734
-		$fields = array_values($this->subscriptionPropertyMap);
1735
-		$fields[] = 'id';
1736
-		$fields[] = 'uri';
1737
-		$fields[] = 'source';
1738
-		$fields[] = 'principaluri';
1739
-		$fields[] = 'lastmodified';
1740
-
1741
-		$query = $this->db->getQueryBuilder();
1742
-		$query->select($fields)
1743
-			->from('calendarsubscriptions')
1744
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1745
-			->orderBy('calendarorder', 'asc');
1746
-		$stmt =$query->execute();
1747
-
1748
-		$subscriptions = [];
1749
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1750
-
1751
-			$subscription = [
1752
-				'id'           => $row['id'],
1753
-				'uri'          => $row['uri'],
1754
-				'principaluri' => $row['principaluri'],
1755
-				'source'       => $row['source'],
1756
-				'lastmodified' => $row['lastmodified'],
1757
-
1758
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1759
-			];
1760
-
1761
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1762
-				if (!is_null($row[$dbName])) {
1763
-					$subscription[$xmlName] = $row[$dbName];
1764
-				}
1765
-			}
1766
-
1767
-			$subscriptions[] = $subscription;
1768
-
1769
-		}
1770
-
1771
-		return $subscriptions;
1772
-	}
1773
-
1774
-	/**
1775
-	 * Creates a new subscription for a principal.
1776
-	 *
1777
-	 * If the creation was a success, an id must be returned that can be used to reference
1778
-	 * this subscription in other methods, such as updateSubscription.
1779
-	 *
1780
-	 * @param string $principalUri
1781
-	 * @param string $uri
1782
-	 * @param array $properties
1783
-	 * @return mixed
1784
-	 */
1785
-	function createSubscription($principalUri, $uri, array $properties) {
1786
-
1787
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1788
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1789
-		}
1790
-
1791
-		$values = [
1792
-			'principaluri' => $principalUri,
1793
-			'uri'          => $uri,
1794
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1795
-			'lastmodified' => time(),
1796
-		];
1797
-
1798
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1799
-
1800
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1801
-			if (array_key_exists($xmlName, $properties)) {
1802
-					$values[$dbName] = $properties[$xmlName];
1803
-					if (in_array($dbName, $propertiesBoolean)) {
1804
-						$values[$dbName] = true;
1805
-				}
1806
-			}
1807
-		}
1808
-
1809
-		$valuesToInsert = array();
1810
-
1811
-		$query = $this->db->getQueryBuilder();
1812
-
1813
-		foreach (array_keys($values) as $name) {
1814
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1815
-		}
1816
-
1817
-		$query->insert('calendarsubscriptions')
1818
-			->values($valuesToInsert)
1819
-			->execute();
1820
-
1821
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1822
-	}
1823
-
1824
-	/**
1825
-	 * Updates a subscription
1826
-	 *
1827
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1828
-	 * To do the actual updates, you must tell this object which properties
1829
-	 * you're going to process with the handle() method.
1830
-	 *
1831
-	 * Calling the handle method is like telling the PropPatch object "I
1832
-	 * promise I can handle updating this property".
1833
-	 *
1834
-	 * Read the PropPatch documentation for more info and examples.
1835
-	 *
1836
-	 * @param mixed $subscriptionId
1837
-	 * @param PropPatch $propPatch
1838
-	 * @return void
1839
-	 */
1840
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1841
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1842
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1843
-
1844
-		/**
1845
-		 * @suppress SqlInjectionChecker
1846
-		 */
1847
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1848
-
1849
-			$newValues = [];
1850
-
1851
-			foreach($mutations as $propertyName=>$propertyValue) {
1852
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1853
-					$newValues['source'] = $propertyValue->getHref();
1854
-				} else {
1855
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1856
-					$newValues[$fieldName] = $propertyValue;
1857
-				}
1858
-			}
1859
-
1860
-			$query = $this->db->getQueryBuilder();
1861
-			$query->update('calendarsubscriptions')
1862
-				->set('lastmodified', $query->createNamedParameter(time()));
1863
-			foreach($newValues as $fieldName=>$value) {
1864
-				$query->set($fieldName, $query->createNamedParameter($value));
1865
-			}
1866
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1867
-				->execute();
1868
-
1869
-			return true;
1870
-
1871
-		});
1872
-	}
1873
-
1874
-	/**
1875
-	 * Deletes a subscription.
1876
-	 *
1877
-	 * @param mixed $subscriptionId
1878
-	 * @return void
1879
-	 */
1880
-	function deleteSubscription($subscriptionId) {
1881
-		$query = $this->db->getQueryBuilder();
1882
-		$query->delete('calendarsubscriptions')
1883
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1884
-			->execute();
1885
-	}
1886
-
1887
-	/**
1888
-	 * Returns a single scheduling object for the inbox collection.
1889
-	 *
1890
-	 * The returned array should contain the following elements:
1891
-	 *   * uri - A unique basename for the object. This will be used to
1892
-	 *           construct a full uri.
1893
-	 *   * calendardata - The iCalendar object
1894
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1895
-	 *                    timestamp, or a PHP DateTime object.
1896
-	 *   * etag - A unique token that must change if the object changed.
1897
-	 *   * size - The size of the object, in bytes.
1898
-	 *
1899
-	 * @param string $principalUri
1900
-	 * @param string $objectUri
1901
-	 * @return array
1902
-	 */
1903
-	function getSchedulingObject($principalUri, $objectUri) {
1904
-		$query = $this->db->getQueryBuilder();
1905
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1906
-			->from('schedulingobjects')
1907
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1908
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1909
-			->execute();
1910
-
1911
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1912
-
1913
-		if(!$row) {
1914
-			return null;
1915
-		}
1916
-
1917
-		return [
1918
-				'uri'          => $row['uri'],
1919
-				'calendardata' => $row['calendardata'],
1920
-				'lastmodified' => $row['lastmodified'],
1921
-				'etag'         => '"' . $row['etag'] . '"',
1922
-				'size'         => (int)$row['size'],
1923
-		];
1924
-	}
1925
-
1926
-	/**
1927
-	 * Returns all scheduling objects for the inbox collection.
1928
-	 *
1929
-	 * These objects should be returned as an array. Every item in the array
1930
-	 * should follow the same structure as returned from getSchedulingObject.
1931
-	 *
1932
-	 * The main difference is that 'calendardata' is optional.
1933
-	 *
1934
-	 * @param string $principalUri
1935
-	 * @return array
1936
-	 */
1937
-	function getSchedulingObjects($principalUri) {
1938
-		$query = $this->db->getQueryBuilder();
1939
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1940
-				->from('schedulingobjects')
1941
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1942
-				->execute();
1943
-
1944
-		$result = [];
1945
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1946
-			$result[] = [
1947
-					'calendardata' => $row['calendardata'],
1948
-					'uri'          => $row['uri'],
1949
-					'lastmodified' => $row['lastmodified'],
1950
-					'etag'         => '"' . $row['etag'] . '"',
1951
-					'size'         => (int)$row['size'],
1952
-			];
1953
-		}
1954
-
1955
-		return $result;
1956
-	}
1957
-
1958
-	/**
1959
-	 * Deletes a scheduling object from the inbox collection.
1960
-	 *
1961
-	 * @param string $principalUri
1962
-	 * @param string $objectUri
1963
-	 * @return void
1964
-	 */
1965
-	function deleteSchedulingObject($principalUri, $objectUri) {
1966
-		$query = $this->db->getQueryBuilder();
1967
-		$query->delete('schedulingobjects')
1968
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1969
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1970
-				->execute();
1971
-	}
1972
-
1973
-	/**
1974
-	 * Creates a new scheduling object. This should land in a users' inbox.
1975
-	 *
1976
-	 * @param string $principalUri
1977
-	 * @param string $objectUri
1978
-	 * @param string $objectData
1979
-	 * @return void
1980
-	 */
1981
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1982
-		$query = $this->db->getQueryBuilder();
1983
-		$query->insert('schedulingobjects')
1984
-			->values([
1985
-				'principaluri' => $query->createNamedParameter($principalUri),
1986
-				'calendardata' => $query->createNamedParameter($objectData),
1987
-				'uri' => $query->createNamedParameter($objectUri),
1988
-				'lastmodified' => $query->createNamedParameter(time()),
1989
-				'etag' => $query->createNamedParameter(md5($objectData)),
1990
-				'size' => $query->createNamedParameter(strlen($objectData))
1991
-			])
1992
-			->execute();
1993
-	}
1994
-
1995
-	/**
1996
-	 * Adds a change record to the calendarchanges table.
1997
-	 *
1998
-	 * @param mixed $calendarId
1999
-	 * @param string $objectUri
2000
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2001
-	 * @return void
2002
-	 */
2003
-	protected function addChange($calendarId, $objectUri, $operation) {
2004
-
2005
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
2006
-		$stmt->execute([
2007
-			$objectUri,
2008
-			$calendarId,
2009
-			$operation,
2010
-			$calendarId
2011
-		]);
2012
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
2013
-		$stmt->execute([
2014
-			$calendarId
2015
-		]);
2016
-
2017
-	}
2018
-
2019
-	/**
2020
-	 * Parses some information from calendar objects, used for optimized
2021
-	 * calendar-queries.
2022
-	 *
2023
-	 * Returns an array with the following keys:
2024
-	 *   * etag - An md5 checksum of the object without the quotes.
2025
-	 *   * size - Size of the object in bytes
2026
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2027
-	 *   * firstOccurence
2028
-	 *   * lastOccurence
2029
-	 *   * uid - value of the UID property
2030
-	 *
2031
-	 * @param string $calendarData
2032
-	 * @return array
2033
-	 */
2034
-	public function getDenormalizedData($calendarData) {
2035
-
2036
-		$vObject = Reader::read($calendarData);
2037
-		$componentType = null;
2038
-		$component = null;
2039
-		$firstOccurrence = null;
2040
-		$lastOccurrence = null;
2041
-		$uid = null;
2042
-		$classification = self::CLASSIFICATION_PUBLIC;
2043
-		foreach($vObject->getComponents() as $component) {
2044
-			if ($component->name!=='VTIMEZONE') {
2045
-				$componentType = $component->name;
2046
-				$uid = (string)$component->UID;
2047
-				break;
2048
-			}
2049
-		}
2050
-		if (!$componentType) {
2051
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2052
-		}
2053
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2054
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2055
-			// Finding the last occurrence is a bit harder
2056
-			if (!isset($component->RRULE)) {
2057
-				if (isset($component->DTEND)) {
2058
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2059
-				} elseif (isset($component->DURATION)) {
2060
-					$endDate = clone $component->DTSTART->getDateTime();
2061
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2062
-					$lastOccurrence = $endDate->getTimeStamp();
2063
-				} elseif (!$component->DTSTART->hasTime()) {
2064
-					$endDate = clone $component->DTSTART->getDateTime();
2065
-					$endDate->modify('+1 day');
2066
-					$lastOccurrence = $endDate->getTimeStamp();
2067
-				} else {
2068
-					$lastOccurrence = $firstOccurrence;
2069
-				}
2070
-			} else {
2071
-				$it = new EventIterator($vObject, (string)$component->UID);
2072
-				$maxDate = new \DateTime(self::MAX_DATE);
2073
-				if ($it->isInfinite()) {
2074
-					$lastOccurrence = $maxDate->getTimestamp();
2075
-				} else {
2076
-					$end = $it->getDtEnd();
2077
-					while($it->valid() && $end < $maxDate) {
2078
-						$end = $it->getDtEnd();
2079
-						$it->next();
2080
-
2081
-					}
2082
-					$lastOccurrence = $end->getTimestamp();
2083
-				}
2084
-
2085
-			}
2086
-		}
2087
-
2088
-		if ($component->CLASS) {
2089
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2090
-			switch ($component->CLASS->getValue()) {
2091
-				case 'PUBLIC':
2092
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2093
-					break;
2094
-				case 'CONFIDENTIAL':
2095
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2096
-					break;
2097
-			}
2098
-		}
2099
-		return [
2100
-			'etag' => md5($calendarData),
2101
-			'size' => strlen($calendarData),
2102
-			'componentType' => $componentType,
2103
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2104
-			'lastOccurence'  => $lastOccurrence,
2105
-			'uid' => $uid,
2106
-			'classification' => $classification
2107
-		];
2108
-
2109
-	}
2110
-
2111
-	private function readBlob($cardData) {
2112
-		if (is_resource($cardData)) {
2113
-			return stream_get_contents($cardData);
2114
-		}
2115
-
2116
-		return $cardData;
2117
-	}
2118
-
2119
-	/**
2120
-	 * @param IShareable $shareable
2121
-	 * @param array $add
2122
-	 * @param array $remove
2123
-	 */
2124
-	public function updateShares($shareable, $add, $remove) {
2125
-		$calendarId = $shareable->getResourceId();
2126
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2127
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2128
-			[
2129
-				'calendarId' => $calendarId,
2130
-				'calendarData' => $this->getCalendarById($calendarId),
2131
-				'shares' => $this->getShares($calendarId),
2132
-				'add' => $add,
2133
-				'remove' => $remove,
2134
-			]));
2135
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
2136
-	}
2137
-
2138
-	/**
2139
-	 * @param int $resourceId
2140
-	 * @return array
2141
-	 */
2142
-	public function getShares($resourceId) {
2143
-		return $this->sharingBackend->getShares($resourceId);
2144
-	}
2145
-
2146
-	/**
2147
-	 * @param boolean $value
2148
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2149
-	 * @return string|null
2150
-	 */
2151
-	public function setPublishStatus($value, $calendar) {
2152
-
2153
-		$calendarId = $calendar->getResourceId();
2154
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2155
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2156
-			[
2157
-				'calendarId' => $calendarId,
2158
-				'calendarData' => $this->getCalendarById($calendarId),
2159
-				'public' => $value,
2160
-			]));
2161
-
2162
-		$query = $this->db->getQueryBuilder();
2163
-		if ($value) {
2164
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2165
-			$query->insert('dav_shares')
2166
-				->values([
2167
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2168
-					'type' => $query->createNamedParameter('calendar'),
2169
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2170
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2171
-					'publicuri' => $query->createNamedParameter($publicUri)
2172
-				]);
2173
-			$query->execute();
2174
-			return $publicUri;
2175
-		}
2176
-		$query->delete('dav_shares')
2177
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2178
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2179
-		$query->execute();
2180
-		return null;
2181
-	}
2182
-
2183
-	/**
2184
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2185
-	 * @return mixed
2186
-	 */
2187
-	public function getPublishStatus($calendar) {
2188
-		$query = $this->db->getQueryBuilder();
2189
-		$result = $query->select('publicuri')
2190
-			->from('dav_shares')
2191
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2192
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2193
-			->execute();
2194
-
2195
-		$row = $result->fetch();
2196
-		$result->closeCursor();
2197
-		return $row ? reset($row) : false;
2198
-	}
2199
-
2200
-	/**
2201
-	 * @param int $resourceId
2202
-	 * @param array $acl
2203
-	 * @return array
2204
-	 */
2205
-	public function applyShareAcl($resourceId, $acl) {
2206
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
2207
-	}
2208
-
2209
-
2210
-
2211
-	/**
2212
-	 * update properties table
2213
-	 *
2214
-	 * @param int $calendarId
2215
-	 * @param string $objectUri
2216
-	 * @param string $calendarData
2217
-	 */
2218
-	public function updateProperties($calendarId, $objectUri, $calendarData) {
2219
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri);
2220
-
2221
-		try {
2222
-			$vCalendar = $this->readCalendarData($calendarData);
2223
-		} catch (\Exception $ex) {
2224
-			return;
2225
-		}
2226
-
2227
-		$this->purgeProperties($calendarId, $objectId);
2228
-
2229
-		$query = $this->db->getQueryBuilder();
2230
-		$query->insert($this->dbObjectPropertiesTable)
2231
-			->values(
2232
-				[
2233
-					'calendarid' => $query->createNamedParameter($calendarId),
2234
-					'objectid' => $query->createNamedParameter($objectId),
2235
-					'name' => $query->createParameter('name'),
2236
-					'parameter' => $query->createParameter('parameter'),
2237
-					'value' => $query->createParameter('value'),
2238
-				]
2239
-			);
2240
-
2241
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2242
-		foreach ($vCalendar->getComponents() as $component) {
2243
-			if (!in_array($component->name, $indexComponents)) {
2244
-				continue;
2245
-			}
2246
-
2247
-			foreach ($component->children() as $property) {
2248
-				if (in_array($property->name, self::$indexProperties)) {
2249
-					$value = $property->getValue();
2250
-					// is this a shitty db?
2251
-					if (!$this->db->supports4ByteText()) {
2252
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2253
-					}
2254
-					$value = substr($value, 0, 254);
2255
-
2256
-					$query->setParameter('name', $property->name);
2257
-					$query->setParameter('parameter', null);
2258
-					$query->setParameter('value', $value);
2259
-					$query->execute();
2260
-				}
2261
-
2262
-				if (array_key_exists($property->name, self::$indexParameters)) {
2263
-					$parameters = $property->parameters();
2264
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2265
-
2266
-					foreach ($parameters as $key => $value) {
2267
-						if (in_array($key, $indexedParametersForProperty)) {
2268
-							// is this a shitty db?
2269
-							if ($this->db->supports4ByteText()) {
2270
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2271
-							}
2272
-							$value = substr($value, 0, 254);
2273
-
2274
-							$query->setParameter('name', $property->name);
2275
-							$query->setParameter('parameter', substr($key, 0, 254));
2276
-							$query->setParameter('value', substr($value, 0, 254));
2277
-							$query->execute();
2278
-						}
2279
-					}
2280
-				}
2281
-			}
2282
-		}
2283
-	}
2284
-
2285
-	/**
2286
-	 * Move a calendar from one user to another
2287
-	 *
2288
-	 * @param string $uriName
2289
-	 * @param string $uriOrigin
2290
-	 * @param string $uriDestination
2291
-	 */
2292
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2293
-	{
2294
-		$query = $this->db->getQueryBuilder();
2295
-		$query->update('calendars')
2296
-			->set('principaluri', $query->createNamedParameter($uriDestination))
2297
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2298
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2299
-			->execute();
2300
-	}
2301
-
2302
-	/**
2303
-	 * @param string $displayName
2304
-	 * @param string|null $principalUri
2305
-	 * @return array
2306
-	 */
2307
-	public function findCalendarsUrisByDisplayName($displayName, $principalUri = null)
2308
-	{
2309
-		// Ideally $displayName would be sanitized the same way as stringUtility.js does in calendar
2310
-
2311
-		$query = $this->db->getQueryBuilder();
2312
-		$query->select('uri')
2313
-			->from('calendars')
2314
-			->where($query->expr()->iLike('displayname',
2315
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($displayName).'%')));
2316
-		if ($principalUri) {
2317
-			$query->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
2318
-		}
2319
-		$result = $query->execute();
2320
-
2321
-		$calendarUris = [];
2322
-		while($row = $result->fetch()) {
2323
-			$calendarUris[] = $row['uri'];
2324
-		}
2325
-		return $calendarUris;
2326
-	}
2327
-
2328
-	/**
2329
-	 * deletes all birthday calendars
2330
-	 */
2331
-	public function deleteAllBirthdayCalendars() {
2332
-		$query = $this->db->getQueryBuilder();
2333
-		$result = $query->select(['id'])->from('calendars')
2334
-			->where($query->expr()->eq('uri',
2335
-				$query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2336
-			->execute();
2337
-
2338
-		$ids = $result->fetchAll();
2339
-		foreach($ids as $id) {
2340
-			$this->deleteCalendar($id['id']);
2341
-		}
2342
-	}
2343
-
2344
-	/**
2345
-	 * read VCalendar data into a VCalendar object
2346
-	 *
2347
-	 * @param string $objectData
2348
-	 * @return VCalendar
2349
-	 */
2350
-	protected function readCalendarData($objectData) {
2351
-		return Reader::read($objectData);
2352
-	}
2353
-
2354
-	/**
2355
-	 * delete all properties from a given calendar object
2356
-	 *
2357
-	 * @param int $calendarId
2358
-	 * @param int $objectId
2359
-	 */
2360
-	protected function purgeProperties($calendarId, $objectId) {
2361
-		$query = $this->db->getQueryBuilder();
2362
-		$query->delete($this->dbObjectPropertiesTable)
2363
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2364
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2365
-		$query->execute();
2366
-	}
2367
-
2368
-	/**
2369
-	 * get ID from a given calendar object
2370
-	 *
2371
-	 * @param int $calendarId
2372
-	 * @param string $uri
2373
-	 * @return int
2374
-	 */
2375
-	protected function getCalendarObjectId($calendarId, $uri) {
2376
-		$query = $this->db->getQueryBuilder();
2377
-		$query->select('id')->from('calendarobjects')
2378
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2379
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2380
-
2381
-		$result = $query->execute();
2382
-		$objectIds = $result->fetch();
2383
-		$result->closeCursor();
2384
-
2385
-		if (!isset($objectIds['id'])) {
2386
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2387
-		}
2388
-
2389
-		return (int)$objectIds['id'];
2390
-	}
2391
-
2392
-	private function convertPrincipal($principalUri, $toV2) {
2393
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2394
-			list(, $name) = Uri\split($principalUri);
2395
-			if ($toV2 === true) {
2396
-				return "principals/users/$name";
2397
-			}
2398
-			return "principals/$name";
2399
-		}
2400
-		return $principalUri;
2401
-	}
2402
-
2403
-	private function addOwnerPrincipal(&$calendarInfo) {
2404
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2405
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2406
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2407
-			$uri = $calendarInfo[$ownerPrincipalKey];
2408
-		} else {
2409
-			$uri = $calendarInfo['principaluri'];
2410
-		}
2411
-
2412
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2413
-		if (isset($principalInformation['{DAV:}displayname'])) {
2414
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2415
-		}
2416
-	}
431
+    /**
432
+     * @return array
433
+     */
434
+    public function getPublicCalendars() {
435
+        $fields = array_values($this->propertyMap);
436
+        $fields[] = 'a.id';
437
+        $fields[] = 'a.uri';
438
+        $fields[] = 'a.synctoken';
439
+        $fields[] = 'a.components';
440
+        $fields[] = 'a.principaluri';
441
+        $fields[] = 'a.transparent';
442
+        $fields[] = 's.access';
443
+        $fields[] = 's.publicuri';
444
+        $calendars = [];
445
+        $query = $this->db->getQueryBuilder();
446
+        $result = $query->select($fields)
447
+            ->from('dav_shares', 's')
448
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
449
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
450
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
451
+            ->execute();
452
+
453
+        while($row = $result->fetch()) {
454
+            list(, $name) = Uri\split($row['principaluri']);
455
+            $row['displayname'] = $row['displayname'] . "($name)";
456
+            $components = [];
457
+            if ($row['components']) {
458
+                $components = explode(',',$row['components']);
459
+            }
460
+            $calendar = [
461
+                'id' => $row['id'],
462
+                'uri' => $row['publicuri'],
463
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
464
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
465
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
466
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
467
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
468
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
469
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
470
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
471
+            ];
472
+
473
+            foreach($this->propertyMap as $xmlName=>$dbName) {
474
+                $calendar[$xmlName] = $row[$dbName];
475
+            }
476
+
477
+            $this->addOwnerPrincipal($calendar);
478
+
479
+            if (!isset($calendars[$calendar['id']])) {
480
+                $calendars[$calendar['id']] = $calendar;
481
+            }
482
+        }
483
+        $result->closeCursor();
484
+
485
+        return array_values($calendars);
486
+    }
487
+
488
+    /**
489
+     * @param string $uri
490
+     * @return array
491
+     * @throws NotFound
492
+     */
493
+    public function getPublicCalendar($uri) {
494
+        $fields = array_values($this->propertyMap);
495
+        $fields[] = 'a.id';
496
+        $fields[] = 'a.uri';
497
+        $fields[] = 'a.synctoken';
498
+        $fields[] = 'a.components';
499
+        $fields[] = 'a.principaluri';
500
+        $fields[] = 'a.transparent';
501
+        $fields[] = 's.access';
502
+        $fields[] = 's.publicuri';
503
+        $query = $this->db->getQueryBuilder();
504
+        $result = $query->select($fields)
505
+            ->from('dav_shares', 's')
506
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
507
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
508
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
509
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
510
+            ->execute();
511
+
512
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
513
+
514
+        $result->closeCursor();
515
+
516
+        if ($row === false) {
517
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
518
+        }
519
+
520
+        list(, $name) = Uri\split($row['principaluri']);
521
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
522
+        $components = [];
523
+        if ($row['components']) {
524
+            $components = explode(',',$row['components']);
525
+        }
526
+        $calendar = [
527
+            'id' => $row['id'],
528
+            'uri' => $row['publicuri'],
529
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
530
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
531
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
532
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
533
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
534
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
535
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
536
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
537
+        ];
538
+
539
+        foreach($this->propertyMap as $xmlName=>$dbName) {
540
+            $calendar[$xmlName] = $row[$dbName];
541
+        }
542
+
543
+        $this->addOwnerPrincipal($calendar);
544
+
545
+        return $calendar;
546
+
547
+    }
548
+
549
+    /**
550
+     * @param string $principal
551
+     * @param string $uri
552
+     * @return array|null
553
+     */
554
+    public function getCalendarByUri($principal, $uri) {
555
+        $fields = array_values($this->propertyMap);
556
+        $fields[] = 'id';
557
+        $fields[] = 'uri';
558
+        $fields[] = 'synctoken';
559
+        $fields[] = 'components';
560
+        $fields[] = 'principaluri';
561
+        $fields[] = 'transparent';
562
+
563
+        // Making fields a comma-delimited list
564
+        $query = $this->db->getQueryBuilder();
565
+        $query->select($fields)->from('calendars')
566
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
567
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
568
+            ->setMaxResults(1);
569
+        $stmt = $query->execute();
570
+
571
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
572
+        $stmt->closeCursor();
573
+        if ($row === false) {
574
+            return null;
575
+        }
576
+
577
+        $components = [];
578
+        if ($row['components']) {
579
+            $components = explode(',',$row['components']);
580
+        }
581
+
582
+        $calendar = [
583
+            'id' => $row['id'],
584
+            'uri' => $row['uri'],
585
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
586
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
587
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
588
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
589
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
590
+        ];
591
+
592
+        foreach($this->propertyMap as $xmlName=>$dbName) {
593
+            $calendar[$xmlName] = $row[$dbName];
594
+        }
595
+
596
+        $this->addOwnerPrincipal($calendar);
597
+
598
+        return $calendar;
599
+    }
600
+
601
+    public function getCalendarById($calendarId) {
602
+        $fields = array_values($this->propertyMap);
603
+        $fields[] = 'id';
604
+        $fields[] = 'uri';
605
+        $fields[] = 'synctoken';
606
+        $fields[] = 'components';
607
+        $fields[] = 'principaluri';
608
+        $fields[] = 'transparent';
609
+
610
+        // Making fields a comma-delimited list
611
+        $query = $this->db->getQueryBuilder();
612
+        $query->select($fields)->from('calendars')
613
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
614
+            ->setMaxResults(1);
615
+        $stmt = $query->execute();
616
+
617
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
618
+        $stmt->closeCursor();
619
+        if ($row === false) {
620
+            return null;
621
+        }
622
+
623
+        $components = [];
624
+        if ($row['components']) {
625
+            $components = explode(',',$row['components']);
626
+        }
627
+
628
+        $calendar = [
629
+            'id' => $row['id'],
630
+            'uri' => $row['uri'],
631
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
632
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
633
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
634
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
635
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
636
+        ];
637
+
638
+        foreach($this->propertyMap as $xmlName=>$dbName) {
639
+            $calendar[$xmlName] = $row[$dbName];
640
+        }
641
+
642
+        $this->addOwnerPrincipal($calendar);
643
+
644
+        return $calendar;
645
+    }
646
+
647
+    /**
648
+     * Creates a new calendar for a principal.
649
+     *
650
+     * If the creation was a success, an id must be returned that can be used to reference
651
+     * this calendar in other methods, such as updateCalendar.
652
+     *
653
+     * @param string $principalUri
654
+     * @param string $calendarUri
655
+     * @param array $properties
656
+     * @return int
657
+     * @suppress SqlInjectionChecker
658
+     */
659
+    function createCalendar($principalUri, $calendarUri, array $properties) {
660
+        $values = [
661
+            'principaluri' => $this->convertPrincipal($principalUri, true),
662
+            'uri'          => $calendarUri,
663
+            'synctoken'    => 1,
664
+            'transparent'  => 0,
665
+            'components'   => 'VEVENT,VTODO',
666
+            'displayname'  => $calendarUri
667
+        ];
668
+
669
+        // Default value
670
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
671
+        if (isset($properties[$sccs])) {
672
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
673
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
674
+            }
675
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
676
+        }
677
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
678
+        if (isset($properties[$transp])) {
679
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
680
+        }
681
+
682
+        foreach($this->propertyMap as $xmlName=>$dbName) {
683
+            if (isset($properties[$xmlName])) {
684
+                $values[$dbName] = $properties[$xmlName];
685
+            }
686
+        }
687
+
688
+        $query = $this->db->getQueryBuilder();
689
+        $query->insert('calendars');
690
+        foreach($values as $column => $value) {
691
+            $query->setValue($column, $query->createNamedParameter($value));
692
+        }
693
+        $query->execute();
694
+        $calendarId = $query->getLastInsertId();
695
+
696
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
697
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
698
+            [
699
+                'calendarId' => $calendarId,
700
+                'calendarData' => $this->getCalendarById($calendarId),
701
+        ]));
702
+
703
+        return $calendarId;
704
+    }
705
+
706
+    /**
707
+     * Updates properties for a calendar.
708
+     *
709
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
710
+     * To do the actual updates, you must tell this object which properties
711
+     * you're going to process with the handle() method.
712
+     *
713
+     * Calling the handle method is like telling the PropPatch object "I
714
+     * promise I can handle updating this property".
715
+     *
716
+     * Read the PropPatch documentation for more info and examples.
717
+     *
718
+     * @param mixed $calendarId
719
+     * @param PropPatch $propPatch
720
+     * @return void
721
+     */
722
+    function updateCalendar($calendarId, PropPatch $propPatch) {
723
+        $supportedProperties = array_keys($this->propertyMap);
724
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
725
+
726
+        /**
727
+         * @suppress SqlInjectionChecker
728
+         */
729
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
730
+            $newValues = [];
731
+            foreach ($mutations as $propertyName => $propertyValue) {
732
+
733
+                switch ($propertyName) {
734
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
735
+                        $fieldName = 'transparent';
736
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
737
+                        break;
738
+                    default :
739
+                        $fieldName = $this->propertyMap[$propertyName];
740
+                        $newValues[$fieldName] = $propertyValue;
741
+                        break;
742
+                }
743
+
744
+            }
745
+            $query = $this->db->getQueryBuilder();
746
+            $query->update('calendars');
747
+            foreach ($newValues as $fieldName => $value) {
748
+                $query->set($fieldName, $query->createNamedParameter($value));
749
+            }
750
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
751
+            $query->execute();
752
+
753
+            $this->addChange($calendarId, "", 2);
754
+
755
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
756
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
757
+                [
758
+                    'calendarId' => $calendarId,
759
+                    'calendarData' => $this->getCalendarById($calendarId),
760
+                    'shares' => $this->getShares($calendarId),
761
+                    'propertyMutations' => $mutations,
762
+            ]));
763
+
764
+            return true;
765
+        });
766
+    }
767
+
768
+    /**
769
+     * Delete a calendar and all it's objects
770
+     *
771
+     * @param mixed $calendarId
772
+     * @return void
773
+     */
774
+    function deleteCalendar($calendarId) {
775
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
776
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
777
+            [
778
+                'calendarId' => $calendarId,
779
+                'calendarData' => $this->getCalendarById($calendarId),
780
+                'shares' => $this->getShares($calendarId),
781
+        ]));
782
+
783
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
784
+        $stmt->execute([$calendarId]);
785
+
786
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
787
+        $stmt->execute([$calendarId]);
788
+
789
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
790
+        $stmt->execute([$calendarId]);
791
+
792
+        $this->sharingBackend->deleteAllShares($calendarId);
793
+
794
+        $query = $this->db->getQueryBuilder();
795
+        $query->delete($this->dbObjectPropertiesTable)
796
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
797
+            ->execute();
798
+    }
799
+
800
+    /**
801
+     * Delete all of an user's shares
802
+     *
803
+     * @param string $principaluri
804
+     * @return void
805
+     */
806
+    function deleteAllSharesByUser($principaluri) {
807
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
808
+    }
809
+
810
+    /**
811
+     * Returns all calendar objects within a calendar.
812
+     *
813
+     * Every item contains an array with the following keys:
814
+     *   * calendardata - The iCalendar-compatible calendar data
815
+     *   * uri - a unique key which will be used to construct the uri. This can
816
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
817
+     *     good idea. This is only the basename, or filename, not the full
818
+     *     path.
819
+     *   * lastmodified - a timestamp of the last modification time
820
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
821
+     *   '"abcdef"')
822
+     *   * size - The size of the calendar objects, in bytes.
823
+     *   * component - optional, a string containing the type of object, such
824
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
825
+     *     the Content-Type header.
826
+     *
827
+     * Note that the etag is optional, but it's highly encouraged to return for
828
+     * speed reasons.
829
+     *
830
+     * The calendardata is also optional. If it's not returned
831
+     * 'getCalendarObject' will be called later, which *is* expected to return
832
+     * calendardata.
833
+     *
834
+     * If neither etag or size are specified, the calendardata will be
835
+     * used/fetched to determine these numbers. If both are specified the
836
+     * amount of times this is needed is reduced by a great degree.
837
+     *
838
+     * @param mixed $calendarId
839
+     * @return array
840
+     */
841
+    function getCalendarObjects($calendarId) {
842
+        $query = $this->db->getQueryBuilder();
843
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
844
+            ->from('calendarobjects')
845
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
846
+        $stmt = $query->execute();
847
+
848
+        $result = [];
849
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
850
+            $result[] = [
851
+                    'id'           => $row['id'],
852
+                    'uri'          => $row['uri'],
853
+                    'lastmodified' => $row['lastmodified'],
854
+                    'etag'         => '"' . $row['etag'] . '"',
855
+                    'calendarid'   => $row['calendarid'],
856
+                    'size'         => (int)$row['size'],
857
+                    'component'    => strtolower($row['componenttype']),
858
+                    'classification'=> (int)$row['classification']
859
+            ];
860
+        }
861
+
862
+        return $result;
863
+    }
864
+
865
+    /**
866
+     * Returns information from a single calendar object, based on it's object
867
+     * uri.
868
+     *
869
+     * The object uri is only the basename, or filename and not a full path.
870
+     *
871
+     * The returned array must have the same keys as getCalendarObjects. The
872
+     * 'calendardata' object is required here though, while it's not required
873
+     * for getCalendarObjects.
874
+     *
875
+     * This method must return null if the object did not exist.
876
+     *
877
+     * @param mixed $calendarId
878
+     * @param string $objectUri
879
+     * @return array|null
880
+     */
881
+    function getCalendarObject($calendarId, $objectUri) {
882
+
883
+        $query = $this->db->getQueryBuilder();
884
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
885
+                ->from('calendarobjects')
886
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
887
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
888
+        $stmt = $query->execute();
889
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
890
+
891
+        if(!$row) return null;
892
+
893
+        return [
894
+                'id'            => $row['id'],
895
+                'uri'           => $row['uri'],
896
+                'lastmodified'  => $row['lastmodified'],
897
+                'etag'          => '"' . $row['etag'] . '"',
898
+                'calendarid'    => $row['calendarid'],
899
+                'size'          => (int)$row['size'],
900
+                'calendardata'  => $this->readBlob($row['calendardata']),
901
+                'component'     => strtolower($row['componenttype']),
902
+                'classification'=> (int)$row['classification']
903
+        ];
904
+    }
905
+
906
+    /**
907
+     * Returns a list of calendar objects.
908
+     *
909
+     * This method should work identical to getCalendarObject, but instead
910
+     * return all the calendar objects in the list as an array.
911
+     *
912
+     * If the backend supports this, it may allow for some speed-ups.
913
+     *
914
+     * @param mixed $calendarId
915
+     * @param string[] $uris
916
+     * @return array
917
+     */
918
+    function getMultipleCalendarObjects($calendarId, array $uris) {
919
+        if (empty($uris)) {
920
+            return [];
921
+        }
922
+
923
+        $chunks = array_chunk($uris, 100);
924
+        $objects = [];
925
+
926
+        $query = $this->db->getQueryBuilder();
927
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
928
+            ->from('calendarobjects')
929
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
930
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
931
+
932
+        foreach ($chunks as $uris) {
933
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
934
+            $result = $query->execute();
935
+
936
+            while ($row = $result->fetch()) {
937
+                $objects[] = [
938
+                    'id'           => $row['id'],
939
+                    'uri'          => $row['uri'],
940
+                    'lastmodified' => $row['lastmodified'],
941
+                    'etag'         => '"' . $row['etag'] . '"',
942
+                    'calendarid'   => $row['calendarid'],
943
+                    'size'         => (int)$row['size'],
944
+                    'calendardata' => $this->readBlob($row['calendardata']),
945
+                    'component'    => strtolower($row['componenttype']),
946
+                    'classification' => (int)$row['classification']
947
+                ];
948
+            }
949
+            $result->closeCursor();
950
+        }
951
+        return $objects;
952
+    }
953
+
954
+    /**
955
+     * Creates a new calendar object.
956
+     *
957
+     * The object uri is only the basename, or filename and not a full path.
958
+     *
959
+     * It is possible return an etag from this function, which will be used in
960
+     * the response to this PUT request. Note that the ETag must be surrounded
961
+     * by double-quotes.
962
+     *
963
+     * However, you should only really return this ETag if you don't mangle the
964
+     * calendar-data. If the result of a subsequent GET to this object is not
965
+     * the exact same as this request body, you should omit the ETag.
966
+     *
967
+     * @param mixed $calendarId
968
+     * @param string $objectUri
969
+     * @param string $calendarData
970
+     * @return string
971
+     */
972
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
973
+        $extraData = $this->getDenormalizedData($calendarData);
974
+
975
+        $q = $this->db->getQueryBuilder();
976
+        $q->select($q->createFunction('COUNT(*)'))
977
+            ->from('calendarobjects')
978
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
979
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
980
+
981
+        $result = $q->execute();
982
+        $count = (int) $result->fetchColumn();
983
+        $result->closeCursor();
984
+
985
+        if ($count !== 0) {
986
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
987
+        }
988
+
989
+        $query = $this->db->getQueryBuilder();
990
+        $query->insert('calendarobjects')
991
+            ->values([
992
+                'calendarid' => $query->createNamedParameter($calendarId),
993
+                'uri' => $query->createNamedParameter($objectUri),
994
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
995
+                'lastmodified' => $query->createNamedParameter(time()),
996
+                'etag' => $query->createNamedParameter($extraData['etag']),
997
+                'size' => $query->createNamedParameter($extraData['size']),
998
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
999
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1000
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1001
+                'classification' => $query->createNamedParameter($extraData['classification']),
1002
+                'uid' => $query->createNamedParameter($extraData['uid']),
1003
+            ])
1004
+            ->execute();
1005
+
1006
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1007
+
1008
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1009
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1010
+            [
1011
+                'calendarId' => $calendarId,
1012
+                'calendarData' => $this->getCalendarById($calendarId),
1013
+                'shares' => $this->getShares($calendarId),
1014
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1015
+            ]
1016
+        ));
1017
+        $this->addChange($calendarId, $objectUri, 1);
1018
+
1019
+        return '"' . $extraData['etag'] . '"';
1020
+    }
1021
+
1022
+    /**
1023
+     * Updates an existing calendarobject, based on it's uri.
1024
+     *
1025
+     * The object uri is only the basename, or filename and not a full path.
1026
+     *
1027
+     * It is possible return an etag from this function, which will be used in
1028
+     * the response to this PUT request. Note that the ETag must be surrounded
1029
+     * by double-quotes.
1030
+     *
1031
+     * However, you should only really return this ETag if you don't mangle the
1032
+     * calendar-data. If the result of a subsequent GET to this object is not
1033
+     * the exact same as this request body, you should omit the ETag.
1034
+     *
1035
+     * @param mixed $calendarId
1036
+     * @param string $objectUri
1037
+     * @param string $calendarData
1038
+     * @return string
1039
+     */
1040
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1041
+        $extraData = $this->getDenormalizedData($calendarData);
1042
+
1043
+        $query = $this->db->getQueryBuilder();
1044
+        $query->update('calendarobjects')
1045
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1046
+                ->set('lastmodified', $query->createNamedParameter(time()))
1047
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1048
+                ->set('size', $query->createNamedParameter($extraData['size']))
1049
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1050
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1051
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1052
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1053
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1054
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1055
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1056
+            ->execute();
1057
+
1058
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1059
+
1060
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1061
+        if (is_array($data)) {
1062
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1063
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1064
+                [
1065
+                    'calendarId' => $calendarId,
1066
+                    'calendarData' => $this->getCalendarById($calendarId),
1067
+                    'shares' => $this->getShares($calendarId),
1068
+                    'objectData' => $data,
1069
+                ]
1070
+            ));
1071
+        }
1072
+        $this->addChange($calendarId, $objectUri, 2);
1073
+
1074
+        return '"' . $extraData['etag'] . '"';
1075
+    }
1076
+
1077
+    /**
1078
+     * @param int $calendarObjectId
1079
+     * @param int $classification
1080
+     */
1081
+    public function setClassification($calendarObjectId, $classification) {
1082
+        if (!in_array($classification, [
1083
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1084
+        ])) {
1085
+            throw new \InvalidArgumentException();
1086
+        }
1087
+        $query = $this->db->getQueryBuilder();
1088
+        $query->update('calendarobjects')
1089
+            ->set('classification', $query->createNamedParameter($classification))
1090
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1091
+            ->execute();
1092
+    }
1093
+
1094
+    /**
1095
+     * Deletes an existing calendar object.
1096
+     *
1097
+     * The object uri is only the basename, or filename and not a full path.
1098
+     *
1099
+     * @param mixed $calendarId
1100
+     * @param string $objectUri
1101
+     * @return void
1102
+     */
1103
+    function deleteCalendarObject($calendarId, $objectUri) {
1104
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1105
+        if (is_array($data)) {
1106
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1107
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1108
+                [
1109
+                    'calendarId' => $calendarId,
1110
+                    'calendarData' => $this->getCalendarById($calendarId),
1111
+                    'shares' => $this->getShares($calendarId),
1112
+                    'objectData' => $data,
1113
+                ]
1114
+            ));
1115
+        }
1116
+
1117
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1118
+        $stmt->execute([$calendarId, $objectUri]);
1119
+
1120
+        $this->purgeProperties($calendarId, $data['id']);
1121
+
1122
+        $this->addChange($calendarId, $objectUri, 3);
1123
+    }
1124
+
1125
+    /**
1126
+     * Performs a calendar-query on the contents of this calendar.
1127
+     *
1128
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1129
+     * calendar-query it is possible for a client to request a specific set of
1130
+     * object, based on contents of iCalendar properties, date-ranges and
1131
+     * iCalendar component types (VTODO, VEVENT).
1132
+     *
1133
+     * This method should just return a list of (relative) urls that match this
1134
+     * query.
1135
+     *
1136
+     * The list of filters are specified as an array. The exact array is
1137
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1138
+     *
1139
+     * Note that it is extremely likely that getCalendarObject for every path
1140
+     * returned from this method will be called almost immediately after. You
1141
+     * may want to anticipate this to speed up these requests.
1142
+     *
1143
+     * This method provides a default implementation, which parses *all* the
1144
+     * iCalendar objects in the specified calendar.
1145
+     *
1146
+     * This default may well be good enough for personal use, and calendars
1147
+     * that aren't very large. But if you anticipate high usage, big calendars
1148
+     * or high loads, you are strongly advised to optimize certain paths.
1149
+     *
1150
+     * The best way to do so is override this method and to optimize
1151
+     * specifically for 'common filters'.
1152
+     *
1153
+     * Requests that are extremely common are:
1154
+     *   * requests for just VEVENTS
1155
+     *   * requests for just VTODO
1156
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1157
+     *
1158
+     * ..and combinations of these requests. It may not be worth it to try to
1159
+     * handle every possible situation and just rely on the (relatively
1160
+     * easy to use) CalendarQueryValidator to handle the rest.
1161
+     *
1162
+     * Note that especially time-range-filters may be difficult to parse. A
1163
+     * time-range filter specified on a VEVENT must for instance also handle
1164
+     * recurrence rules correctly.
1165
+     * A good example of how to interprete all these filters can also simply
1166
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1167
+     * as possible, so it gives you a good idea on what type of stuff you need
1168
+     * to think of.
1169
+     *
1170
+     * @param mixed $calendarId
1171
+     * @param array $filters
1172
+     * @return array
1173
+     */
1174
+    function calendarQuery($calendarId, array $filters) {
1175
+        $componentType = null;
1176
+        $requirePostFilter = true;
1177
+        $timeRange = null;
1178
+
1179
+        // if no filters were specified, we don't need to filter after a query
1180
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1181
+            $requirePostFilter = false;
1182
+        }
1183
+
1184
+        // Figuring out if there's a component filter
1185
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1186
+            $componentType = $filters['comp-filters'][0]['name'];
1187
+
1188
+            // Checking if we need post-filters
1189
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1190
+                $requirePostFilter = false;
1191
+            }
1192
+            // There was a time-range filter
1193
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1194
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1195
+
1196
+                // If start time OR the end time is not specified, we can do a
1197
+                // 100% accurate mysql query.
1198
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1199
+                    $requirePostFilter = false;
1200
+                }
1201
+            }
1202
+
1203
+        }
1204
+        $columns = ['uri'];
1205
+        if ($requirePostFilter) {
1206
+            $columns = ['uri', 'calendardata'];
1207
+        }
1208
+        $query = $this->db->getQueryBuilder();
1209
+        $query->select($columns)
1210
+            ->from('calendarobjects')
1211
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1212
+
1213
+        if ($componentType) {
1214
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1215
+        }
1216
+
1217
+        if ($timeRange && $timeRange['start']) {
1218
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1219
+        }
1220
+        if ($timeRange && $timeRange['end']) {
1221
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1222
+        }
1223
+
1224
+        $stmt = $query->execute();
1225
+
1226
+        $result = [];
1227
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1228
+            if ($requirePostFilter) {
1229
+                // validateFilterForObject will parse the calendar data
1230
+                // catch parsing errors
1231
+                try {
1232
+                    $matches = $this->validateFilterForObject($row, $filters);
1233
+                } catch(ParseException $ex) {
1234
+                    $this->logger->logException($ex, [
1235
+                        'app' => 'dav',
1236
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1237
+                    ]);
1238
+                    continue;
1239
+                } catch (InvalidDataException $ex) {
1240
+                    $this->logger->logException($ex, [
1241
+                        'app' => 'dav',
1242
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1243
+                    ]);
1244
+                    continue;
1245
+                }
1246
+
1247
+                if (!$matches) {
1248
+                    continue;
1249
+                }
1250
+            }
1251
+            $result[] = $row['uri'];
1252
+        }
1253
+
1254
+        return $result;
1255
+    }
1256
+
1257
+    /**
1258
+     * custom Nextcloud search extension for CalDAV
1259
+     *
1260
+     * @param string $principalUri
1261
+     * @param array $filters
1262
+     * @param integer|null $limit
1263
+     * @param integer|null $offset
1264
+     * @return array
1265
+     */
1266
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1267
+        $calendars = $this->getCalendarsForUser($principalUri);
1268
+        $ownCalendars = [];
1269
+        $sharedCalendars = [];
1270
+
1271
+        $uriMapper = [];
1272
+
1273
+        foreach($calendars as $calendar) {
1274
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1275
+                $ownCalendars[] = $calendar['id'];
1276
+            } else {
1277
+                $sharedCalendars[] = $calendar['id'];
1278
+            }
1279
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1280
+        }
1281
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1282
+            return [];
1283
+        }
1284
+
1285
+        $query = $this->db->getQueryBuilder();
1286
+        // Calendar id expressions
1287
+        $calendarExpressions = [];
1288
+        foreach($ownCalendars as $id) {
1289
+            $calendarExpressions[] = $query->expr()
1290
+                ->eq('c.calendarid', $query->createNamedParameter($id));
1291
+        }
1292
+        foreach($sharedCalendars as $id) {
1293
+            $calendarExpressions[] = $query->expr()->andX(
1294
+                $query->expr()->eq('c.calendarid',
1295
+                    $query->createNamedParameter($id)),
1296
+                $query->expr()->eq('c.classification',
1297
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1298
+            );
1299
+        }
1300
+
1301
+        if (count($calendarExpressions) === 1) {
1302
+            $calExpr = $calendarExpressions[0];
1303
+        } else {
1304
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1305
+        }
1306
+
1307
+        // Component expressions
1308
+        $compExpressions = [];
1309
+        foreach($filters['comps'] as $comp) {
1310
+            $compExpressions[] = $query->expr()
1311
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1312
+        }
1313
+
1314
+        if (count($compExpressions) === 1) {
1315
+            $compExpr = $compExpressions[0];
1316
+        } else {
1317
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1318
+        }
1319
+
1320
+        if (!isset($filters['props'])) {
1321
+            $filters['props'] = [];
1322
+        }
1323
+        if (!isset($filters['params'])) {
1324
+            $filters['params'] = [];
1325
+        }
1326
+
1327
+        $propParamExpressions = [];
1328
+        foreach($filters['props'] as $prop) {
1329
+            $propParamExpressions[] = $query->expr()->andX(
1330
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1331
+                $query->expr()->isNull('i.parameter')
1332
+            );
1333
+        }
1334
+        foreach($filters['params'] as $param) {
1335
+            $propParamExpressions[] = $query->expr()->andX(
1336
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1337
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1338
+            );
1339
+        }
1340
+
1341
+        if (count($propParamExpressions) === 1) {
1342
+            $propParamExpr = $propParamExpressions[0];
1343
+        } else {
1344
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1345
+        }
1346
+
1347
+        $query->select(['c.calendarid', 'c.uri'])
1348
+            ->from($this->dbObjectPropertiesTable, 'i')
1349
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1350
+            ->where($calExpr)
1351
+            ->andWhere($compExpr)
1352
+            ->andWhere($propParamExpr)
1353
+            ->andWhere($query->expr()->iLike('i.value',
1354
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1355
+
1356
+        if ($offset) {
1357
+            $query->setFirstResult($offset);
1358
+        }
1359
+        if ($limit) {
1360
+            $query->setMaxResults($limit);
1361
+        }
1362
+
1363
+        $stmt = $query->execute();
1364
+
1365
+        $result = [];
1366
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1367
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1368
+            if (!in_array($path, $result)) {
1369
+                $result[] = $path;
1370
+            }
1371
+        }
1372
+
1373
+        return $result;
1374
+    }
1375
+
1376
+    /**
1377
+     * used for Nextcloud's calendar API
1378
+     *
1379
+     * @param array $calendarInfo
1380
+     * @param string $pattern
1381
+     * @param array $searchProperties
1382
+     * @param array $options
1383
+     * @param integer|null $limit
1384
+     * @param integer|null $offset
1385
+     *
1386
+     * @return array
1387
+     */
1388
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1389
+                            array $options, $limit, $offset) {
1390
+        $outerQuery = $this->db->getQueryBuilder();
1391
+        $innerQuery = $this->db->getQueryBuilder();
1392
+
1393
+        $innerQuery->selectDistinct('op.objectid')
1394
+            ->from($this->dbObjectPropertiesTable, 'op')
1395
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1396
+                $outerQuery->createNamedParameter($calendarInfo['id'])));
1397
+
1398
+        // only return public items for shared calendars for now
1399
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1400
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1401
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1402
+        }
1403
+
1404
+        $or = $innerQuery->expr()->orX();
1405
+        foreach($searchProperties as $searchProperty) {
1406
+            $or->add($innerQuery->expr()->eq('op.name',
1407
+                $outerQuery->createNamedParameter($searchProperty)));
1408
+        }
1409
+        $innerQuery->andWhere($or);
1410
+
1411
+        if ($pattern !== '') {
1412
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1413
+                $outerQuery->createNamedParameter('%' .
1414
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1415
+        }
1416
+
1417
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1418
+            ->from('calendarobjects', 'c');
1419
+
1420
+        if (isset($options['timerange'])) {
1421
+            if (isset($options['timerange']['start'])) {
1422
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1423
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1424
+
1425
+            }
1426
+            if (isset($options['timerange']['end'])) {
1427
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1428
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1429
+            }
1430
+        }
1431
+
1432
+        if (isset($options['types'])) {
1433
+            $or = $outerQuery->expr()->orX();
1434
+            foreach($options['types'] as $type) {
1435
+                $or->add($outerQuery->expr()->eq('componenttype',
1436
+                    $outerQuery->createNamedParameter($type)));
1437
+            }
1438
+            $outerQuery->andWhere($or);
1439
+        }
1440
+
1441
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1442
+            $outerQuery->createFunction($innerQuery->getSQL())));
1443
+
1444
+        if ($offset) {
1445
+            $outerQuery->setFirstResult($offset);
1446
+        }
1447
+        if ($limit) {
1448
+            $outerQuery->setMaxResults($limit);
1449
+        }
1450
+
1451
+        $result = $outerQuery->execute();
1452
+        $calendarObjects = $result->fetchAll();
1453
+
1454
+        return array_map(function($o) {
1455
+            $calendarData = Reader::read($o['calendardata']);
1456
+            $comps = $calendarData->getComponents();
1457
+            $objects = [];
1458
+            $timezones = [];
1459
+            foreach($comps as $comp) {
1460
+                if ($comp instanceof VTimeZone) {
1461
+                    $timezones[] = $comp;
1462
+                } else {
1463
+                    $objects[] = $comp;
1464
+                }
1465
+            }
1466
+
1467
+            return [
1468
+                'id' => $o['id'],
1469
+                'type' => $o['componenttype'],
1470
+                'uid' => $o['uid'],
1471
+                'uri' => $o['uri'],
1472
+                'objects' => array_map(function($c) {
1473
+                    return $this->transformSearchData($c);
1474
+                }, $objects),
1475
+                'timezones' => array_map(function($c) {
1476
+                    return $this->transformSearchData($c);
1477
+                }, $timezones),
1478
+            ];
1479
+        }, $calendarObjects);
1480
+    }
1481
+
1482
+    /**
1483
+     * @param Component $comp
1484
+     * @return array
1485
+     */
1486
+    private function transformSearchData(Component $comp) {
1487
+        $data = [];
1488
+        /** @var Component[] $subComponents */
1489
+        $subComponents = $comp->getComponents();
1490
+        /** @var Property[] $properties */
1491
+        $properties = array_filter($comp->children(), function($c) {
1492
+            return $c instanceof Property;
1493
+        });
1494
+        $validationRules = $comp->getValidationRules();
1495
+
1496
+        foreach($subComponents as $subComponent) {
1497
+            $name = $subComponent->name;
1498
+            if (!isset($data[$name])) {
1499
+                $data[$name] = [];
1500
+            }
1501
+            $data[$name][] = $this->transformSearchData($subComponent);
1502
+        }
1503
+
1504
+        foreach($properties as $property) {
1505
+            $name = $property->name;
1506
+            if (!isset($validationRules[$name])) {
1507
+                $validationRules[$name] = '*';
1508
+            }
1509
+
1510
+            $rule = $validationRules[$property->name];
1511
+            if ($rule === '+' || $rule === '*') { // multiple
1512
+                if (!isset($data[$name])) {
1513
+                    $data[$name] = [];
1514
+                }
1515
+
1516
+                $data[$name][] = $this->transformSearchProperty($property);
1517
+            } else { // once
1518
+                $data[$name] = $this->transformSearchProperty($property);
1519
+            }
1520
+        }
1521
+
1522
+        return $data;
1523
+    }
1524
+
1525
+    /**
1526
+     * @param Property $prop
1527
+     * @return array
1528
+     */
1529
+    private function transformSearchProperty(Property $prop) {
1530
+        // No need to check Date, as it extends DateTime
1531
+        if ($prop instanceof Property\ICalendar\DateTime) {
1532
+            $value = $prop->getDateTime();
1533
+        } else {
1534
+            $value = $prop->getValue();
1535
+        }
1536
+
1537
+        return [
1538
+            $value,
1539
+            $prop->parameters()
1540
+        ];
1541
+    }
1542
+
1543
+    /**
1544
+     * Searches through all of a users calendars and calendar objects to find
1545
+     * an object with a specific UID.
1546
+     *
1547
+     * This method should return the path to this object, relative to the
1548
+     * calendar home, so this path usually only contains two parts:
1549
+     *
1550
+     * calendarpath/objectpath.ics
1551
+     *
1552
+     * If the uid is not found, return null.
1553
+     *
1554
+     * This method should only consider * objects that the principal owns, so
1555
+     * any calendars owned by other principals that also appear in this
1556
+     * collection should be ignored.
1557
+     *
1558
+     * @param string $principalUri
1559
+     * @param string $uid
1560
+     * @return string|null
1561
+     */
1562
+    function getCalendarObjectByUID($principalUri, $uid) {
1563
+
1564
+        $query = $this->db->getQueryBuilder();
1565
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1566
+            ->from('calendarobjects', 'co')
1567
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1568
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1569
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1570
+
1571
+        $stmt = $query->execute();
1572
+
1573
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1574
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1575
+        }
1576
+
1577
+        return null;
1578
+    }
1579
+
1580
+    /**
1581
+     * The getChanges method returns all the changes that have happened, since
1582
+     * the specified syncToken in the specified calendar.
1583
+     *
1584
+     * This function should return an array, such as the following:
1585
+     *
1586
+     * [
1587
+     *   'syncToken' => 'The current synctoken',
1588
+     *   'added'   => [
1589
+     *      'new.txt',
1590
+     *   ],
1591
+     *   'modified'   => [
1592
+     *      'modified.txt',
1593
+     *   ],
1594
+     *   'deleted' => [
1595
+     *      'foo.php.bak',
1596
+     *      'old.txt'
1597
+     *   ]
1598
+     * );
1599
+     *
1600
+     * The returned syncToken property should reflect the *current* syncToken
1601
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1602
+     * property This is * needed here too, to ensure the operation is atomic.
1603
+     *
1604
+     * If the $syncToken argument is specified as null, this is an initial
1605
+     * sync, and all members should be reported.
1606
+     *
1607
+     * The modified property is an array of nodenames that have changed since
1608
+     * the last token.
1609
+     *
1610
+     * The deleted property is an array with nodenames, that have been deleted
1611
+     * from collection.
1612
+     *
1613
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1614
+     * 1, you only have to report changes that happened only directly in
1615
+     * immediate descendants. If it's 2, it should also include changes from
1616
+     * the nodes below the child collections. (grandchildren)
1617
+     *
1618
+     * The $limit argument allows a client to specify how many results should
1619
+     * be returned at most. If the limit is not specified, it should be treated
1620
+     * as infinite.
1621
+     *
1622
+     * If the limit (infinite or not) is higher than you're willing to return,
1623
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1624
+     *
1625
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1626
+     * return null.
1627
+     *
1628
+     * The limit is 'suggestive'. You are free to ignore it.
1629
+     *
1630
+     * @param string $calendarId
1631
+     * @param string $syncToken
1632
+     * @param int $syncLevel
1633
+     * @param int $limit
1634
+     * @return array
1635
+     */
1636
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1637
+        // Current synctoken
1638
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1639
+        $stmt->execute([ $calendarId ]);
1640
+        $currentToken = $stmt->fetchColumn(0);
1641
+
1642
+        if (is_null($currentToken)) {
1643
+            return null;
1644
+        }
1645
+
1646
+        $result = [
1647
+            'syncToken' => $currentToken,
1648
+            'added'     => [],
1649
+            'modified'  => [],
1650
+            'deleted'   => [],
1651
+        ];
1652
+
1653
+        if ($syncToken) {
1654
+
1655
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1656
+            if ($limit>0) {
1657
+                $query.= " LIMIT " . (int)$limit;
1658
+            }
1659
+
1660
+            // Fetching all changes
1661
+            $stmt = $this->db->prepare($query);
1662
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1663
+
1664
+            $changes = [];
1665
+
1666
+            // This loop ensures that any duplicates are overwritten, only the
1667
+            // last change on a node is relevant.
1668
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1669
+
1670
+                $changes[$row['uri']] = $row['operation'];
1671
+
1672
+            }
1673
+
1674
+            foreach($changes as $uri => $operation) {
1675
+
1676
+                switch($operation) {
1677
+                    case 1 :
1678
+                        $result['added'][] = $uri;
1679
+                        break;
1680
+                    case 2 :
1681
+                        $result['modified'][] = $uri;
1682
+                        break;
1683
+                    case 3 :
1684
+                        $result['deleted'][] = $uri;
1685
+                        break;
1686
+                }
1687
+
1688
+            }
1689
+        } else {
1690
+            // No synctoken supplied, this is the initial sync.
1691
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1692
+            $stmt = $this->db->prepare($query);
1693
+            $stmt->execute([$calendarId]);
1694
+
1695
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1696
+        }
1697
+        return $result;
1698
+
1699
+    }
1700
+
1701
+    /**
1702
+     * Returns a list of subscriptions for a principal.
1703
+     *
1704
+     * Every subscription is an array with the following keys:
1705
+     *  * id, a unique id that will be used by other functions to modify the
1706
+     *    subscription. This can be the same as the uri or a database key.
1707
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1708
+     *  * principaluri. The owner of the subscription. Almost always the same as
1709
+     *    principalUri passed to this method.
1710
+     *
1711
+     * Furthermore, all the subscription info must be returned too:
1712
+     *
1713
+     * 1. {DAV:}displayname
1714
+     * 2. {http://apple.com/ns/ical/}refreshrate
1715
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1716
+     *    should not be stripped).
1717
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1718
+     *    should not be stripped).
1719
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1720
+     *    attachments should not be stripped).
1721
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1722
+     *     Sabre\DAV\Property\Href).
1723
+     * 7. {http://apple.com/ns/ical/}calendar-color
1724
+     * 8. {http://apple.com/ns/ical/}calendar-order
1725
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1726
+     *    (should just be an instance of
1727
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1728
+     *    default components).
1729
+     *
1730
+     * @param string $principalUri
1731
+     * @return array
1732
+     */
1733
+    function getSubscriptionsForUser($principalUri) {
1734
+        $fields = array_values($this->subscriptionPropertyMap);
1735
+        $fields[] = 'id';
1736
+        $fields[] = 'uri';
1737
+        $fields[] = 'source';
1738
+        $fields[] = 'principaluri';
1739
+        $fields[] = 'lastmodified';
1740
+
1741
+        $query = $this->db->getQueryBuilder();
1742
+        $query->select($fields)
1743
+            ->from('calendarsubscriptions')
1744
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1745
+            ->orderBy('calendarorder', 'asc');
1746
+        $stmt =$query->execute();
1747
+
1748
+        $subscriptions = [];
1749
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1750
+
1751
+            $subscription = [
1752
+                'id'           => $row['id'],
1753
+                'uri'          => $row['uri'],
1754
+                'principaluri' => $row['principaluri'],
1755
+                'source'       => $row['source'],
1756
+                'lastmodified' => $row['lastmodified'],
1757
+
1758
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1759
+            ];
1760
+
1761
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1762
+                if (!is_null($row[$dbName])) {
1763
+                    $subscription[$xmlName] = $row[$dbName];
1764
+                }
1765
+            }
1766
+
1767
+            $subscriptions[] = $subscription;
1768
+
1769
+        }
1770
+
1771
+        return $subscriptions;
1772
+    }
1773
+
1774
+    /**
1775
+     * Creates a new subscription for a principal.
1776
+     *
1777
+     * If the creation was a success, an id must be returned that can be used to reference
1778
+     * this subscription in other methods, such as updateSubscription.
1779
+     *
1780
+     * @param string $principalUri
1781
+     * @param string $uri
1782
+     * @param array $properties
1783
+     * @return mixed
1784
+     */
1785
+    function createSubscription($principalUri, $uri, array $properties) {
1786
+
1787
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1788
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1789
+        }
1790
+
1791
+        $values = [
1792
+            'principaluri' => $principalUri,
1793
+            'uri'          => $uri,
1794
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1795
+            'lastmodified' => time(),
1796
+        ];
1797
+
1798
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1799
+
1800
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1801
+            if (array_key_exists($xmlName, $properties)) {
1802
+                    $values[$dbName] = $properties[$xmlName];
1803
+                    if (in_array($dbName, $propertiesBoolean)) {
1804
+                        $values[$dbName] = true;
1805
+                }
1806
+            }
1807
+        }
1808
+
1809
+        $valuesToInsert = array();
1810
+
1811
+        $query = $this->db->getQueryBuilder();
1812
+
1813
+        foreach (array_keys($values) as $name) {
1814
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1815
+        }
1816
+
1817
+        $query->insert('calendarsubscriptions')
1818
+            ->values($valuesToInsert)
1819
+            ->execute();
1820
+
1821
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1822
+    }
1823
+
1824
+    /**
1825
+     * Updates a subscription
1826
+     *
1827
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1828
+     * To do the actual updates, you must tell this object which properties
1829
+     * you're going to process with the handle() method.
1830
+     *
1831
+     * Calling the handle method is like telling the PropPatch object "I
1832
+     * promise I can handle updating this property".
1833
+     *
1834
+     * Read the PropPatch documentation for more info and examples.
1835
+     *
1836
+     * @param mixed $subscriptionId
1837
+     * @param PropPatch $propPatch
1838
+     * @return void
1839
+     */
1840
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1841
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1842
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1843
+
1844
+        /**
1845
+         * @suppress SqlInjectionChecker
1846
+         */
1847
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1848
+
1849
+            $newValues = [];
1850
+
1851
+            foreach($mutations as $propertyName=>$propertyValue) {
1852
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1853
+                    $newValues['source'] = $propertyValue->getHref();
1854
+                } else {
1855
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1856
+                    $newValues[$fieldName] = $propertyValue;
1857
+                }
1858
+            }
1859
+
1860
+            $query = $this->db->getQueryBuilder();
1861
+            $query->update('calendarsubscriptions')
1862
+                ->set('lastmodified', $query->createNamedParameter(time()));
1863
+            foreach($newValues as $fieldName=>$value) {
1864
+                $query->set($fieldName, $query->createNamedParameter($value));
1865
+            }
1866
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1867
+                ->execute();
1868
+
1869
+            return true;
1870
+
1871
+        });
1872
+    }
1873
+
1874
+    /**
1875
+     * Deletes a subscription.
1876
+     *
1877
+     * @param mixed $subscriptionId
1878
+     * @return void
1879
+     */
1880
+    function deleteSubscription($subscriptionId) {
1881
+        $query = $this->db->getQueryBuilder();
1882
+        $query->delete('calendarsubscriptions')
1883
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1884
+            ->execute();
1885
+    }
1886
+
1887
+    /**
1888
+     * Returns a single scheduling object for the inbox collection.
1889
+     *
1890
+     * The returned array should contain the following elements:
1891
+     *   * uri - A unique basename for the object. This will be used to
1892
+     *           construct a full uri.
1893
+     *   * calendardata - The iCalendar object
1894
+     *   * lastmodified - The last modification date. Can be an int for a unix
1895
+     *                    timestamp, or a PHP DateTime object.
1896
+     *   * etag - A unique token that must change if the object changed.
1897
+     *   * size - The size of the object, in bytes.
1898
+     *
1899
+     * @param string $principalUri
1900
+     * @param string $objectUri
1901
+     * @return array
1902
+     */
1903
+    function getSchedulingObject($principalUri, $objectUri) {
1904
+        $query = $this->db->getQueryBuilder();
1905
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1906
+            ->from('schedulingobjects')
1907
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1908
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1909
+            ->execute();
1910
+
1911
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1912
+
1913
+        if(!$row) {
1914
+            return null;
1915
+        }
1916
+
1917
+        return [
1918
+                'uri'          => $row['uri'],
1919
+                'calendardata' => $row['calendardata'],
1920
+                'lastmodified' => $row['lastmodified'],
1921
+                'etag'         => '"' . $row['etag'] . '"',
1922
+                'size'         => (int)$row['size'],
1923
+        ];
1924
+    }
1925
+
1926
+    /**
1927
+     * Returns all scheduling objects for the inbox collection.
1928
+     *
1929
+     * These objects should be returned as an array. Every item in the array
1930
+     * should follow the same structure as returned from getSchedulingObject.
1931
+     *
1932
+     * The main difference is that 'calendardata' is optional.
1933
+     *
1934
+     * @param string $principalUri
1935
+     * @return array
1936
+     */
1937
+    function getSchedulingObjects($principalUri) {
1938
+        $query = $this->db->getQueryBuilder();
1939
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1940
+                ->from('schedulingobjects')
1941
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1942
+                ->execute();
1943
+
1944
+        $result = [];
1945
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1946
+            $result[] = [
1947
+                    'calendardata' => $row['calendardata'],
1948
+                    'uri'          => $row['uri'],
1949
+                    'lastmodified' => $row['lastmodified'],
1950
+                    'etag'         => '"' . $row['etag'] . '"',
1951
+                    'size'         => (int)$row['size'],
1952
+            ];
1953
+        }
1954
+
1955
+        return $result;
1956
+    }
1957
+
1958
+    /**
1959
+     * Deletes a scheduling object from the inbox collection.
1960
+     *
1961
+     * @param string $principalUri
1962
+     * @param string $objectUri
1963
+     * @return void
1964
+     */
1965
+    function deleteSchedulingObject($principalUri, $objectUri) {
1966
+        $query = $this->db->getQueryBuilder();
1967
+        $query->delete('schedulingobjects')
1968
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1969
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1970
+                ->execute();
1971
+    }
1972
+
1973
+    /**
1974
+     * Creates a new scheduling object. This should land in a users' inbox.
1975
+     *
1976
+     * @param string $principalUri
1977
+     * @param string $objectUri
1978
+     * @param string $objectData
1979
+     * @return void
1980
+     */
1981
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1982
+        $query = $this->db->getQueryBuilder();
1983
+        $query->insert('schedulingobjects')
1984
+            ->values([
1985
+                'principaluri' => $query->createNamedParameter($principalUri),
1986
+                'calendardata' => $query->createNamedParameter($objectData),
1987
+                'uri' => $query->createNamedParameter($objectUri),
1988
+                'lastmodified' => $query->createNamedParameter(time()),
1989
+                'etag' => $query->createNamedParameter(md5($objectData)),
1990
+                'size' => $query->createNamedParameter(strlen($objectData))
1991
+            ])
1992
+            ->execute();
1993
+    }
1994
+
1995
+    /**
1996
+     * Adds a change record to the calendarchanges table.
1997
+     *
1998
+     * @param mixed $calendarId
1999
+     * @param string $objectUri
2000
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2001
+     * @return void
2002
+     */
2003
+    protected function addChange($calendarId, $objectUri, $operation) {
2004
+
2005
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
2006
+        $stmt->execute([
2007
+            $objectUri,
2008
+            $calendarId,
2009
+            $operation,
2010
+            $calendarId
2011
+        ]);
2012
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
2013
+        $stmt->execute([
2014
+            $calendarId
2015
+        ]);
2016
+
2017
+    }
2018
+
2019
+    /**
2020
+     * Parses some information from calendar objects, used for optimized
2021
+     * calendar-queries.
2022
+     *
2023
+     * Returns an array with the following keys:
2024
+     *   * etag - An md5 checksum of the object without the quotes.
2025
+     *   * size - Size of the object in bytes
2026
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2027
+     *   * firstOccurence
2028
+     *   * lastOccurence
2029
+     *   * uid - value of the UID property
2030
+     *
2031
+     * @param string $calendarData
2032
+     * @return array
2033
+     */
2034
+    public function getDenormalizedData($calendarData) {
2035
+
2036
+        $vObject = Reader::read($calendarData);
2037
+        $componentType = null;
2038
+        $component = null;
2039
+        $firstOccurrence = null;
2040
+        $lastOccurrence = null;
2041
+        $uid = null;
2042
+        $classification = self::CLASSIFICATION_PUBLIC;
2043
+        foreach($vObject->getComponents() as $component) {
2044
+            if ($component->name!=='VTIMEZONE') {
2045
+                $componentType = $component->name;
2046
+                $uid = (string)$component->UID;
2047
+                break;
2048
+            }
2049
+        }
2050
+        if (!$componentType) {
2051
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2052
+        }
2053
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2054
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2055
+            // Finding the last occurrence is a bit harder
2056
+            if (!isset($component->RRULE)) {
2057
+                if (isset($component->DTEND)) {
2058
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2059
+                } elseif (isset($component->DURATION)) {
2060
+                    $endDate = clone $component->DTSTART->getDateTime();
2061
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2062
+                    $lastOccurrence = $endDate->getTimeStamp();
2063
+                } elseif (!$component->DTSTART->hasTime()) {
2064
+                    $endDate = clone $component->DTSTART->getDateTime();
2065
+                    $endDate->modify('+1 day');
2066
+                    $lastOccurrence = $endDate->getTimeStamp();
2067
+                } else {
2068
+                    $lastOccurrence = $firstOccurrence;
2069
+                }
2070
+            } else {
2071
+                $it = new EventIterator($vObject, (string)$component->UID);
2072
+                $maxDate = new \DateTime(self::MAX_DATE);
2073
+                if ($it->isInfinite()) {
2074
+                    $lastOccurrence = $maxDate->getTimestamp();
2075
+                } else {
2076
+                    $end = $it->getDtEnd();
2077
+                    while($it->valid() && $end < $maxDate) {
2078
+                        $end = $it->getDtEnd();
2079
+                        $it->next();
2080
+
2081
+                    }
2082
+                    $lastOccurrence = $end->getTimestamp();
2083
+                }
2084
+
2085
+            }
2086
+        }
2087
+
2088
+        if ($component->CLASS) {
2089
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2090
+            switch ($component->CLASS->getValue()) {
2091
+                case 'PUBLIC':
2092
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2093
+                    break;
2094
+                case 'CONFIDENTIAL':
2095
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2096
+                    break;
2097
+            }
2098
+        }
2099
+        return [
2100
+            'etag' => md5($calendarData),
2101
+            'size' => strlen($calendarData),
2102
+            'componentType' => $componentType,
2103
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2104
+            'lastOccurence'  => $lastOccurrence,
2105
+            'uid' => $uid,
2106
+            'classification' => $classification
2107
+        ];
2108
+
2109
+    }
2110
+
2111
+    private function readBlob($cardData) {
2112
+        if (is_resource($cardData)) {
2113
+            return stream_get_contents($cardData);
2114
+        }
2115
+
2116
+        return $cardData;
2117
+    }
2118
+
2119
+    /**
2120
+     * @param IShareable $shareable
2121
+     * @param array $add
2122
+     * @param array $remove
2123
+     */
2124
+    public function updateShares($shareable, $add, $remove) {
2125
+        $calendarId = $shareable->getResourceId();
2126
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2127
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2128
+            [
2129
+                'calendarId' => $calendarId,
2130
+                'calendarData' => $this->getCalendarById($calendarId),
2131
+                'shares' => $this->getShares($calendarId),
2132
+                'add' => $add,
2133
+                'remove' => $remove,
2134
+            ]));
2135
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
2136
+    }
2137
+
2138
+    /**
2139
+     * @param int $resourceId
2140
+     * @return array
2141
+     */
2142
+    public function getShares($resourceId) {
2143
+        return $this->sharingBackend->getShares($resourceId);
2144
+    }
2145
+
2146
+    /**
2147
+     * @param boolean $value
2148
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2149
+     * @return string|null
2150
+     */
2151
+    public function setPublishStatus($value, $calendar) {
2152
+
2153
+        $calendarId = $calendar->getResourceId();
2154
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2155
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2156
+            [
2157
+                'calendarId' => $calendarId,
2158
+                'calendarData' => $this->getCalendarById($calendarId),
2159
+                'public' => $value,
2160
+            ]));
2161
+
2162
+        $query = $this->db->getQueryBuilder();
2163
+        if ($value) {
2164
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2165
+            $query->insert('dav_shares')
2166
+                ->values([
2167
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2168
+                    'type' => $query->createNamedParameter('calendar'),
2169
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2170
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2171
+                    'publicuri' => $query->createNamedParameter($publicUri)
2172
+                ]);
2173
+            $query->execute();
2174
+            return $publicUri;
2175
+        }
2176
+        $query->delete('dav_shares')
2177
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2178
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2179
+        $query->execute();
2180
+        return null;
2181
+    }
2182
+
2183
+    /**
2184
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2185
+     * @return mixed
2186
+     */
2187
+    public function getPublishStatus($calendar) {
2188
+        $query = $this->db->getQueryBuilder();
2189
+        $result = $query->select('publicuri')
2190
+            ->from('dav_shares')
2191
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2192
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2193
+            ->execute();
2194
+
2195
+        $row = $result->fetch();
2196
+        $result->closeCursor();
2197
+        return $row ? reset($row) : false;
2198
+    }
2199
+
2200
+    /**
2201
+     * @param int $resourceId
2202
+     * @param array $acl
2203
+     * @return array
2204
+     */
2205
+    public function applyShareAcl($resourceId, $acl) {
2206
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
2207
+    }
2208
+
2209
+
2210
+
2211
+    /**
2212
+     * update properties table
2213
+     *
2214
+     * @param int $calendarId
2215
+     * @param string $objectUri
2216
+     * @param string $calendarData
2217
+     */
2218
+    public function updateProperties($calendarId, $objectUri, $calendarData) {
2219
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri);
2220
+
2221
+        try {
2222
+            $vCalendar = $this->readCalendarData($calendarData);
2223
+        } catch (\Exception $ex) {
2224
+            return;
2225
+        }
2226
+
2227
+        $this->purgeProperties($calendarId, $objectId);
2228
+
2229
+        $query = $this->db->getQueryBuilder();
2230
+        $query->insert($this->dbObjectPropertiesTable)
2231
+            ->values(
2232
+                [
2233
+                    'calendarid' => $query->createNamedParameter($calendarId),
2234
+                    'objectid' => $query->createNamedParameter($objectId),
2235
+                    'name' => $query->createParameter('name'),
2236
+                    'parameter' => $query->createParameter('parameter'),
2237
+                    'value' => $query->createParameter('value'),
2238
+                ]
2239
+            );
2240
+
2241
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2242
+        foreach ($vCalendar->getComponents() as $component) {
2243
+            if (!in_array($component->name, $indexComponents)) {
2244
+                continue;
2245
+            }
2246
+
2247
+            foreach ($component->children() as $property) {
2248
+                if (in_array($property->name, self::$indexProperties)) {
2249
+                    $value = $property->getValue();
2250
+                    // is this a shitty db?
2251
+                    if (!$this->db->supports4ByteText()) {
2252
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2253
+                    }
2254
+                    $value = substr($value, 0, 254);
2255
+
2256
+                    $query->setParameter('name', $property->name);
2257
+                    $query->setParameter('parameter', null);
2258
+                    $query->setParameter('value', $value);
2259
+                    $query->execute();
2260
+                }
2261
+
2262
+                if (array_key_exists($property->name, self::$indexParameters)) {
2263
+                    $parameters = $property->parameters();
2264
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2265
+
2266
+                    foreach ($parameters as $key => $value) {
2267
+                        if (in_array($key, $indexedParametersForProperty)) {
2268
+                            // is this a shitty db?
2269
+                            if ($this->db->supports4ByteText()) {
2270
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2271
+                            }
2272
+                            $value = substr($value, 0, 254);
2273
+
2274
+                            $query->setParameter('name', $property->name);
2275
+                            $query->setParameter('parameter', substr($key, 0, 254));
2276
+                            $query->setParameter('value', substr($value, 0, 254));
2277
+                            $query->execute();
2278
+                        }
2279
+                    }
2280
+                }
2281
+            }
2282
+        }
2283
+    }
2284
+
2285
+    /**
2286
+     * Move a calendar from one user to another
2287
+     *
2288
+     * @param string $uriName
2289
+     * @param string $uriOrigin
2290
+     * @param string $uriDestination
2291
+     */
2292
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2293
+    {
2294
+        $query = $this->db->getQueryBuilder();
2295
+        $query->update('calendars')
2296
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
2297
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2298
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2299
+            ->execute();
2300
+    }
2301
+
2302
+    /**
2303
+     * @param string $displayName
2304
+     * @param string|null $principalUri
2305
+     * @return array
2306
+     */
2307
+    public function findCalendarsUrisByDisplayName($displayName, $principalUri = null)
2308
+    {
2309
+        // Ideally $displayName would be sanitized the same way as stringUtility.js does in calendar
2310
+
2311
+        $query = $this->db->getQueryBuilder();
2312
+        $query->select('uri')
2313
+            ->from('calendars')
2314
+            ->where($query->expr()->iLike('displayname',
2315
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($displayName).'%')));
2316
+        if ($principalUri) {
2317
+            $query->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
2318
+        }
2319
+        $result = $query->execute();
2320
+
2321
+        $calendarUris = [];
2322
+        while($row = $result->fetch()) {
2323
+            $calendarUris[] = $row['uri'];
2324
+        }
2325
+        return $calendarUris;
2326
+    }
2327
+
2328
+    /**
2329
+     * deletes all birthday calendars
2330
+     */
2331
+    public function deleteAllBirthdayCalendars() {
2332
+        $query = $this->db->getQueryBuilder();
2333
+        $result = $query->select(['id'])->from('calendars')
2334
+            ->where($query->expr()->eq('uri',
2335
+                $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2336
+            ->execute();
2337
+
2338
+        $ids = $result->fetchAll();
2339
+        foreach($ids as $id) {
2340
+            $this->deleteCalendar($id['id']);
2341
+        }
2342
+    }
2343
+
2344
+    /**
2345
+     * read VCalendar data into a VCalendar object
2346
+     *
2347
+     * @param string $objectData
2348
+     * @return VCalendar
2349
+     */
2350
+    protected function readCalendarData($objectData) {
2351
+        return Reader::read($objectData);
2352
+    }
2353
+
2354
+    /**
2355
+     * delete all properties from a given calendar object
2356
+     *
2357
+     * @param int $calendarId
2358
+     * @param int $objectId
2359
+     */
2360
+    protected function purgeProperties($calendarId, $objectId) {
2361
+        $query = $this->db->getQueryBuilder();
2362
+        $query->delete($this->dbObjectPropertiesTable)
2363
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2364
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2365
+        $query->execute();
2366
+    }
2367
+
2368
+    /**
2369
+     * get ID from a given calendar object
2370
+     *
2371
+     * @param int $calendarId
2372
+     * @param string $uri
2373
+     * @return int
2374
+     */
2375
+    protected function getCalendarObjectId($calendarId, $uri) {
2376
+        $query = $this->db->getQueryBuilder();
2377
+        $query->select('id')->from('calendarobjects')
2378
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2379
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2380
+
2381
+        $result = $query->execute();
2382
+        $objectIds = $result->fetch();
2383
+        $result->closeCursor();
2384
+
2385
+        if (!isset($objectIds['id'])) {
2386
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2387
+        }
2388
+
2389
+        return (int)$objectIds['id'];
2390
+    }
2391
+
2392
+    private function convertPrincipal($principalUri, $toV2) {
2393
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2394
+            list(, $name) = Uri\split($principalUri);
2395
+            if ($toV2 === true) {
2396
+                return "principals/users/$name";
2397
+            }
2398
+            return "principals/$name";
2399
+        }
2400
+        return $principalUri;
2401
+    }
2402
+
2403
+    private function addOwnerPrincipal(&$calendarInfo) {
2404
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2405
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2406
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2407
+            $uri = $calendarInfo[$ownerPrincipalKey];
2408
+        } else {
2409
+            $uri = $calendarInfo['principaluri'];
2410
+        }
2411
+
2412
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2413
+        if (isset($principalInformation['{DAV:}displayname'])) {
2414
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2415
+        }
2416
+    }
2417 2417
 }
Please login to merge, or discard this patch.
apps/dav/lib/Command/ListCalendars.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -35,85 +35,85 @@
 block discarded – undo
35 35
 
36 36
 class ListCalendars extends Command {
37 37
 
38
-	/** @var IUserManager */
39
-	protected $userManager;
40
-
41
-	/** @var IGroupManager $groupManager */
42
-	private $groupManager;
43
-
44
-	/** @var \OCP\IDBConnection */
45
-	protected $dbConnection;
46
-
47
-	/**
48
-	 * @param IUserManager $userManager
49
-	 * @param IGroupManager $groupManager
50
-	 * @param IDBConnection $dbConnection
51
-	 */
52
-	function __construct(IUserManager $userManager, IGroupManager $groupManager, IDBConnection $dbConnection) {
53
-		parent::__construct();
54
-		$this->userManager = $userManager;
55
-		$this->groupManager = $groupManager;
56
-		$this->dbConnection = $dbConnection;
57
-	}
58
-
59
-	protected function configure() {
60
-		$this
61
-			->setName('dav:list-calendars')
62
-			->setDescription('List all calendars of a user')
63
-			->addArgument('user',
64
-				InputArgument::REQUIRED,
65
-				'User for whom all calendars will be listed');
66
-	}
67
-
68
-	protected function execute(InputInterface $input, OutputInterface $output) {
69
-		$user = $input->getArgument('user');
70
-		if (!$this->userManager->userExists($user)) {
71
-			throw new \InvalidArgumentException("User <$user> in unknown.");
72
-		}
73
-
74
-		$principalBackend = new Principal(
75
-			$this->userManager,
76
-			$this->groupManager,
77
-			\OC::$server->getShareManager(),
78
-			\OC::$server->getUserSession()
79
-		);
80
-		$random = \OC::$server->getSecureRandom();
81
-		$logger = \OC::$server->getLogger();
82
-		$dispatcher = \OC::$server->getEventDispatcher();
83
-
84
-		$caldav = new CalDavBackend($this->dbConnection, $principalBackend,
85
-			$this->userManager, $this->groupManager, $random, $logger,
86
-			$dispatcher);
87
-
88
-		$calendars = $caldav->getCalendarsForUser("principals/users/$user");
89
-
90
-		$calendarTableData = [];
91
-		foreach($calendars as $calendar) {
92
-			// skip birthday calendar
93
-			if ($calendar['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI) {
94
-				continue;
95
-			}
96
-
97
-			$readOnly = false;
98
-			$readOnlyIndex = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
99
-			if (isset($calendar[$readOnlyIndex])) {
100
-				$readOnly = $calendar[$readOnlyIndex];
101
-			}
102
-
103
-			$calendarTableData[] = [
104
-				$calendar['uri'],
105
-				$calendar['{DAV:}displayname'],
106
-				$calendar['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal'],
107
-				$calendar['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname'],
108
-				$readOnly ? ' x ' : ' ✓ ',
109
-			];
110
-		}
111
-
112
-		$table = new Table($output);
113
-		$table->setHeaders(['uri', 'displayname', 'owner\'s userid', 'owner\'s displayname', 'writable'])
114
-			->setRows($calendarTableData);
115
-
116
-		$table->render();
117
-	}
38
+    /** @var IUserManager */
39
+    protected $userManager;
40
+
41
+    /** @var IGroupManager $groupManager */
42
+    private $groupManager;
43
+
44
+    /** @var \OCP\IDBConnection */
45
+    protected $dbConnection;
46
+
47
+    /**
48
+     * @param IUserManager $userManager
49
+     * @param IGroupManager $groupManager
50
+     * @param IDBConnection $dbConnection
51
+     */
52
+    function __construct(IUserManager $userManager, IGroupManager $groupManager, IDBConnection $dbConnection) {
53
+        parent::__construct();
54
+        $this->userManager = $userManager;
55
+        $this->groupManager = $groupManager;
56
+        $this->dbConnection = $dbConnection;
57
+    }
58
+
59
+    protected function configure() {
60
+        $this
61
+            ->setName('dav:list-calendars')
62
+            ->setDescription('List all calendars of a user')
63
+            ->addArgument('user',
64
+                InputArgument::REQUIRED,
65
+                'User for whom all calendars will be listed');
66
+    }
67
+
68
+    protected function execute(InputInterface $input, OutputInterface $output) {
69
+        $user = $input->getArgument('user');
70
+        if (!$this->userManager->userExists($user)) {
71
+            throw new \InvalidArgumentException("User <$user> in unknown.");
72
+        }
73
+
74
+        $principalBackend = new Principal(
75
+            $this->userManager,
76
+            $this->groupManager,
77
+            \OC::$server->getShareManager(),
78
+            \OC::$server->getUserSession()
79
+        );
80
+        $random = \OC::$server->getSecureRandom();
81
+        $logger = \OC::$server->getLogger();
82
+        $dispatcher = \OC::$server->getEventDispatcher();
83
+
84
+        $caldav = new CalDavBackend($this->dbConnection, $principalBackend,
85
+            $this->userManager, $this->groupManager, $random, $logger,
86
+            $dispatcher);
87
+
88
+        $calendars = $caldav->getCalendarsForUser("principals/users/$user");
89
+
90
+        $calendarTableData = [];
91
+        foreach($calendars as $calendar) {
92
+            // skip birthday calendar
93
+            if ($calendar['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI) {
94
+                continue;
95
+            }
96
+
97
+            $readOnly = false;
98
+            $readOnlyIndex = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
99
+            if (isset($calendar[$readOnlyIndex])) {
100
+                $readOnly = $calendar[$readOnlyIndex];
101
+            }
102
+
103
+            $calendarTableData[] = [
104
+                $calendar['uri'],
105
+                $calendar['{DAV:}displayname'],
106
+                $calendar['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal'],
107
+                $calendar['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname'],
108
+                $readOnly ? ' x ' : ' ✓ ',
109
+            ];
110
+        }
111
+
112
+        $table = new Table($output);
113
+        $table->setHeaders(['uri', 'displayname', 'owner\'s userid', 'owner\'s displayname', 'writable'])
114
+            ->setRows($calendarTableData);
115
+
116
+        $table->render();
117
+    }
118 118
 
119 119
 }
Please login to merge, or discard this patch.