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