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