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