Completed
Pull Request — master (#9773)
by Georg
157:58 queued 131:31
created
apps/dav/lib/RootCollection.php 1 patch
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -39,118 +39,118 @@
 block discarded – undo
39 39
 
40 40
 class RootCollection extends SimpleCollection {
41 41
 
42
-	public function __construct() {
43
-		$config = \OC::$server->getConfig();
44
-		$l10n = \OC::$server->getL10N('dav');
45
-		$random = \OC::$server->getSecureRandom();
46
-		$logger = \OC::$server->getLogger();
47
-		$userManager = \OC::$server->getUserManager();
48
-		$userSession = \OC::$server->getUserSession();
49
-		$groupManager = \OC::$server->getGroupManager();
50
-		$shareManager = \OC::$server->getShareManager();
51
-		$db = \OC::$server->getDatabaseConnection();
52
-		$dispatcher = \OC::$server->getEventDispatcher();
53
-		$userPrincipalBackend = new Principal(
54
-			$userManager,
55
-			$groupManager,
56
-			$shareManager,
57
-			\OC::$server->getUserSession(),
58
-			$config
59
-		);
60
-		$groupPrincipalBackend = new GroupPrincipalBackend($groupManager);
61
-		$calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger);
62
-		$calendarRoomPrincipalBackend = new RoomPrincipalBackend($db, $userSession, $groupManager, $logger);
63
-		// as soon as debug mode is enabled we allow listing of principals
64
-		$disableListing = !$config->getSystemValue('debug', false);
65
-
66
-		// setup the first level of the dav tree
67
-		$userPrincipals = new Collection($userPrincipalBackend, 'principals/users');
68
-		$userPrincipals->disableListing = $disableListing;
69
-		$groupPrincipals = new Collection($groupPrincipalBackend, 'principals/groups');
70
-		$groupPrincipals->disableListing = $disableListing;
71
-		$systemPrincipals = new Collection(new SystemPrincipalBackend(), 'principals/system');
72
-		$systemPrincipals->disableListing = $disableListing;
73
-		$calendarResourcePrincipals = new Collection($calendarResourcePrincipalBackend, 'principals/calendar-resources');
74
-		$calendarResourcePrincipals->disableListing = $disableListing;
75
-		$calendarRoomPrincipals = new Collection($calendarRoomPrincipalBackend, 'principals/calendar-rooms');
76
-		$calendarRoomPrincipals->disableListing = $disableListing;
77
-
78
-
79
-		$filesCollection = new Files\RootCollection($userPrincipalBackend, 'principals/users');
80
-		$filesCollection->disableListing = $disableListing;
81
-		$caldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
82
-		$userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users');
83
-		$userCalendarRoot->disableListing = $disableListing;
84
-
85
-		$resourceCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
86
-		$resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources');
87
-		$resourceCalendarRoot->disableListing = $disableListing;
88
-		$roomCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
89
-		$roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $roomCalendarCaldavBackend, 'principals/calendar-rooms');
90
-		$roomCalendarRoot->disableListing = $disableListing;
91
-
92
-		$publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config);
93
-		$publicCalendarRoot->disableListing = $disableListing;
94
-
95
-		$systemTagCollection = new SystemTag\SystemTagsByIdCollection(
96
-			\OC::$server->getSystemTagManager(),
97
-			\OC::$server->getUserSession(),
98
-			$groupManager
99
-		);
100
-		$systemTagRelationsCollection = new SystemTag\SystemTagsRelationsCollection(
101
-			\OC::$server->getSystemTagManager(),
102
-			\OC::$server->getSystemTagObjectMapper(),
103
-			\OC::$server->getUserSession(),
104
-			$groupManager,
105
-			\OC::$server->getEventDispatcher()
106
-		);
107
-		$commentsCollection = new Comments\RootCollection(
108
-			\OC::$server->getCommentsManager(),
109
-			$userManager,
110
-			\OC::$server->getUserSession(),
111
-			\OC::$server->getEventDispatcher(),
112
-			\OC::$server->getLogger()
113
-		);
114
-
115
-		$usersCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
116
-		$usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, 'principals/users');
117
-		$usersAddressBookRoot->disableListing = $disableListing;
118
-
119
-		$systemCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
120
-		$systemAddressBookRoot = new AddressBookRoot(new SystemPrincipalBackend(), $systemCardDavBackend, 'principals/system');
121
-		$systemAddressBookRoot->disableListing = $disableListing;
122
-
123
-		$uploadCollection = new Upload\RootCollection($userPrincipalBackend, 'principals/users');
124
-		$uploadCollection->disableListing = $disableListing;
125
-
126
-		$avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users');
127
-		$avatarCollection->disableListing = $disableListing;
128
-
129
-		$children = [
130
-				new SimpleCollection('principals', [
131
-						$userPrincipals,
132
-						$groupPrincipals,
133
-						$systemPrincipals,
134
-						$calendarResourcePrincipals,
135
-						$calendarRoomPrincipals]),
136
-				$filesCollection,
137
-				$userCalendarRoot,
138
-				new SimpleCollection('system-calendars', [
139
-					$resourceCalendarRoot,
140
-					$roomCalendarRoot,
141
-				]),
142
-				$publicCalendarRoot,
143
-				new SimpleCollection('addressbooks', [
144
-						$usersAddressBookRoot,
145
-						$systemAddressBookRoot]),
146
-				$systemTagCollection,
147
-				$systemTagRelationsCollection,
148
-				$commentsCollection,
149
-				$uploadCollection,
150
-				$avatarCollection
151
-		];
152
-
153
-		parent::__construct('root', $children);
154
-	}
42
+    public function __construct() {
43
+        $config = \OC::$server->getConfig();
44
+        $l10n = \OC::$server->getL10N('dav');
45
+        $random = \OC::$server->getSecureRandom();
46
+        $logger = \OC::$server->getLogger();
47
+        $userManager = \OC::$server->getUserManager();
48
+        $userSession = \OC::$server->getUserSession();
49
+        $groupManager = \OC::$server->getGroupManager();
50
+        $shareManager = \OC::$server->getShareManager();
51
+        $db = \OC::$server->getDatabaseConnection();
52
+        $dispatcher = \OC::$server->getEventDispatcher();
53
+        $userPrincipalBackend = new Principal(
54
+            $userManager,
55
+            $groupManager,
56
+            $shareManager,
57
+            \OC::$server->getUserSession(),
58
+            $config
59
+        );
60
+        $groupPrincipalBackend = new GroupPrincipalBackend($groupManager);
61
+        $calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger);
62
+        $calendarRoomPrincipalBackend = new RoomPrincipalBackend($db, $userSession, $groupManager, $logger);
63
+        // as soon as debug mode is enabled we allow listing of principals
64
+        $disableListing = !$config->getSystemValue('debug', false);
65
+
66
+        // setup the first level of the dav tree
67
+        $userPrincipals = new Collection($userPrincipalBackend, 'principals/users');
68
+        $userPrincipals->disableListing = $disableListing;
69
+        $groupPrincipals = new Collection($groupPrincipalBackend, 'principals/groups');
70
+        $groupPrincipals->disableListing = $disableListing;
71
+        $systemPrincipals = new Collection(new SystemPrincipalBackend(), 'principals/system');
72
+        $systemPrincipals->disableListing = $disableListing;
73
+        $calendarResourcePrincipals = new Collection($calendarResourcePrincipalBackend, 'principals/calendar-resources');
74
+        $calendarResourcePrincipals->disableListing = $disableListing;
75
+        $calendarRoomPrincipals = new Collection($calendarRoomPrincipalBackend, 'principals/calendar-rooms');
76
+        $calendarRoomPrincipals->disableListing = $disableListing;
77
+
78
+
79
+        $filesCollection = new Files\RootCollection($userPrincipalBackend, 'principals/users');
80
+        $filesCollection->disableListing = $disableListing;
81
+        $caldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
82
+        $userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users');
83
+        $userCalendarRoot->disableListing = $disableListing;
84
+
85
+        $resourceCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
86
+        $resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources');
87
+        $resourceCalendarRoot->disableListing = $disableListing;
88
+        $roomCalendarCaldavBackend = new CalDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $random, $logger, $dispatcher);
89
+        $roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $roomCalendarCaldavBackend, 'principals/calendar-rooms');
90
+        $roomCalendarRoot->disableListing = $disableListing;
91
+
92
+        $publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config);
93
+        $publicCalendarRoot->disableListing = $disableListing;
94
+
95
+        $systemTagCollection = new SystemTag\SystemTagsByIdCollection(
96
+            \OC::$server->getSystemTagManager(),
97
+            \OC::$server->getUserSession(),
98
+            $groupManager
99
+        );
100
+        $systemTagRelationsCollection = new SystemTag\SystemTagsRelationsCollection(
101
+            \OC::$server->getSystemTagManager(),
102
+            \OC::$server->getSystemTagObjectMapper(),
103
+            \OC::$server->getUserSession(),
104
+            $groupManager,
105
+            \OC::$server->getEventDispatcher()
106
+        );
107
+        $commentsCollection = new Comments\RootCollection(
108
+            \OC::$server->getCommentsManager(),
109
+            $userManager,
110
+            \OC::$server->getUserSession(),
111
+            \OC::$server->getEventDispatcher(),
112
+            \OC::$server->getLogger()
113
+        );
114
+
115
+        $usersCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
116
+        $usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, 'principals/users');
117
+        $usersAddressBookRoot->disableListing = $disableListing;
118
+
119
+        $systemCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher);
120
+        $systemAddressBookRoot = new AddressBookRoot(new SystemPrincipalBackend(), $systemCardDavBackend, 'principals/system');
121
+        $systemAddressBookRoot->disableListing = $disableListing;
122
+
123
+        $uploadCollection = new Upload\RootCollection($userPrincipalBackend, 'principals/users');
124
+        $uploadCollection->disableListing = $disableListing;
125
+
126
+        $avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users');
127
+        $avatarCollection->disableListing = $disableListing;
128
+
129
+        $children = [
130
+                new SimpleCollection('principals', [
131
+                        $userPrincipals,
132
+                        $groupPrincipals,
133
+                        $systemPrincipals,
134
+                        $calendarResourcePrincipals,
135
+                        $calendarRoomPrincipals]),
136
+                $filesCollection,
137
+                $userCalendarRoot,
138
+                new SimpleCollection('system-calendars', [
139
+                    $resourceCalendarRoot,
140
+                    $roomCalendarRoot,
141
+                ]),
142
+                $publicCalendarRoot,
143
+                new SimpleCollection('addressbooks', [
144
+                        $usersAddressBookRoot,
145
+                        $systemAddressBookRoot]),
146
+                $systemTagCollection,
147
+                $systemTagRelationsCollection,
148
+                $commentsCollection,
149
+                $uploadCollection,
150
+                $avatarCollection
151
+        ];
152
+
153
+        parent::__construct('root', $children);
154
+    }
155 155
 
156 156
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php 2 patches
Indentation   +326 added lines, -326 removed lines patch added patch discarded remove patch
@@ -32,330 +32,330 @@
 block discarded – undo
32 32
 
33 33
 abstract class AbstractPrincipalBackend implements BackendInterface {
34 34
 
35
-	/** @var IDBConnection */
36
-	private $db;
37
-
38
-	/** @var IUserSession */
39
-	private $userSession;
40
-
41
-	/** @var IGroupManager */
42
-	private $groupManager;
43
-
44
-	/** @var ILogger */
45
-	private $logger;
46
-
47
-	/** @var string */
48
-	private $principalPrefix;
49
-
50
-	/** @var string */
51
-	private $dbTableName;
52
-
53
-	/**
54
-	 * @param IDBConnection $dbConnection
55
-	 * @param IUserSession $userSession
56
-	 * @param IGroupManager $groupManager
57
-	 * @param ILogger $logger
58
-	 * @param string $principalPrefix
59
-	 * @param string $dbPrefix
60
-	 */
61
-	public function __construct(IDBConnection $dbConnection,
62
-								IUserSession $userSession,
63
-								IGroupManager $groupManager,
64
-								ILogger $logger,
65
-								$principalPrefix, $dbPrefix) {
66
-		$this->db = $dbConnection;
67
-		$this->userSession = $userSession;
68
-		$this->groupManager = $groupManager;
69
-		$this->logger = $logger;
70
-		$this->principalPrefix = $principalPrefix;
71
-		$this->dbTableName = 'calendar_' . $dbPrefix . '_cache';
72
-	}
73
-
74
-	/**
75
-	 * Returns a list of principals based on a prefix.
76
-	 *
77
-	 * This prefix will often contain something like 'principals'. You are only
78
-	 * expected to return principals that are in this base path.
79
-	 *
80
-	 * You are expected to return at least a 'uri' for every user, you can
81
-	 * return any additional properties if you wish so. Common properties are:
82
-	 *   {DAV:}displayname
83
-	 *
84
-	 * @param string $prefixPath
85
-	 * @return string[]
86
-	 */
87
-	public function getPrincipalsByPrefix($prefixPath) {
88
-		$principals = [];
89
-
90
-		if ($prefixPath === $this->principalPrefix) {
91
-			$query = $this->db->getQueryBuilder();
92
-			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
93
-				->from($this->dbTableName);
94
-			$stmt = $query->execute();
95
-
96
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
97
-				$principals[] = $this->rowToPrincipal($row);
98
-			}
99
-
100
-			$stmt->closeCursor();
101
-		}
102
-
103
-		return $principals;
104
-	}
105
-
106
-	/**
107
-	 * Returns a specific principal, specified by it's path.
108
-	 * The returned structure should be the exact same as from
109
-	 * getPrincipalsByPrefix.
110
-	 *
111
-	 * @param string $path
112
-	 * @return array
113
-	 */
114
-	public function getPrincipalByPath($path) {
115
-		if (strpos($path, $this->principalPrefix) !== 0) {
116
-			return null;
117
-		}
118
-		list(, $name) = \Sabre\Uri\split($path);
119
-
120
-		list($backendId, $resourceId) = explode('-',  $name, 2);
121
-
122
-		$query = $this->db->getQueryBuilder();
123
-		$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
124
-			->from($this->dbTableName)
125
-			->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
126
-			->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
127
-		$stmt = $query->execute();
128
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
129
-
130
-		if(!$row) {
131
-			return null;
132
-		}
133
-
134
-		return $this->rowToPrincipal($row);
135
-	}
136
-
137
-	/**
138
-	 * Returns the list of members for a group-principal
139
-	 *
140
-	 * @param string $principal
141
-	 * @return string[]
142
-	 */
143
-	public function getGroupMemberSet($principal) {
144
-		return [];
145
-	}
146
-
147
-	/**
148
-	 * Returns the list of groups a principal is a member of
149
-	 *
150
-	 * @param string $principal
151
-	 * @return array
152
-	 */
153
-	public function getGroupMembership($principal) {
154
-		return [];
155
-	}
156
-
157
-	/**
158
-	 * Updates the list of group members for a group principal.
159
-	 *
160
-	 * The principals should be passed as a list of uri's.
161
-	 *
162
-	 * @param string $principal
163
-	 * @param string[] $members
164
-	 * @throws Exception
165
-	 */
166
-	public function setGroupMemberSet($principal, array $members) {
167
-		throw new Exception('Setting members of the group is not supported yet');
168
-	}
169
-
170
-	/**
171
-	 * @param string $path
172
-	 * @param PropPatch $propPatch
173
-	 * @return int
174
-	 */
175
-	function updatePrincipal($path, PropPatch $propPatch) {
176
-		return 0;
177
-	}
178
-
179
-	/**
180
-	 * @param string $prefixPath
181
-	 * @param array $searchProperties
182
-	 * @param string $test
183
-	 * @return array
184
-	 */
185
-	function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
186
-		$results = [];
187
-		if (\count($searchProperties) === 0) {
188
-			return [];
189
-		}
190
-		if ($prefixPath !== $this->principalPrefix) {
191
-			return [];
192
-		}
193
-
194
-		$user = $this->userSession->getUser();
195
-		if (!$user) {
196
-			return [];
197
-		}
198
-		$usersGroups = $this->groupManager->getUserGroupIds($user);
199
-
200
-		foreach ($searchProperties as $prop => $value) {
201
-			switch ($prop) {
202
-				case '{http://sabredav.org/ns}email-address':
203
-					$query = $this->db->getQueryBuilder();
204
-					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
205
-						->from($this->dbTableName)
206
-						->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
207
-
208
-					$stmt = $query->execute();
209
-					$principals = [];
210
-					while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
211
-						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
212
-							continue;
213
-						}
214
-						$principals[] = $this->rowToPrincipal($row)['uri'];
215
-					}
216
-					$results[] = $principals;
217
-
218
-					$stmt->closeCursor();
219
-					break;
220
-
221
-				case '{DAV:}displayname':
222
-					$query = $this->db->getQueryBuilder();
223
-					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
224
-						->from($this->dbTableName)
225
-						->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
226
-
227
-					$stmt = $query->execute();
228
-					$principals = [];
229
-					while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
-						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
231
-							continue;
232
-						}
233
-						$principals[] = $this->rowToPrincipal($row)['uri'];
234
-					}
235
-					$results[] = $principals;
236
-
237
-					$stmt->closeCursor();
238
-					break;
239
-
240
-				default:
241
-					$results[] = [];
242
-					break;
243
-			}
244
-		}
245
-
246
-		// results is an array of arrays, so this is not the first search result
247
-		// but the results of the first searchProperty
248
-		if (count($results) === 1) {
249
-			return $results[0];
250
-		}
251
-
252
-		switch ($test) {
253
-			case 'anyof':
254
-				return array_values(array_unique(array_merge(...$results)));
255
-
256
-			case 'allof':
257
-			default:
258
-				return array_values(array_intersect(...$results));
259
-		}
260
-	}
261
-
262
-	/**
263
-	 * @param string $uri
264
-	 * @param string $principalPrefix
265
-	 * @return null|string
266
-	 */
267
-	function findByUri($uri, $principalPrefix) {
268
-		$user = $this->userSession->getUser();
269
-		if (!$user) {
270
-			return null;
271
-		}
272
-		$usersGroups = $this->groupManager->getUserGroupIds($user);
273
-
274
-		if (strpos($uri, 'mailto:') === 0) {
275
-			$email = substr($uri, 7);
276
-			$query = $this->db->getQueryBuilder();
277
-			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
278
-				->from($this->dbTableName)
279
-				->where($query->expr()->eq('email', $query->createNamedParameter($email)));
280
-
281
-			$stmt = $query->execute();
282
-			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
283
-
284
-			if(!$row) {
285
-				return null;
286
-			}
287
-			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
288
-				return null;
289
-			}
290
-
291
-			return $this->rowToPrincipal($row)['uri'];
292
-		}
293
-
294
-		if (strpos($uri, 'principal:') === 0) {
295
-			$path = substr($uri, 10);
296
-			if (strpos($path, $this->principalPrefix) !== 0) {
297
-				return null;
298
-			}
299
-
300
-			list(, $name) = \Sabre\Uri\split($path);
301
-			list($backendId, $resourceId) = explode('-',  $name, 2);
302
-
303
-			$query = $this->db->getQueryBuilder();
304
-			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
305
-				->from($this->dbTableName)
306
-				->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
307
-				->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
308
-			$stmt = $query->execute();
309
-			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
310
-
311
-			if(!$row) {
312
-				return null;
313
-			}
314
-			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
315
-				return null;
316
-			}
317
-
318
-			return $this->rowToPrincipal($row)['uri'];
319
-		}
320
-
321
-		return null;
322
-	}
323
-
324
-	/**
325
-	 * convert database row to principal
326
-	 */
327
-	private function rowToPrincipal($row) {
328
-		return [
329
-			'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
330
-			'{DAV:}displayname' => $row['displayname'],
331
-			'{http://sabredav.org/ns}email-address' => $row['email']
332
-		];
333
-	}
334
-
335
-	/**
336
-	 * @param $row
337
-	 * @param $userGroups
338
-	 * @return bool
339
-	 */
340
-	private function isAllowedToAccessResource($row, $userGroups) {
341
-		if (!isset($row['group_restrictions']) ||
342
-			$row['group_restrictions'] === null ||
343
-			$row['group_restrictions'] === '') {
344
-			return true;
345
-		}
346
-
347
-		// group restrictions contains something, but not parsable, deny access and log warning
348
-		$json = json_decode($row['group_restrictions']);
349
-		if (!\is_array($json)) {
350
-			$this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
351
-			return false;
352
-		}
353
-
354
-		// empty array => no group restrictions
355
-		if (empty($json)) {
356
-			return true;
357
-		}
358
-
359
-		return !empty(array_intersect($json, $userGroups));
360
-	}
35
+    /** @var IDBConnection */
36
+    private $db;
37
+
38
+    /** @var IUserSession */
39
+    private $userSession;
40
+
41
+    /** @var IGroupManager */
42
+    private $groupManager;
43
+
44
+    /** @var ILogger */
45
+    private $logger;
46
+
47
+    /** @var string */
48
+    private $principalPrefix;
49
+
50
+    /** @var string */
51
+    private $dbTableName;
52
+
53
+    /**
54
+     * @param IDBConnection $dbConnection
55
+     * @param IUserSession $userSession
56
+     * @param IGroupManager $groupManager
57
+     * @param ILogger $logger
58
+     * @param string $principalPrefix
59
+     * @param string $dbPrefix
60
+     */
61
+    public function __construct(IDBConnection $dbConnection,
62
+                                IUserSession $userSession,
63
+                                IGroupManager $groupManager,
64
+                                ILogger $logger,
65
+                                $principalPrefix, $dbPrefix) {
66
+        $this->db = $dbConnection;
67
+        $this->userSession = $userSession;
68
+        $this->groupManager = $groupManager;
69
+        $this->logger = $logger;
70
+        $this->principalPrefix = $principalPrefix;
71
+        $this->dbTableName = 'calendar_' . $dbPrefix . '_cache';
72
+    }
73
+
74
+    /**
75
+     * Returns a list of principals based on a prefix.
76
+     *
77
+     * This prefix will often contain something like 'principals'. You are only
78
+     * expected to return principals that are in this base path.
79
+     *
80
+     * You are expected to return at least a 'uri' for every user, you can
81
+     * return any additional properties if you wish so. Common properties are:
82
+     *   {DAV:}displayname
83
+     *
84
+     * @param string $prefixPath
85
+     * @return string[]
86
+     */
87
+    public function getPrincipalsByPrefix($prefixPath) {
88
+        $principals = [];
89
+
90
+        if ($prefixPath === $this->principalPrefix) {
91
+            $query = $this->db->getQueryBuilder();
92
+            $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
93
+                ->from($this->dbTableName);
94
+            $stmt = $query->execute();
95
+
96
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
97
+                $principals[] = $this->rowToPrincipal($row);
98
+            }
99
+
100
+            $stmt->closeCursor();
101
+        }
102
+
103
+        return $principals;
104
+    }
105
+
106
+    /**
107
+     * Returns a specific principal, specified by it's path.
108
+     * The returned structure should be the exact same as from
109
+     * getPrincipalsByPrefix.
110
+     *
111
+     * @param string $path
112
+     * @return array
113
+     */
114
+    public function getPrincipalByPath($path) {
115
+        if (strpos($path, $this->principalPrefix) !== 0) {
116
+            return null;
117
+        }
118
+        list(, $name) = \Sabre\Uri\split($path);
119
+
120
+        list($backendId, $resourceId) = explode('-',  $name, 2);
121
+
122
+        $query = $this->db->getQueryBuilder();
123
+        $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
124
+            ->from($this->dbTableName)
125
+            ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
126
+            ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
127
+        $stmt = $query->execute();
128
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
129
+
130
+        if(!$row) {
131
+            return null;
132
+        }
133
+
134
+        return $this->rowToPrincipal($row);
135
+    }
136
+
137
+    /**
138
+     * Returns the list of members for a group-principal
139
+     *
140
+     * @param string $principal
141
+     * @return string[]
142
+     */
143
+    public function getGroupMemberSet($principal) {
144
+        return [];
145
+    }
146
+
147
+    /**
148
+     * Returns the list of groups a principal is a member of
149
+     *
150
+     * @param string $principal
151
+     * @return array
152
+     */
153
+    public function getGroupMembership($principal) {
154
+        return [];
155
+    }
156
+
157
+    /**
158
+     * Updates the list of group members for a group principal.
159
+     *
160
+     * The principals should be passed as a list of uri's.
161
+     *
162
+     * @param string $principal
163
+     * @param string[] $members
164
+     * @throws Exception
165
+     */
166
+    public function setGroupMemberSet($principal, array $members) {
167
+        throw new Exception('Setting members of the group is not supported yet');
168
+    }
169
+
170
+    /**
171
+     * @param string $path
172
+     * @param PropPatch $propPatch
173
+     * @return int
174
+     */
175
+    function updatePrincipal($path, PropPatch $propPatch) {
176
+        return 0;
177
+    }
178
+
179
+    /**
180
+     * @param string $prefixPath
181
+     * @param array $searchProperties
182
+     * @param string $test
183
+     * @return array
184
+     */
185
+    function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
186
+        $results = [];
187
+        if (\count($searchProperties) === 0) {
188
+            return [];
189
+        }
190
+        if ($prefixPath !== $this->principalPrefix) {
191
+            return [];
192
+        }
193
+
194
+        $user = $this->userSession->getUser();
195
+        if (!$user) {
196
+            return [];
197
+        }
198
+        $usersGroups = $this->groupManager->getUserGroupIds($user);
199
+
200
+        foreach ($searchProperties as $prop => $value) {
201
+            switch ($prop) {
202
+                case '{http://sabredav.org/ns}email-address':
203
+                    $query = $this->db->getQueryBuilder();
204
+                    $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
205
+                        ->from($this->dbTableName)
206
+                        ->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
207
+
208
+                    $stmt = $query->execute();
209
+                    $principals = [];
210
+                    while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
211
+                        if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
212
+                            continue;
213
+                        }
214
+                        $principals[] = $this->rowToPrincipal($row)['uri'];
215
+                    }
216
+                    $results[] = $principals;
217
+
218
+                    $stmt->closeCursor();
219
+                    break;
220
+
221
+                case '{DAV:}displayname':
222
+                    $query = $this->db->getQueryBuilder();
223
+                    $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
224
+                        ->from($this->dbTableName)
225
+                        ->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
226
+
227
+                    $stmt = $query->execute();
228
+                    $principals = [];
229
+                    while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
+                        if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
231
+                            continue;
232
+                        }
233
+                        $principals[] = $this->rowToPrincipal($row)['uri'];
234
+                    }
235
+                    $results[] = $principals;
236
+
237
+                    $stmt->closeCursor();
238
+                    break;
239
+
240
+                default:
241
+                    $results[] = [];
242
+                    break;
243
+            }
244
+        }
245
+
246
+        // results is an array of arrays, so this is not the first search result
247
+        // but the results of the first searchProperty
248
+        if (count($results) === 1) {
249
+            return $results[0];
250
+        }
251
+
252
+        switch ($test) {
253
+            case 'anyof':
254
+                return array_values(array_unique(array_merge(...$results)));
255
+
256
+            case 'allof':
257
+            default:
258
+                return array_values(array_intersect(...$results));
259
+        }
260
+    }
261
+
262
+    /**
263
+     * @param string $uri
264
+     * @param string $principalPrefix
265
+     * @return null|string
266
+     */
267
+    function findByUri($uri, $principalPrefix) {
268
+        $user = $this->userSession->getUser();
269
+        if (!$user) {
270
+            return null;
271
+        }
272
+        $usersGroups = $this->groupManager->getUserGroupIds($user);
273
+
274
+        if (strpos($uri, 'mailto:') === 0) {
275
+            $email = substr($uri, 7);
276
+            $query = $this->db->getQueryBuilder();
277
+            $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
278
+                ->from($this->dbTableName)
279
+                ->where($query->expr()->eq('email', $query->createNamedParameter($email)));
280
+
281
+            $stmt = $query->execute();
282
+            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
283
+
284
+            if(!$row) {
285
+                return null;
286
+            }
287
+            if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
288
+                return null;
289
+            }
290
+
291
+            return $this->rowToPrincipal($row)['uri'];
292
+        }
293
+
294
+        if (strpos($uri, 'principal:') === 0) {
295
+            $path = substr($uri, 10);
296
+            if (strpos($path, $this->principalPrefix) !== 0) {
297
+                return null;
298
+            }
299
+
300
+            list(, $name) = \Sabre\Uri\split($path);
301
+            list($backendId, $resourceId) = explode('-',  $name, 2);
302
+
303
+            $query = $this->db->getQueryBuilder();
304
+            $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
305
+                ->from($this->dbTableName)
306
+                ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
307
+                ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
308
+            $stmt = $query->execute();
309
+            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
310
+
311
+            if(!$row) {
312
+                return null;
313
+            }
314
+            if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
315
+                return null;
316
+            }
317
+
318
+            return $this->rowToPrincipal($row)['uri'];
319
+        }
320
+
321
+        return null;
322
+    }
323
+
324
+    /**
325
+     * convert database row to principal
326
+     */
327
+    private function rowToPrincipal($row) {
328
+        return [
329
+            'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
330
+            '{DAV:}displayname' => $row['displayname'],
331
+            '{http://sabredav.org/ns}email-address' => $row['email']
332
+        ];
333
+    }
334
+
335
+    /**
336
+     * @param $row
337
+     * @param $userGroups
338
+     * @return bool
339
+     */
340
+    private function isAllowedToAccessResource($row, $userGroups) {
341
+        if (!isset($row['group_restrictions']) ||
342
+            $row['group_restrictions'] === null ||
343
+            $row['group_restrictions'] === '') {
344
+            return true;
345
+        }
346
+
347
+        // group restrictions contains something, but not parsable, deny access and log warning
348
+        $json = json_decode($row['group_restrictions']);
349
+        if (!\is_array($json)) {
350
+            $this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
351
+            return false;
352
+        }
353
+
354
+        // empty array => no group restrictions
355
+        if (empty($json)) {
356
+            return true;
357
+        }
358
+
359
+        return !empty(array_intersect($json, $userGroups));
360
+    }
361 361
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		$this->groupManager = $groupManager;
69 69
 		$this->logger = $logger;
70 70
 		$this->principalPrefix = $principalPrefix;
71
-		$this->dbTableName = 'calendar_' . $dbPrefix . '_cache';
71
+		$this->dbTableName = 'calendar_'.$dbPrefix.'_cache';
72 72
 	}
73 73
 
74 74
 	/**
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 				->from($this->dbTableName);
94 94
 			$stmt = $query->execute();
95 95
 
96
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
96
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
97 97
 				$principals[] = $this->rowToPrincipal($row);
98 98
 			}
99 99
 
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 		}
118 118
 		list(, $name) = \Sabre\Uri\split($path);
119 119
 
120
-		list($backendId, $resourceId) = explode('-',  $name, 2);
120
+		list($backendId, $resourceId) = explode('-', $name, 2);
121 121
 
122 122
 		$query = $this->db->getQueryBuilder();
123 123
 		$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 		$stmt = $query->execute();
128 128
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
129 129
 
130
-		if(!$row) {
130
+		if (!$row) {
131 131
 			return null;
132 132
 		}
133 133
 
@@ -203,11 +203,11 @@  discard block
 block discarded – undo
203 203
 					$query = $this->db->getQueryBuilder();
204 204
 					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
205 205
 						->from($this->dbTableName)
206
-						->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
206
+						->where($query->expr()->iLike('email', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($value).'%')));
207 207
 
208 208
 					$stmt = $query->execute();
209 209
 					$principals = [];
210
-					while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
210
+					while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
211 211
 						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
212 212
 							continue;
213 213
 						}
@@ -222,11 +222,11 @@  discard block
 block discarded – undo
222 222
 					$query = $this->db->getQueryBuilder();
223 223
 					$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
224 224
 						->from($this->dbTableName)
225
-						->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
225
+						->where($query->expr()->iLike('displayname', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($value).'%')));
226 226
 
227 227
 					$stmt = $query->execute();
228 228
 					$principals = [];
229
-					while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
229
+					while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230 230
 						if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
231 231
 							continue;
232 232
 						}
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
 			$stmt = $query->execute();
282 282
 			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
283 283
 
284
-			if(!$row) {
284
+			if (!$row) {
285 285
 				return null;
286 286
 			}
287 287
 			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
 			}
299 299
 
300 300
 			list(, $name) = \Sabre\Uri\split($path);
301
-			list($backendId, $resourceId) = explode('-',  $name, 2);
301
+			list($backendId, $resourceId) = explode('-', $name, 2);
302 302
 
303 303
 			$query = $this->db->getQueryBuilder();
304 304
 			$query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 			$stmt = $query->execute();
309 309
 			$row = $stmt->fetch(\PDO::FETCH_ASSOC);
310 310
 
311
-			if(!$row) {
311
+			if (!$row) {
312 312
 				return null;
313 313
 			}
314 314
 			if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 	 */
327 327
 	private function rowToPrincipal($row) {
328 328
 		return [
329
-			'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
329
+			'uri' => $this->principalPrefix.'/'.$row['backend_id'].'-'.$row['resource_id'],
330 330
 			'{DAV:}displayname' => $row['displayname'],
331 331
 			'{http://sabredav.org/ns}email-address' => $row['email']
332 332
 		];
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 		// group restrictions contains something, but not parsable, deny access and log warning
348 348
 		$json = json_decode($row['group_restrictions']);
349 349
 		if (!\is_array($json)) {
350
-			$this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
350
+			$this->logger->info('group_restrictions field could not be parsed for '.$this->dbTableName.'::'.$row['id'].', denying access to resource');
351 351
 			return false;
352 352
 		}
353 353
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -29,17 +29,17 @@
 block discarded – undo
29 29
 
30 30
 class ResourcePrincipalBackend extends AbstractPrincipalBackend {
31 31
 
32
-	/**
33
-	 * @param IDBConnection $dbConnection
34
-	 * @param IUserSession $userSession
35
-	 * @param IGroupManager $groupManager
36
-	 * @param ILogger $logger
37
-	 */
38
-	public function __construct(IDBConnection $dbConnection,
39
-								IUserSession $userSession,
40
-								IGroupManager $groupManager,
41
-								ILogger $logger) {
42
-		parent::__construct($dbConnection, $userSession, $groupManager, $logger,
43
-			'principals/calendar-resources', 'resources');
44
-	}
32
+    /**
33
+     * @param IDBConnection $dbConnection
34
+     * @param IUserSession $userSession
35
+     * @param IGroupManager $groupManager
36
+     * @param ILogger $logger
37
+     */
38
+    public function __construct(IDBConnection $dbConnection,
39
+                                IUserSession $userSession,
40
+                                IGroupManager $groupManager,
41
+                                ILogger $logger) {
42
+        parent::__construct($dbConnection, $userSession, $groupManager, $logger,
43
+            'principals/calendar-resources', 'resources');
44
+    }
45 45
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -29,17 +29,17 @@
 block discarded – undo
29 29
 
30 30
 class RoomPrincipalBackend extends AbstractPrincipalBackend {
31 31
 
32
-	/**
33
-	 * @param IDBConnection $dbConnection
34
-	 * @param IUserSession $userSession
35
-	 * @param IGroupManager $groupManager
36
-	 * @param ILogger $logger
37
-	 */
38
-	public function __construct(IDBConnection $dbConnection,
39
-								IUserSession $userSession,
40
-								IGroupManager $groupManager,
41
-								ILogger $logger) {
42
-		parent::__construct($dbConnection, $userSession, $groupManager, $logger,
43
-			'principals/calendar-rooms', 'rooms');
44
-	}
32
+    /**
33
+     * @param IDBConnection $dbConnection
34
+     * @param IUserSession $userSession
35
+     * @param IGroupManager $groupManager
36
+     * @param ILogger $logger
37
+     */
38
+    public function __construct(IDBConnection $dbConnection,
39
+                                IUserSession $userSession,
40
+                                IGroupManager $groupManager,
41
+                                ILogger $logger) {
42
+        parent::__construct($dbConnection, $userSession, $groupManager, $logger,
43
+            'principals/calendar-rooms', 'rooms');
44
+    }
45 45
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Schedule/Plugin.php 2 patches
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -38,143 +38,143 @@
 block discarded – undo
38 38
 
39 39
 class Plugin extends \Sabre\CalDAV\Schedule\Plugin {
40 40
 
41
-	/**
42
-	 * Initializes the plugin
43
-	 *
44
-	 * @param Server $server
45
-	 * @return void
46
-	 */
47
-	function initialize(Server $server) {
48
-		parent::initialize($server);
49
-		$server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
50
-	}
51
-
52
-	/**
53
-	 * Returns a list of addresses that are associated with a principal.
54
-	 *
55
-	 * @param string $principal
56
-	 * @return array
57
-	 */
58
-	protected function getAddressesForPrincipal($principal) {
59
-		$result = parent::getAddressesForPrincipal($principal);
60
-
61
-		if ($result === null) {
62
-			$result = [];
63
-		}
64
-
65
-		return $result;
66
-	}
67
-
68
-	/**
69
-	 * Always use the personal calendar as target for scheduled events
70
-	 *
71
-	 * @param PropFind $propFind
72
-	 * @param INode $node
73
-	 * @return void
74
-	 */
75
-	function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
76
-		if ($node instanceof IPrincipal) {
77
-			$propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function() use ($node) {
78
-				/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
79
-				$caldavPlugin = $this->server->getPlugin('caldav');
80
-				$principalUrl = $node->getPrincipalUrl();
81
-
82
-				$calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
83
-				if (!$calendarHomePath) {
84
-					return null;
85
-				}
86
-
87
-				if (strpos($principalUrl, 'principals/users') === 0) {
88
-					$uri = CalDavBackend::PERSONAL_CALENDAR_URI;
89
-					$displayname = CalDavBackend::PERSONAL_CALENDAR_NAME;
90
-				} elseif (strpos($principalUrl, 'principals/calendar-resources') === 0 ||
91
-						  strpos($principalUrl, 'principals/calendar-rooms') === 0) {
92
-					$uri = CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI;
93
-					$displayname = CalDavBackend::RESOURCE_BOOKING_CALENDAR_NAME;
94
-				} else {
95
-					// How did we end up here?
96
-					// TODO - throw exception or just ignore?
97
-					return null;
98
-				}
99
-
100
-				/** @var CalendarHome $calendarHome */
101
-				$calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
102
-				if (!$calendarHome->childExists($uri)) {
103
-					$calendarHome->getCalDAVBackend()->createCalendar($principalUrl, $uri, [
104
-						'{DAV:}displayname' => $displayname,
105
-					]);
106
-				}
107
-
108
-				$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
109
-				if (empty($result)) {
110
-					return null;
111
-				}
112
-
113
-				return new LocalHref($result[0]['href']);
114
-			});
115
-		}
116
-	}
117
-
118
-	/**
119
-	 * This method is triggered whenever there was a calendar object gets
120
-	 * created or updated.
121
-	 *
122
-	 * Basically just a copy of parent::calendarObjectChange, with the change
123
-	 * from:
124
-	 * $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
125
-	 * to:
126
-	 * $addresses = $this->getAddressesForPrincipal($calendarNode->getPrincipalURI());
127
-	 *
128
-	 * @param RequestInterface $request HTTP request
129
-	 * @param ResponseInterface $response HTTP Response
130
-	 * @param VCalendar $vCal Parsed iCalendar object
131
-	 * @param mixed $calendarPath Path to calendar collection
132
-	 * @param mixed $modified The iCalendar object has been touched.
133
-	 * @param mixed $isNew Whether this was a new item or we're updating one
134
-	 * @return void
135
-	 */
136
-	function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
137
-
138
-		if (!$this->scheduleReply($this->server->httpRequest)) {
139
-			return;
140
-		}
141
-
142
-		$calendarNode = $this->server->tree->getNodeForPath($calendarPath);
143
-
144
-		$addresses = $this->getAddressesForPrincipal(
145
-			$calendarNode->getPrincipalURI()
146
-		);
147
-
148
-		if (!$isNew) {
149
-			$node = $this->server->tree->getNodeForPath($request->getPath());
150
-			$oldObj = Reader::read($node->get());
151
-		} else {
152
-			$oldObj = null;
153
-		}
154
-
155
-		$this->processICalendarChange($oldObj, $vCal, $addresses, [], $modified);
156
-
157
-		if ($oldObj) {
158
-			// Destroy circular references so PHP will GC the object.
159
-			$oldObj->destroy();
160
-		}
161
-
162
-	}
163
-
164
-	/**
165
-	 * This method checks the 'Schedule-Reply' header
166
-	 * and returns false if it's 'F', otherwise true.
167
-	 *
168
-	 * Copied from Sabre/DAV's Schedule plugin, because it's
169
-	 * private for whatever reason
170
-	 *
171
-	 * @param RequestInterface $request
172
-	 * @return bool
173
-	 */
174
-	private function scheduleReply(RequestInterface $request) {
175
-
176
-		$scheduleReply = $request->getHeader('Schedule-Reply');
177
-		return $scheduleReply !== 'F';
178
-
179
-	}
41
+    /**
42
+     * Initializes the plugin
43
+     *
44
+     * @param Server $server
45
+     * @return void
46
+     */
47
+    function initialize(Server $server) {
48
+        parent::initialize($server);
49
+        $server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
50
+    }
51
+
52
+    /**
53
+     * Returns a list of addresses that are associated with a principal.
54
+     *
55
+     * @param string $principal
56
+     * @return array
57
+     */
58
+    protected function getAddressesForPrincipal($principal) {
59
+        $result = parent::getAddressesForPrincipal($principal);
60
+
61
+        if ($result === null) {
62
+            $result = [];
63
+        }
64
+
65
+        return $result;
66
+    }
67
+
68
+    /**
69
+     * Always use the personal calendar as target for scheduled events
70
+     *
71
+     * @param PropFind $propFind
72
+     * @param INode $node
73
+     * @return void
74
+     */
75
+    function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
76
+        if ($node instanceof IPrincipal) {
77
+            $propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function() use ($node) {
78
+                /** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
79
+                $caldavPlugin = $this->server->getPlugin('caldav');
80
+                $principalUrl = $node->getPrincipalUrl();
81
+
82
+                $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
83
+                if (!$calendarHomePath) {
84
+                    return null;
85
+                }
86
+
87
+                if (strpos($principalUrl, 'principals/users') === 0) {
88
+                    $uri = CalDavBackend::PERSONAL_CALENDAR_URI;
89
+                    $displayname = CalDavBackend::PERSONAL_CALENDAR_NAME;
90
+                } elseif (strpos($principalUrl, 'principals/calendar-resources') === 0 ||
91
+                          strpos($principalUrl, 'principals/calendar-rooms') === 0) {
92
+                    $uri = CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI;
93
+                    $displayname = CalDavBackend::RESOURCE_BOOKING_CALENDAR_NAME;
94
+                } else {
95
+                    // How did we end up here?
96
+                    // TODO - throw exception or just ignore?
97
+                    return null;
98
+                }
99
+
100
+                /** @var CalendarHome $calendarHome */
101
+                $calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
102
+                if (!$calendarHome->childExists($uri)) {
103
+                    $calendarHome->getCalDAVBackend()->createCalendar($principalUrl, $uri, [
104
+                        '{DAV:}displayname' => $displayname,
105
+                    ]);
106
+                }
107
+
108
+                $result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
109
+                if (empty($result)) {
110
+                    return null;
111
+                }
112
+
113
+                return new LocalHref($result[0]['href']);
114
+            });
115
+        }
116
+    }
117
+
118
+    /**
119
+     * This method is triggered whenever there was a calendar object gets
120
+     * created or updated.
121
+     *
122
+     * Basically just a copy of parent::calendarObjectChange, with the change
123
+     * from:
124
+     * $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
125
+     * to:
126
+     * $addresses = $this->getAddressesForPrincipal($calendarNode->getPrincipalURI());
127
+     *
128
+     * @param RequestInterface $request HTTP request
129
+     * @param ResponseInterface $response HTTP Response
130
+     * @param VCalendar $vCal Parsed iCalendar object
131
+     * @param mixed $calendarPath Path to calendar collection
132
+     * @param mixed $modified The iCalendar object has been touched.
133
+     * @param mixed $isNew Whether this was a new item or we're updating one
134
+     * @return void
135
+     */
136
+    function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
137
+
138
+        if (!$this->scheduleReply($this->server->httpRequest)) {
139
+            return;
140
+        }
141
+
142
+        $calendarNode = $this->server->tree->getNodeForPath($calendarPath);
143
+
144
+        $addresses = $this->getAddressesForPrincipal(
145
+            $calendarNode->getPrincipalURI()
146
+        );
147
+
148
+        if (!$isNew) {
149
+            $node = $this->server->tree->getNodeForPath($request->getPath());
150
+            $oldObj = Reader::read($node->get());
151
+        } else {
152
+            $oldObj = null;
153
+        }
154
+
155
+        $this->processICalendarChange($oldObj, $vCal, $addresses, [], $modified);
156
+
157
+        if ($oldObj) {
158
+            // Destroy circular references so PHP will GC the object.
159
+            $oldObj->destroy();
160
+        }
161
+
162
+    }
163
+
164
+    /**
165
+     * This method checks the 'Schedule-Reply' header
166
+     * and returns false if it's 'F', otherwise true.
167
+     *
168
+     * Copied from Sabre/DAV's Schedule plugin, because it's
169
+     * private for whatever reason
170
+     *
171
+     * @param RequestInterface $request
172
+     * @return bool
173
+     */
174
+    private function scheduleReply(RequestInterface $request) {
175
+
176
+        $scheduleReply = $request->getHeader('Schedule-Reply');
177
+        return $scheduleReply !== 'F';
178
+
179
+    }
180 180
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 	 */
75 75
 	function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
76 76
 		if ($node instanceof IPrincipal) {
77
-			$propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function() use ($node) {
77
+			$propFind->handle('{'.self::NS_CALDAV.'}schedule-default-calendar-URL', function() use ($node) {
78 78
 				/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
79 79
 				$caldavPlugin = $this->server->getPlugin('caldav');
80 80
 				$principalUrl = $node->getPrincipalUrl();
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 					]);
106 106
 				}
107 107
 
108
-				$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1);
108
+				$result = $this->server->getPropertiesForPath($calendarHomePath.'/'.$uri, [], 1);
109 109
 				if (empty($result)) {
110 110
 					return null;
111 111
 				}
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Plugin.php 2 patches
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -25,27 +25,27 @@
 block discarded – undo
25 25
 
26 26
 class Plugin extends \Sabre\CalDAV\Plugin {
27 27
 
28
-	const SYSTEM_CALENDAR_ROOT = 'system-calendars';
28
+    const SYSTEM_CALENDAR_ROOT = 'system-calendars';
29 29
 
30
-	/**
31
-	 * @inheritdoc
32
-	 */
33
-	function getCalendarHomeForPrincipal($principalUrl):string {
30
+    /**
31
+     * @inheritdoc
32
+     */
33
+    function getCalendarHomeForPrincipal($principalUrl):string {
34 34
 
35
-		if (strrpos($principalUrl, 'principals/users', -strlen($principalUrl)) !== false) {
36
-			list(, $principalId) = \Sabre\Uri\split($principalUrl);
37
-			return self::CALENDAR_ROOT . '/' . $principalId;
38
-		}
39
-		if (strrpos($principalUrl, 'principals/calendar-resources', -strlen($principalUrl)) !== false) {
40
-			list(, $principalId) = \Sabre\Uri\split($principalUrl);
41
-			return self::SYSTEM_CALENDAR_ROOT . '/calendar-resources/' . $principalId;
42
-		}
43
-		if (strrpos($principalUrl, 'principals/calendar-rooms', -strlen($principalUrl)) !== false) {
44
-			list(, $principalId) = \Sabre\Uri\split($principalUrl);
45
-			return self::SYSTEM_CALENDAR_ROOT . '/calendar-rooms/' . $principalId;
46
-		}
35
+        if (strrpos($principalUrl, 'principals/users', -strlen($principalUrl)) !== false) {
36
+            list(, $principalId) = \Sabre\Uri\split($principalUrl);
37
+            return self::CALENDAR_ROOT . '/' . $principalId;
38
+        }
39
+        if (strrpos($principalUrl, 'principals/calendar-resources', -strlen($principalUrl)) !== false) {
40
+            list(, $principalId) = \Sabre\Uri\split($principalUrl);
41
+            return self::SYSTEM_CALENDAR_ROOT . '/calendar-resources/' . $principalId;
42
+        }
43
+        if (strrpos($principalUrl, 'principals/calendar-rooms', -strlen($principalUrl)) !== false) {
44
+            list(, $principalId) = \Sabre\Uri\split($principalUrl);
45
+            return self::SYSTEM_CALENDAR_ROOT . '/calendar-rooms/' . $principalId;
46
+        }
47 47
 
48
-		throw new \LogicException('This is not supposed to happen');
49
-	}
48
+        throw new \LogicException('This is not supposed to happen');
49
+    }
50 50
 
51 51
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -34,15 +34,15 @@
 block discarded – undo
34 34
 
35 35
 		if (strrpos($principalUrl, 'principals/users', -strlen($principalUrl)) !== false) {
36 36
 			list(, $principalId) = \Sabre\Uri\split($principalUrl);
37
-			return self::CALENDAR_ROOT . '/' . $principalId;
37
+			return self::CALENDAR_ROOT.'/'.$principalId;
38 38
 		}
39 39
 		if (strrpos($principalUrl, 'principals/calendar-resources', -strlen($principalUrl)) !== false) {
40 40
 			list(, $principalId) = \Sabre\Uri\split($principalUrl);
41
-			return self::SYSTEM_CALENDAR_ROOT . '/calendar-resources/' . $principalId;
41
+			return self::SYSTEM_CALENDAR_ROOT.'/calendar-resources/'.$principalId;
42 42
 		}
43 43
 		if (strrpos($principalUrl, 'principals/calendar-rooms', -strlen($principalUrl)) !== false) {
44 44
 			list(, $principalId) = \Sabre\Uri\split($principalUrl);
45
-			return self::SYSTEM_CALENDAR_ROOT . '/calendar-rooms/' . $principalId;
45
+			return self::SYSTEM_CALENDAR_ROOT.'/calendar-rooms/'.$principalId;
46 46
 		}
47 47
 
48 48
 		throw new \LogicException('This is not supposed to happen');
Please login to merge, or discard this patch.
apps/dav/lib/Migration/Version1005Date20180530124431.php 2 patches
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -32,56 +32,56 @@
 block discarded – undo
32 32
  */
33 33
 class Version1005Date20180530124431 extends SimpleMigrationStep {
34 34
 
35
-	/**
36
-	 * @param IOutput $output
37
-	 * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
38
-	 * @param array $options
39
-	 * @return null|ISchemaWrapper
40
-	 * @since 13.0.0
41
-	 */
42
-	public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
43
-		/** @var ISchemaWrapper $schema */
44
-		$schema = $schemaClosure();
35
+    /**
36
+     * @param IOutput $output
37
+     * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
38
+     * @param array $options
39
+     * @return null|ISchemaWrapper
40
+     * @since 13.0.0
41
+     */
42
+    public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
43
+        /** @var ISchemaWrapper $schema */
44
+        $schema = $schemaClosure();
45 45
 
46
-		$types = ['resources', 'rooms'];
47
-		foreach($types as $type) {
48
-			if (!$schema->hasTable('calendar_' . $type . '_cache')) {
49
-				$table = $schema->createTable('calendar_' . $type . '_cache');
46
+        $types = ['resources', 'rooms'];
47
+        foreach($types as $type) {
48
+            if (!$schema->hasTable('calendar_' . $type . '_cache')) {
49
+                $table = $schema->createTable('calendar_' . $type . '_cache');
50 50
 
51
-				$table->addColumn('id', Type::BIGINT, [
52
-					'autoincrement' => true,
53
-					'notnull' => true,
54
-					'length' => 11,
55
-					'unsigned' => true,
56
-				]);
57
-				$table->addColumn('backend_id', Type::STRING, [
58
-					'notnull' => false,
59
-					'length' => 64,
60
-				]);
61
-				$table->addColumn('resource_id', Type::STRING, [
62
-					'notnull' => false,
63
-					'length' => 64,
64
-				]);
65
-				$table->addColumn('email', Type::STRING, [
66
-					'notnull' => false,
67
-					'length' => 255,
68
-				]);
69
-				$table->addColumn('displayname', Type::STRING, [
70
-					'notnull' => false,
71
-					'length' => 255,
72
-				]);
73
-				$table->addColumn('group_restrictions', Type::STRING, [
74
-					'notnull' => false,
75
-					'length' => 4000,
76
-				]);
51
+                $table->addColumn('id', Type::BIGINT, [
52
+                    'autoincrement' => true,
53
+                    'notnull' => true,
54
+                    'length' => 11,
55
+                    'unsigned' => true,
56
+                ]);
57
+                $table->addColumn('backend_id', Type::STRING, [
58
+                    'notnull' => false,
59
+                    'length' => 64,
60
+                ]);
61
+                $table->addColumn('resource_id', Type::STRING, [
62
+                    'notnull' => false,
63
+                    'length' => 64,
64
+                ]);
65
+                $table->addColumn('email', Type::STRING, [
66
+                    'notnull' => false,
67
+                    'length' => 255,
68
+                ]);
69
+                $table->addColumn('displayname', Type::STRING, [
70
+                    'notnull' => false,
71
+                    'length' => 255,
72
+                ]);
73
+                $table->addColumn('group_restrictions', Type::STRING, [
74
+                    'notnull' => false,
75
+                    'length' => 4000,
76
+                ]);
77 77
 
78
-				$table->setPrimaryKey(['id'], 'calendar_' . $type . '_cache_id_idx');
79
-				$table->addIndex(['backend_id', 'resource_id'], 'calendar_' . $type . '_cache_backendresource_idx');
80
-				$table->addIndex(['email'], 'calendar_' . $type . '_cache_email_idx');
81
-				$table->addIndex(['displayname'], 'calendar_' . $type . '_cache_displayname_idx');
82
-			}
83
-		}
78
+                $table->setPrimaryKey(['id'], 'calendar_' . $type . '_cache_id_idx');
79
+                $table->addIndex(['backend_id', 'resource_id'], 'calendar_' . $type . '_cache_backendresource_idx');
80
+                $table->addIndex(['email'], 'calendar_' . $type . '_cache_email_idx');
81
+                $table->addIndex(['displayname'], 'calendar_' . $type . '_cache_displayname_idx');
82
+            }
83
+        }
84 84
 
85
-		return $schema;
86
-	}
85
+        return $schema;
86
+    }
87 87
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -44,9 +44,9 @@  discard block
 block discarded – undo
44 44
 		$schema = $schemaClosure();
45 45
 
46 46
 		$types = ['resources', 'rooms'];
47
-		foreach($types as $type) {
48
-			if (!$schema->hasTable('calendar_' . $type . '_cache')) {
49
-				$table = $schema->createTable('calendar_' . $type . '_cache');
47
+		foreach ($types as $type) {
48
+			if (!$schema->hasTable('calendar_'.$type.'_cache')) {
49
+				$table = $schema->createTable('calendar_'.$type.'_cache');
50 50
 
51 51
 				$table->addColumn('id', Type::BIGINT, [
52 52
 					'autoincrement' => true,
@@ -75,10 +75,10 @@  discard block
 block discarded – undo
75 75
 					'length' => 4000,
76 76
 				]);
77 77
 
78
-				$table->setPrimaryKey(['id'], 'calendar_' . $type . '_cache_id_idx');
79
-				$table->addIndex(['backend_id', 'resource_id'], 'calendar_' . $type . '_cache_backendresource_idx');
80
-				$table->addIndex(['email'], 'calendar_' . $type . '_cache_email_idx');
81
-				$table->addIndex(['displayname'], 'calendar_' . $type . '_cache_displayname_idx');
78
+				$table->setPrimaryKey(['id'], 'calendar_'.$type.'_cache_id_idx');
79
+				$table->addIndex(['backend_id', 'resource_id'], 'calendar_'.$type.'_cache_backendresource_idx');
80
+				$table->addIndex(['email'], 'calendar_'.$type.'_cache_email_idx');
81
+				$table->addIndex(['displayname'], 'calendar_'.$type.'_cache_displayname_idx');
82 82
 			}
83 83
 		}
84 84
 
Please login to merge, or discard this patch.
lib/public/Calendar/Resource/IBackend.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -32,36 +32,36 @@
 block discarded – undo
32 32
  */
33 33
 interface IBackend {
34 34
 
35
-	/**
36
-	 * get a list of all resources in this backend
37
-	 *
38
-	 * @throws BackendTemporarilyUnavailableException
39
-	 * @return IResource[]
40
-	 */
41
-	public function getAllResources():array;
35
+    /**
36
+     * get a list of all resources in this backend
37
+     *
38
+     * @throws BackendTemporarilyUnavailableException
39
+     * @return IResource[]
40
+     */
41
+    public function getAllResources():array;
42 42
 
43
-	/**
44
-	 * get a list of all resource identifiers in this backend
45
-	 *
46
-	 * @throws BackendTemporarilyUnavailableException
47
-	 * @return string[]
48
-	 */
49
-	public function listAllResources():array;
43
+    /**
44
+     * get a list of all resource identifiers in this backend
45
+     *
46
+     * @throws BackendTemporarilyUnavailableException
47
+     * @return string[]
48
+     */
49
+    public function listAllResources():array;
50 50
 
51
-	/**
52
-	 * get a resource by it's id
53
-	 *
54
-	 * @param string $id
55
-	 * @throws BackendTemporarilyUnavailableException
56
-	 * @return IResource|null
57
-	 */
58
-	public function getResource($id);
51
+    /**
52
+     * get a resource by it's id
53
+     *
54
+     * @param string $id
55
+     * @throws BackendTemporarilyUnavailableException
56
+     * @return IResource|null
57
+     */
58
+    public function getResource($id);
59 59
 
60
-	/**
61
-	 * Get unique identifier of the backend
62
-	 *
63
-	 * @return string
64
-	 * @since 14.0.0
65
-	 */
66
-	public function getBackendIdentifier():string;
60
+    /**
61
+     * Get unique identifier of the backend
62
+     *
63
+     * @return string
64
+     * @since 14.0.0
65
+     */
66
+    public function getBackendIdentifier():string;
67 67
 }
Please login to merge, or discard this patch.
lib/public/Calendar/Resource/IManager.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -25,40 +25,40 @@
 block discarded – undo
25 25
 
26 26
 interface IManager {
27 27
 
28
-	/**
29
-	 * Registers a resource backend
30
-	 *
31
-	 * @param IBackend $backend
32
-	 * @return void
33
-	 * @since 14.0.0
34
-	 */
35
-	public function registerBackend(IBackend $backend);
28
+    /**
29
+     * Registers a resource backend
30
+     *
31
+     * @param IBackend $backend
32
+     * @return void
33
+     * @since 14.0.0
34
+     */
35
+    public function registerBackend(IBackend $backend);
36 36
 
37
-	/**
38
-	 * Unregisters a resource backend
39
-	 *
40
-	 * @param IBackend $backend
41
-	 * @return void
42
-	 * @since 14.0.0
43
-	 */
44
-	public function unregisterBackend(IBackend $backend);
37
+    /**
38
+     * Unregisters a resource backend
39
+     *
40
+     * @param IBackend $backend
41
+     * @return void
42
+     * @since 14.0.0
43
+     */
44
+    public function unregisterBackend(IBackend $backend);
45 45
 
46
-	/**
47
-	 * @return IBackend[]
48
-	 * @since 14.0.0
49
-	 */
50
-	public function getBackends():array;
46
+    /**
47
+     * @return IBackend[]
48
+     * @since 14.0.0
49
+     */
50
+    public function getBackends():array;
51 51
 
52
-	/**
53
-	 * @param string $backendId
54
-	 * @return IBackend
55
-	 */
56
-	public function getBackend($backendId):IBackend;
52
+    /**
53
+     * @param string $backendId
54
+     * @return IBackend
55
+     */
56
+    public function getBackend($backendId):IBackend;
57 57
 
58
-	/**
59
-	 * removes all registered backend instances
60
-	 * @return void
61
-	 * @since 14.0.0
62
-	 */
63
-	public function clear();
58
+    /**
59
+     * removes all registered backend instances
60
+     * @return void
61
+     * @since 14.0.0
62
+     */
63
+    public function clear();
64 64
 }
Please login to merge, or discard this patch.