Completed
Pull Request — master (#3218)
by Vars
131:47 queued 107:50
created
lib/private/AppFramework/OCS/BaseResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 	/**
25 25
 	 * BaseResponse constructor.
26 26
 	 *
27
-	 * @param DataResponse|null $dataResponse
27
+	 * @param DataResponse $dataResponse
28 28
 	 * @param string $format
29 29
 	 * @param string|null $statusMessage
30 30
 	 * @param int|null $itemsCount
Please login to merge, or discard this patch.
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -27,70 +27,70 @@
 block discarded – undo
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29 29
 abstract class BaseResponse extends Response   {
30
-	/** @var array */
31
-	protected $data;
30
+    /** @var array */
31
+    protected $data;
32 32
 
33
-	/** @var string */
34
-	protected $format;
33
+    /** @var string */
34
+    protected $format;
35 35
 
36
-	/** @var string */
37
-	protected $statusMessage;
36
+    /** @var string */
37
+    protected $statusMessage;
38 38
 
39
-	/** @var int */
40
-	protected $itemsCount;
39
+    /** @var int */
40
+    protected $itemsCount;
41 41
 
42
-	/** @var int */
43
-	protected $itemsPerPage;
42
+    /** @var int */
43
+    protected $itemsPerPage;
44 44
 
45
-	/**
46
-	 * BaseResponse constructor.
47
-	 *
48
-	 * @param DataResponse|null $dataResponse
49
-	 * @param string $format
50
-	 * @param string|null $statusMessage
51
-	 * @param int|null $itemsCount
52
-	 * @param int|null $itemsPerPage
53
-	 */
54
-	public function __construct(DataResponse $dataResponse,
55
-								$format = 'xml',
56
-								$statusMessage = null,
57
-								$itemsCount = null,
58
-								$itemsPerPage = null) {
59
-		$this->format = $format;
60
-		$this->statusMessage = $statusMessage;
61
-		$this->itemsCount = $itemsCount;
62
-		$this->itemsPerPage = $itemsPerPage;
45
+    /**
46
+     * BaseResponse constructor.
47
+     *
48
+     * @param DataResponse|null $dataResponse
49
+     * @param string $format
50
+     * @param string|null $statusMessage
51
+     * @param int|null $itemsCount
52
+     * @param int|null $itemsPerPage
53
+     */
54
+    public function __construct(DataResponse $dataResponse,
55
+                                $format = 'xml',
56
+                                $statusMessage = null,
57
+                                $itemsCount = null,
58
+                                $itemsPerPage = null) {
59
+        $this->format = $format;
60
+        $this->statusMessage = $statusMessage;
61
+        $this->itemsCount = $itemsCount;
62
+        $this->itemsPerPage = $itemsPerPage;
63 63
 
64
-		$this->data = $dataResponse->getData();
64
+        $this->data = $dataResponse->getData();
65 65
 
66
-		$this->setHeaders($dataResponse->getHeaders());
67
-		$this->setStatus($dataResponse->getStatus());
68
-		$this->setETag($dataResponse->getETag());
69
-		$this->setLastModified($dataResponse->getLastModified());
70
-		$this->setCookies($dataResponse->getCookies());
71
-		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
66
+        $this->setHeaders($dataResponse->getHeaders());
67
+        $this->setStatus($dataResponse->getStatus());
68
+        $this->setETag($dataResponse->getETag());
69
+        $this->setLastModified($dataResponse->getLastModified());
70
+        $this->setCookies($dataResponse->getCookies());
71
+        $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
72 72
 
73
-		if ($format === 'json') {
74
-			$this->addHeader(
75
-				'Content-Type', 'application/json; charset=utf-8'
76
-			);
77
-		} else {
78
-			$this->addHeader(
79
-				'Content-Type', 'application/xml; charset=utf-8'
80
-			);
81
-		}
82
-	}
73
+        if ($format === 'json') {
74
+            $this->addHeader(
75
+                'Content-Type', 'application/json; charset=utf-8'
76
+            );
77
+        } else {
78
+            $this->addHeader(
79
+                'Content-Type', 'application/xml; charset=utf-8'
80
+            );
81
+        }
82
+    }
83 83
 
84
-	/**
85
-	 * @param string[] $meta
86
-	 * @return string
87
-	 */
88
-	protected function renderResult($meta) {
89
-		// TODO rewrite functions
90
-		return \OC_API::renderResult($this->format, $meta, $this->data);
91
-	}
84
+    /**
85
+     * @param string[] $meta
86
+     * @return string
87
+     */
88
+    protected function renderResult($meta) {
89
+        // TODO rewrite functions
90
+        return \OC_API::renderResult($this->format, $meta, $this->data);
91
+    }
92 92
 
93
-	public function getOCSStatus() {
94
-		return parent::getStatus();
95
-	}
93
+    public function getOCSStatus() {
94
+        return parent::getStatus();
95
+    }
96 96
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@
 block discarded – undo
26 26
 use OCP\AppFramework\Http\EmptyContentSecurityPolicy;
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29
-abstract class BaseResponse extends Response   {
29
+abstract class BaseResponse extends Response {
30 30
 	/** @var array */
31 31
 	protected $data;
32 32
 
Please login to merge, or discard this patch.
lib/private/Server.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1143,7 +1143,7 @@  discard block
 block discarded – undo
1143 1143
 	 * Get the certificate manager for the user
1144 1144
 	 *
1145 1145
 	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1146
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1146
+	 * @return null|CertificateManager | null if $uid is null and no user is logged in
1147 1147
 	 */
1148 1148
 	public function getCertificateManager($userId = '') {
1149 1149
 		if ($userId === '') {
@@ -1464,6 +1464,7 @@  discard block
 block discarded – undo
1464 1464
 	}
1465 1465
 
1466 1466
 	/**
1467
+	 * @param string $app
1467 1468
 	 * @return \OCP\Files\IAppData
1468 1469
 	 */
1469 1470
 	public function getAppDataDir($app) {
Please login to merge, or discard this patch.
Indentation   +1619 added lines, -1619 removed lines patch added patch discarded remove patch
@@ -119,1628 +119,1628 @@
 block discarded – undo
119 119
  * TODO: hookup all manager classes
120 120
  */
121 121
 class Server extends ServerContainer implements IServerContainer {
122
-	/** @var string */
123
-	private $webRoot;
124
-
125
-	/**
126
-	 * @param string $webRoot
127
-	 * @param \OC\Config $config
128
-	 */
129
-	public function __construct($webRoot, \OC\Config $config) {
130
-		parent::__construct();
131
-		$this->webRoot = $webRoot;
132
-
133
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
134
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
135
-
136
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
137
-			return new PreviewManager(
138
-				$c->getConfig(),
139
-				$c->getRootFolder(),
140
-				$c->getAppDataDir('preview'),
141
-				$c->getEventDispatcher(),
142
-				$c->getSession()->get('user_id')
143
-			);
144
-		});
145
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
146
-
147
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
148
-			return new \OC\Preview\Watcher(
149
-				$c->getAppDataDir('preview')
150
-			);
151
-		});
152
-
153
-		$this->registerService('EncryptionManager', function (Server $c) {
154
-			$view = new View();
155
-			$util = new Encryption\Util(
156
-				$view,
157
-				$c->getUserManager(),
158
-				$c->getGroupManager(),
159
-				$c->getConfig()
160
-			);
161
-			return new Encryption\Manager(
162
-				$c->getConfig(),
163
-				$c->getLogger(),
164
-				$c->getL10N('core'),
165
-				new View(),
166
-				$util,
167
-				new ArrayCache()
168
-			);
169
-		});
170
-
171
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
172
-			$util = new Encryption\Util(
173
-				new View(),
174
-				$c->getUserManager(),
175
-				$c->getGroupManager(),
176
-				$c->getConfig()
177
-			);
178
-			return new Encryption\File(
179
-				$util,
180
-				$c->getRootFolder(),
181
-				$c->getShareManager()
182
-			);
183
-		});
184
-
185
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
186
-			$view = new View();
187
-			$util = new Encryption\Util(
188
-				$view,
189
-				$c->getUserManager(),
190
-				$c->getGroupManager(),
191
-				$c->getConfig()
192
-			);
193
-
194
-			return new Encryption\Keys\Storage($view, $util);
195
-		});
196
-		$this->registerService('TagMapper', function (Server $c) {
197
-			return new TagMapper($c->getDatabaseConnection());
198
-		});
199
-
200
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
201
-			$tagMapper = $c->query('TagMapper');
202
-			return new TagManager($tagMapper, $c->getUserSession());
203
-		});
204
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
205
-
206
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
207
-			$config = $c->getConfig();
208
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
209
-			/** @var \OC\SystemTag\ManagerFactory $factory */
210
-			$factory = new $factoryClass($this);
211
-			return $factory;
212
-		});
213
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
214
-			return $c->query('SystemTagManagerFactory')->getManager();
215
-		});
216
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
217
-
218
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
219
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
220
-		});
221
-		$this->registerService('RootFolder', function (Server $c) {
222
-			$manager = \OC\Files\Filesystem::getMountManager(null);
223
-			$view = new View();
224
-			$root = new Root(
225
-				$manager,
226
-				$view,
227
-				null,
228
-				$c->getUserMountCache(),
229
-				$this->getLogger(),
230
-				$this->getUserManager()
231
-			);
232
-			$connector = new HookConnector($root, $view);
233
-			$connector->viewToNode();
234
-
235
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
236
-			$previewConnector->connectWatcher();
237
-
238
-			return $root;
239
-		});
240
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
241
-
242
-		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
243
-			return new LazyRoot(function() use ($c) {
244
-				return $c->query('RootFolder');
245
-			});
246
-		});
247
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
248
-
249
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
250
-			$config = $c->getConfig();
251
-			return new \OC\User\Manager($config);
252
-		});
253
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
254
-
255
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
256
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
257
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
258
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
259
-			});
260
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
261
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
262
-			});
263
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
264
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
265
-			});
266
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
267
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
268
-			});
269
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
270
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
271
-			});
272
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
273
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
274
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
275
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
276
-			});
277
-			return $groupManager;
278
-		});
279
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
280
-
281
-		$this->registerService(Store::class, function(Server $c) {
282
-			$session = $c->getSession();
283
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
284
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
285
-			} else {
286
-				$tokenProvider = null;
287
-			}
288
-			$logger = $c->getLogger();
289
-			return new Store($session, $logger, $tokenProvider);
290
-		});
291
-		$this->registerAlias(IStore::class, Store::class);
292
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
293
-			$dbConnection = $c->getDatabaseConnection();
294
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
295
-		});
296
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
297
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
298
-			$crypto = $c->getCrypto();
299
-			$config = $c->getConfig();
300
-			$logger = $c->getLogger();
301
-			$timeFactory = new TimeFactory();
302
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
303
-		});
304
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
305
-
306
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
307
-			$manager = $c->getUserManager();
308
-			$session = new \OC\Session\Memory('');
309
-			$timeFactory = new TimeFactory();
310
-			// Token providers might require a working database. This code
311
-			// might however be called when ownCloud is not yet setup.
312
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
313
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
314
-			} else {
315
-				$defaultTokenProvider = null;
316
-			}
317
-
318
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
319
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
320
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
321
-			});
322
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
323
-				/** @var $user \OC\User\User */
324
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
325
-			});
326
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
327
-				/** @var $user \OC\User\User */
328
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
329
-			});
330
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
331
-				/** @var $user \OC\User\User */
332
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
333
-			});
334
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
335
-				/** @var $user \OC\User\User */
336
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
337
-			});
338
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
339
-				/** @var $user \OC\User\User */
340
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
341
-			});
342
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
343
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
344
-			});
345
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
346
-				/** @var $user \OC\User\User */
347
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
348
-			});
349
-			$userSession->listen('\OC\User', 'logout', function () {
350
-				\OC_Hook::emit('OC_User', 'logout', array());
351
-			});
352
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
353
-				/** @var $user \OC\User\User */
354
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
355
-			});
356
-			return $userSession;
357
-		});
358
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
359
-
360
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
361
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
362
-		});
363
-
364
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
365
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
366
-
367
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
368
-			return new \OC\AllConfig(
369
-				$c->getSystemConfig()
370
-			);
371
-		});
372
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
373
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
374
-
375
-		$this->registerService('SystemConfig', function ($c) use ($config) {
376
-			return new \OC\SystemConfig($config);
377
-		});
378
-
379
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
380
-			return new \OC\AppConfig($c->getDatabaseConnection());
381
-		});
382
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
383
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
384
-
385
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
386
-			return new \OC\L10N\Factory(
387
-				$c->getConfig(),
388
-				$c->getRequest(),
389
-				$c->getUserSession(),
390
-				\OC::$SERVERROOT
391
-			);
392
-		});
393
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
394
-
395
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
396
-			$config = $c->getConfig();
397
-			$cacheFactory = $c->getMemCacheFactory();
398
-			return new \OC\URLGenerator(
399
-				$config,
400
-				$cacheFactory
401
-			);
402
-		});
403
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
404
-
405
-		$this->registerService('AppHelper', function ($c) {
406
-			return new \OC\AppHelper();
407
-		});
408
-		$this->registerService('AppFetcher', function ($c) {
409
-			return new AppFetcher(
410
-				$this->getAppDataDir('appstore'),
411
-				$this->getHTTPClientService(),
412
-				$this->query(TimeFactory::class),
413
-				$this->getConfig()
414
-			);
415
-		});
416
-		$this->registerService('CategoryFetcher', function ($c) {
417
-			return new CategoryFetcher(
418
-				$this->getAppDataDir('appstore'),
419
-				$this->getHTTPClientService(),
420
-				$this->query(TimeFactory::class),
421
-				$this->getConfig()
422
-			);
423
-		});
424
-
425
-		$this->registerService(\OCP\ICache::class, function ($c) {
426
-			return new Cache\File();
427
-		});
428
-		$this->registerAlias('UserCache', \OCP\ICache::class);
429
-
430
-		$this->registerService(Factory::class, function (Server $c) {
431
-			$config = $c->getConfig();
432
-
433
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
434
-				$v = \OC_App::getAppVersions();
435
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
436
-				$version = implode(',', $v);
437
-				$instanceId = \OC_Util::getInstanceId();
438
-				$path = \OC::$SERVERROOT;
439
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
440
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
441
-					$config->getSystemValue('memcache.local', null),
442
-					$config->getSystemValue('memcache.distributed', null),
443
-					$config->getSystemValue('memcache.locking', null)
444
-				);
445
-			}
446
-
447
-			return new \OC\Memcache\Factory('', $c->getLogger(),
448
-				'\\OC\\Memcache\\ArrayCache',
449
-				'\\OC\\Memcache\\ArrayCache',
450
-				'\\OC\\Memcache\\ArrayCache'
451
-			);
452
-		});
453
-		$this->registerAlias('MemCacheFactory', Factory::class);
454
-		$this->registerAlias(ICacheFactory::class, Factory::class);
455
-
456
-		$this->registerService('RedisFactory', function (Server $c) {
457
-			$systemConfig = $c->getSystemConfig();
458
-			return new RedisFactory($systemConfig);
459
-		});
460
-
461
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
462
-			return new \OC\Activity\Manager(
463
-				$c->getRequest(),
464
-				$c->getUserSession(),
465
-				$c->getConfig(),
466
-				$c->query(IValidator::class)
467
-			);
468
-		});
469
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
470
-
471
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
472
-			return new \OC\Activity\EventMerger(
473
-				$c->getL10N('lib')
474
-			);
475
-		});
476
-		$this->registerAlias(IValidator::class, Validator::class);
477
-
478
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
479
-			return new AvatarManager(
480
-				$c->getUserManager(),
481
-				$c->getAppDataDir('avatar'),
482
-				$c->getL10N('lib'),
483
-				$c->getLogger(),
484
-				$c->getConfig()
485
-			);
486
-		});
487
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
488
-
489
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
490
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
491
-			$logger = Log::getLogClass($logType);
492
-			call_user_func(array($logger, 'init'));
493
-
494
-			return new Log($logger);
495
-		});
496
-		$this->registerAlias('Logger', \OCP\ILogger::class);
497
-
498
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
499
-			$config = $c->getConfig();
500
-			return new \OC\BackgroundJob\JobList(
501
-				$c->getDatabaseConnection(),
502
-				$config,
503
-				new TimeFactory()
504
-			);
505
-		});
506
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
507
-
508
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
509
-			$cacheFactory = $c->getMemCacheFactory();
510
-			$logger = $c->getLogger();
511
-			if ($cacheFactory->isAvailable()) {
512
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
513
-			} else {
514
-				$router = new \OC\Route\Router($logger);
515
-			}
516
-			return $router;
517
-		});
518
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
519
-
520
-		$this->registerService(\OCP\ISearch::class, function ($c) {
521
-			return new Search();
522
-		});
523
-		$this->registerAlias('Search', \OCP\ISearch::class);
524
-
525
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
526
-			return new \OC\Security\RateLimiting\Limiter(
527
-				$this->getUserSession(),
528
-				$this->getRequest(),
529
-				new \OC\AppFramework\Utility\TimeFactory(),
530
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
531
-			);
532
-		});
533
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
534
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
535
-				$this->getMemCacheFactory(),
536
-				new \OC\AppFramework\Utility\TimeFactory()
537
-			);
538
-		});
539
-
540
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
541
-			return new SecureRandom();
542
-		});
543
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
544
-
545
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
546
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
547
-		});
548
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
549
-
550
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
551
-			return new Hasher($c->getConfig());
552
-		});
553
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
554
-
555
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
556
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
557
-		});
558
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
559
-
560
-		$this->registerService(IDBConnection::class, function (Server $c) {
561
-			$systemConfig = $c->getSystemConfig();
562
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
563
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
564
-			if (!$factory->isValidType($type)) {
565
-				throw new \OC\DatabaseException('Invalid database type');
566
-			}
567
-			$connectionParams = $factory->createConnectionParams();
568
-			$connection = $factory->getConnection($type, $connectionParams);
569
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
570
-			return $connection;
571
-		});
572
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
573
-
574
-		$this->registerService('HTTPHelper', function (Server $c) {
575
-			$config = $c->getConfig();
576
-			return new HTTPHelper(
577
-				$config,
578
-				$c->getHTTPClientService()
579
-			);
580
-		});
581
-
582
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
583
-			$user = \OC_User::getUser();
584
-			$uid = $user ? $user : null;
585
-			return new ClientService(
586
-				$c->getConfig(),
587
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
588
-			);
589
-		});
590
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
591
-
592
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
593
-			if ($c->getSystemConfig()->getValue('debug', false)) {
594
-				return new EventLogger();
595
-			} else {
596
-				return new NullEventLogger();
597
-			}
598
-		});
599
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
600
-
601
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
602
-			if ($c->getSystemConfig()->getValue('debug', false)) {
603
-				return new QueryLogger();
604
-			} else {
605
-				return new NullQueryLogger();
606
-			}
607
-		});
608
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
609
-
610
-		$this->registerService(TempManager::class, function (Server $c) {
611
-			return new TempManager(
612
-				$c->getLogger(),
613
-				$c->getConfig()
614
-			);
615
-		});
616
-		$this->registerAlias('TempManager', TempManager::class);
617
-		$this->registerAlias(ITempManager::class, TempManager::class);
618
-
619
-		$this->registerService(AppManager::class, function (Server $c) {
620
-			return new \OC\App\AppManager(
621
-				$c->getUserSession(),
622
-				$c->getAppConfig(),
623
-				$c->getGroupManager(),
624
-				$c->getMemCacheFactory(),
625
-				$c->getEventDispatcher()
626
-			);
627
-		});
628
-		$this->registerAlias('AppManager', AppManager::class);
629
-		$this->registerAlias(IAppManager::class, AppManager::class);
630
-
631
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
632
-			return new DateTimeZone(
633
-				$c->getConfig(),
634
-				$c->getSession()
635
-			);
636
-		});
637
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
638
-
639
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
640
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
641
-
642
-			return new DateTimeFormatter(
643
-				$c->getDateTimeZone()->getTimeZone(),
644
-				$c->getL10N('lib', $language)
645
-			);
646
-		});
647
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
648
-
649
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
650
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
651
-			$listener = new UserMountCacheListener($mountCache);
652
-			$listener->listen($c->getUserManager());
653
-			return $mountCache;
654
-		});
655
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
656
-
657
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
658
-			$loader = \OC\Files\Filesystem::getLoader();
659
-			$mountCache = $c->query('UserMountCache');
660
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
661
-
662
-			// builtin providers
663
-
664
-			$config = $c->getConfig();
665
-			$manager->registerProvider(new CacheMountProvider($config));
666
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
667
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
668
-
669
-			return $manager;
670
-		});
671
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
672
-
673
-		$this->registerService('IniWrapper', function ($c) {
674
-			return new IniGetWrapper();
675
-		});
676
-		$this->registerService('AsyncCommandBus', function (Server $c) {
677
-			$jobList = $c->getJobList();
678
-			return new AsyncBus($jobList);
679
-		});
680
-		$this->registerService('TrustedDomainHelper', function ($c) {
681
-			return new TrustedDomainHelper($this->getConfig());
682
-		});
683
-		$this->registerService('Throttler', function(Server $c) {
684
-			return new Throttler(
685
-				$c->getDatabaseConnection(),
686
-				new TimeFactory(),
687
-				$c->getLogger(),
688
-				$c->getConfig()
689
-			);
690
-		});
691
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
692
-			// IConfig and IAppManager requires a working database. This code
693
-			// might however be called when ownCloud is not yet setup.
694
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
695
-				$config = $c->getConfig();
696
-				$appManager = $c->getAppManager();
697
-			} else {
698
-				$config = null;
699
-				$appManager = null;
700
-			}
701
-
702
-			return new Checker(
703
-					new EnvironmentHelper(),
704
-					new FileAccessHelper(),
705
-					new AppLocator(),
706
-					$config,
707
-					$c->getMemCacheFactory(),
708
-					$appManager,
709
-					$c->getTempManager()
710
-			);
711
-		});
712
-		$this->registerService(\OCP\IRequest::class, function ($c) {
713
-			if (isset($this['urlParams'])) {
714
-				$urlParams = $this['urlParams'];
715
-			} else {
716
-				$urlParams = [];
717
-			}
718
-
719
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
720
-				&& in_array('fakeinput', stream_get_wrappers())
721
-			) {
722
-				$stream = 'fakeinput://data';
723
-			} else {
724
-				$stream = 'php://input';
725
-			}
726
-
727
-			return new Request(
728
-				[
729
-					'get' => $_GET,
730
-					'post' => $_POST,
731
-					'files' => $_FILES,
732
-					'server' => $_SERVER,
733
-					'env' => $_ENV,
734
-					'cookies' => $_COOKIE,
735
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
736
-						? $_SERVER['REQUEST_METHOD']
737
-						: null,
738
-					'urlParams' => $urlParams,
739
-				],
740
-				$this->getSecureRandom(),
741
-				$this->getConfig(),
742
-				$this->getCsrfTokenManager(),
743
-				$stream
744
-			);
745
-		});
746
-		$this->registerAlias('Request', \OCP\IRequest::class);
747
-
748
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
749
-			return new Mailer(
750
-				$c->getConfig(),
751
-				$c->getLogger(),
752
-				$c->query(Defaults::class),
753
-				$c->getURLGenerator(),
754
-				$c->getL10N('lib')
755
-			);
756
-		});
757
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
758
-
759
-		$this->registerService('LDAPProvider', function(Server $c) {
760
-			$config = $c->getConfig();
761
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
762
-			if(is_null($factoryClass)) {
763
-				throw new \Exception('ldapProviderFactory not set');
764
-			}
765
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
766
-			$factory = new $factoryClass($this);
767
-			return $factory->getLDAPProvider();
768
-		});
769
-		$this->registerService('LockingProvider', function (Server $c) {
770
-			$ini = $c->getIniWrapper();
771
-			$config = $c->getConfig();
772
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
773
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
774
-				/** @var \OC\Memcache\Factory $memcacheFactory */
775
-				$memcacheFactory = $c->getMemCacheFactory();
776
-				$memcache = $memcacheFactory->createLocking('lock');
777
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
778
-					return new MemcacheLockingProvider($memcache, $ttl);
779
-				}
780
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
781
-			}
782
-			return new NoopLockingProvider();
783
-		});
784
-
785
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
786
-			return new \OC\Files\Mount\Manager();
787
-		});
788
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
789
-
790
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
791
-			return new \OC\Files\Type\Detection(
792
-				$c->getURLGenerator(),
793
-				\OC::$configDir,
794
-				\OC::$SERVERROOT . '/resources/config/'
795
-			);
796
-		});
797
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
798
-
799
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
800
-			return new \OC\Files\Type\Loader(
801
-				$c->getDatabaseConnection()
802
-			);
803
-		});
804
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
805
-
806
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
807
-			return new Manager(
808
-				$c->query(IValidator::class)
809
-			);
810
-		});
811
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
812
-
813
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
814
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
815
-			$manager->registerCapability(function () use ($c) {
816
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
817
-			});
818
-			return $manager;
819
-		});
820
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
821
-
822
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
823
-			$config = $c->getConfig();
824
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
825
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
826
-			$factory = new $factoryClass($this);
827
-			return $factory->getManager();
828
-		});
829
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
830
-
831
-		$this->registerService('ThemingDefaults', function(Server $c) {
832
-			/*
122
+    /** @var string */
123
+    private $webRoot;
124
+
125
+    /**
126
+     * @param string $webRoot
127
+     * @param \OC\Config $config
128
+     */
129
+    public function __construct($webRoot, \OC\Config $config) {
130
+        parent::__construct();
131
+        $this->webRoot = $webRoot;
132
+
133
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
134
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
135
+
136
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
137
+            return new PreviewManager(
138
+                $c->getConfig(),
139
+                $c->getRootFolder(),
140
+                $c->getAppDataDir('preview'),
141
+                $c->getEventDispatcher(),
142
+                $c->getSession()->get('user_id')
143
+            );
144
+        });
145
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
146
+
147
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
148
+            return new \OC\Preview\Watcher(
149
+                $c->getAppDataDir('preview')
150
+            );
151
+        });
152
+
153
+        $this->registerService('EncryptionManager', function (Server $c) {
154
+            $view = new View();
155
+            $util = new Encryption\Util(
156
+                $view,
157
+                $c->getUserManager(),
158
+                $c->getGroupManager(),
159
+                $c->getConfig()
160
+            );
161
+            return new Encryption\Manager(
162
+                $c->getConfig(),
163
+                $c->getLogger(),
164
+                $c->getL10N('core'),
165
+                new View(),
166
+                $util,
167
+                new ArrayCache()
168
+            );
169
+        });
170
+
171
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
172
+            $util = new Encryption\Util(
173
+                new View(),
174
+                $c->getUserManager(),
175
+                $c->getGroupManager(),
176
+                $c->getConfig()
177
+            );
178
+            return new Encryption\File(
179
+                $util,
180
+                $c->getRootFolder(),
181
+                $c->getShareManager()
182
+            );
183
+        });
184
+
185
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
186
+            $view = new View();
187
+            $util = new Encryption\Util(
188
+                $view,
189
+                $c->getUserManager(),
190
+                $c->getGroupManager(),
191
+                $c->getConfig()
192
+            );
193
+
194
+            return new Encryption\Keys\Storage($view, $util);
195
+        });
196
+        $this->registerService('TagMapper', function (Server $c) {
197
+            return new TagMapper($c->getDatabaseConnection());
198
+        });
199
+
200
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
201
+            $tagMapper = $c->query('TagMapper');
202
+            return new TagManager($tagMapper, $c->getUserSession());
203
+        });
204
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
205
+
206
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
207
+            $config = $c->getConfig();
208
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
209
+            /** @var \OC\SystemTag\ManagerFactory $factory */
210
+            $factory = new $factoryClass($this);
211
+            return $factory;
212
+        });
213
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
214
+            return $c->query('SystemTagManagerFactory')->getManager();
215
+        });
216
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
217
+
218
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
219
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
220
+        });
221
+        $this->registerService('RootFolder', function (Server $c) {
222
+            $manager = \OC\Files\Filesystem::getMountManager(null);
223
+            $view = new View();
224
+            $root = new Root(
225
+                $manager,
226
+                $view,
227
+                null,
228
+                $c->getUserMountCache(),
229
+                $this->getLogger(),
230
+                $this->getUserManager()
231
+            );
232
+            $connector = new HookConnector($root, $view);
233
+            $connector->viewToNode();
234
+
235
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
236
+            $previewConnector->connectWatcher();
237
+
238
+            return $root;
239
+        });
240
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
241
+
242
+        $this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
243
+            return new LazyRoot(function() use ($c) {
244
+                return $c->query('RootFolder');
245
+            });
246
+        });
247
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
248
+
249
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
250
+            $config = $c->getConfig();
251
+            return new \OC\User\Manager($config);
252
+        });
253
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
254
+
255
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
256
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
257
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
258
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
259
+            });
260
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
261
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
262
+            });
263
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
264
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
265
+            });
266
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
267
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
268
+            });
269
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
270
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
271
+            });
272
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
273
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
274
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
275
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
276
+            });
277
+            return $groupManager;
278
+        });
279
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
280
+
281
+        $this->registerService(Store::class, function(Server $c) {
282
+            $session = $c->getSession();
283
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
284
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
285
+            } else {
286
+                $tokenProvider = null;
287
+            }
288
+            $logger = $c->getLogger();
289
+            return new Store($session, $logger, $tokenProvider);
290
+        });
291
+        $this->registerAlias(IStore::class, Store::class);
292
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
293
+            $dbConnection = $c->getDatabaseConnection();
294
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
295
+        });
296
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
297
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
298
+            $crypto = $c->getCrypto();
299
+            $config = $c->getConfig();
300
+            $logger = $c->getLogger();
301
+            $timeFactory = new TimeFactory();
302
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
303
+        });
304
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
305
+
306
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
307
+            $manager = $c->getUserManager();
308
+            $session = new \OC\Session\Memory('');
309
+            $timeFactory = new TimeFactory();
310
+            // Token providers might require a working database. This code
311
+            // might however be called when ownCloud is not yet setup.
312
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
313
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
314
+            } else {
315
+                $defaultTokenProvider = null;
316
+            }
317
+
318
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
319
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
320
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
321
+            });
322
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
323
+                /** @var $user \OC\User\User */
324
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
325
+            });
326
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
327
+                /** @var $user \OC\User\User */
328
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
329
+            });
330
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
331
+                /** @var $user \OC\User\User */
332
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
333
+            });
334
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
335
+                /** @var $user \OC\User\User */
336
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
337
+            });
338
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
339
+                /** @var $user \OC\User\User */
340
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
341
+            });
342
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
343
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
344
+            });
345
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
346
+                /** @var $user \OC\User\User */
347
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
348
+            });
349
+            $userSession->listen('\OC\User', 'logout', function () {
350
+                \OC_Hook::emit('OC_User', 'logout', array());
351
+            });
352
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
353
+                /** @var $user \OC\User\User */
354
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
355
+            });
356
+            return $userSession;
357
+        });
358
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
359
+
360
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
361
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
362
+        });
363
+
364
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
365
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
366
+
367
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
368
+            return new \OC\AllConfig(
369
+                $c->getSystemConfig()
370
+            );
371
+        });
372
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
373
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
374
+
375
+        $this->registerService('SystemConfig', function ($c) use ($config) {
376
+            return new \OC\SystemConfig($config);
377
+        });
378
+
379
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
380
+            return new \OC\AppConfig($c->getDatabaseConnection());
381
+        });
382
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
383
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
384
+
385
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
386
+            return new \OC\L10N\Factory(
387
+                $c->getConfig(),
388
+                $c->getRequest(),
389
+                $c->getUserSession(),
390
+                \OC::$SERVERROOT
391
+            );
392
+        });
393
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
394
+
395
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
396
+            $config = $c->getConfig();
397
+            $cacheFactory = $c->getMemCacheFactory();
398
+            return new \OC\URLGenerator(
399
+                $config,
400
+                $cacheFactory
401
+            );
402
+        });
403
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
404
+
405
+        $this->registerService('AppHelper', function ($c) {
406
+            return new \OC\AppHelper();
407
+        });
408
+        $this->registerService('AppFetcher', function ($c) {
409
+            return new AppFetcher(
410
+                $this->getAppDataDir('appstore'),
411
+                $this->getHTTPClientService(),
412
+                $this->query(TimeFactory::class),
413
+                $this->getConfig()
414
+            );
415
+        });
416
+        $this->registerService('CategoryFetcher', function ($c) {
417
+            return new CategoryFetcher(
418
+                $this->getAppDataDir('appstore'),
419
+                $this->getHTTPClientService(),
420
+                $this->query(TimeFactory::class),
421
+                $this->getConfig()
422
+            );
423
+        });
424
+
425
+        $this->registerService(\OCP\ICache::class, function ($c) {
426
+            return new Cache\File();
427
+        });
428
+        $this->registerAlias('UserCache', \OCP\ICache::class);
429
+
430
+        $this->registerService(Factory::class, function (Server $c) {
431
+            $config = $c->getConfig();
432
+
433
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
434
+                $v = \OC_App::getAppVersions();
435
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
436
+                $version = implode(',', $v);
437
+                $instanceId = \OC_Util::getInstanceId();
438
+                $path = \OC::$SERVERROOT;
439
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
440
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
441
+                    $config->getSystemValue('memcache.local', null),
442
+                    $config->getSystemValue('memcache.distributed', null),
443
+                    $config->getSystemValue('memcache.locking', null)
444
+                );
445
+            }
446
+
447
+            return new \OC\Memcache\Factory('', $c->getLogger(),
448
+                '\\OC\\Memcache\\ArrayCache',
449
+                '\\OC\\Memcache\\ArrayCache',
450
+                '\\OC\\Memcache\\ArrayCache'
451
+            );
452
+        });
453
+        $this->registerAlias('MemCacheFactory', Factory::class);
454
+        $this->registerAlias(ICacheFactory::class, Factory::class);
455
+
456
+        $this->registerService('RedisFactory', function (Server $c) {
457
+            $systemConfig = $c->getSystemConfig();
458
+            return new RedisFactory($systemConfig);
459
+        });
460
+
461
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
462
+            return new \OC\Activity\Manager(
463
+                $c->getRequest(),
464
+                $c->getUserSession(),
465
+                $c->getConfig(),
466
+                $c->query(IValidator::class)
467
+            );
468
+        });
469
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
470
+
471
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
472
+            return new \OC\Activity\EventMerger(
473
+                $c->getL10N('lib')
474
+            );
475
+        });
476
+        $this->registerAlias(IValidator::class, Validator::class);
477
+
478
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
479
+            return new AvatarManager(
480
+                $c->getUserManager(),
481
+                $c->getAppDataDir('avatar'),
482
+                $c->getL10N('lib'),
483
+                $c->getLogger(),
484
+                $c->getConfig()
485
+            );
486
+        });
487
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
488
+
489
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
490
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
491
+            $logger = Log::getLogClass($logType);
492
+            call_user_func(array($logger, 'init'));
493
+
494
+            return new Log($logger);
495
+        });
496
+        $this->registerAlias('Logger', \OCP\ILogger::class);
497
+
498
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
499
+            $config = $c->getConfig();
500
+            return new \OC\BackgroundJob\JobList(
501
+                $c->getDatabaseConnection(),
502
+                $config,
503
+                new TimeFactory()
504
+            );
505
+        });
506
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
507
+
508
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
509
+            $cacheFactory = $c->getMemCacheFactory();
510
+            $logger = $c->getLogger();
511
+            if ($cacheFactory->isAvailable()) {
512
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
513
+            } else {
514
+                $router = new \OC\Route\Router($logger);
515
+            }
516
+            return $router;
517
+        });
518
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
519
+
520
+        $this->registerService(\OCP\ISearch::class, function ($c) {
521
+            return new Search();
522
+        });
523
+        $this->registerAlias('Search', \OCP\ISearch::class);
524
+
525
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
526
+            return new \OC\Security\RateLimiting\Limiter(
527
+                $this->getUserSession(),
528
+                $this->getRequest(),
529
+                new \OC\AppFramework\Utility\TimeFactory(),
530
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
531
+            );
532
+        });
533
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
534
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
535
+                $this->getMemCacheFactory(),
536
+                new \OC\AppFramework\Utility\TimeFactory()
537
+            );
538
+        });
539
+
540
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
541
+            return new SecureRandom();
542
+        });
543
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
544
+
545
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
546
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
547
+        });
548
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
549
+
550
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
551
+            return new Hasher($c->getConfig());
552
+        });
553
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
554
+
555
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
556
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
557
+        });
558
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
559
+
560
+        $this->registerService(IDBConnection::class, function (Server $c) {
561
+            $systemConfig = $c->getSystemConfig();
562
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
563
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
564
+            if (!$factory->isValidType($type)) {
565
+                throw new \OC\DatabaseException('Invalid database type');
566
+            }
567
+            $connectionParams = $factory->createConnectionParams();
568
+            $connection = $factory->getConnection($type, $connectionParams);
569
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
570
+            return $connection;
571
+        });
572
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
573
+
574
+        $this->registerService('HTTPHelper', function (Server $c) {
575
+            $config = $c->getConfig();
576
+            return new HTTPHelper(
577
+                $config,
578
+                $c->getHTTPClientService()
579
+            );
580
+        });
581
+
582
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
583
+            $user = \OC_User::getUser();
584
+            $uid = $user ? $user : null;
585
+            return new ClientService(
586
+                $c->getConfig(),
587
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
588
+            );
589
+        });
590
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
591
+
592
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
593
+            if ($c->getSystemConfig()->getValue('debug', false)) {
594
+                return new EventLogger();
595
+            } else {
596
+                return new NullEventLogger();
597
+            }
598
+        });
599
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
600
+
601
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
602
+            if ($c->getSystemConfig()->getValue('debug', false)) {
603
+                return new QueryLogger();
604
+            } else {
605
+                return new NullQueryLogger();
606
+            }
607
+        });
608
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
609
+
610
+        $this->registerService(TempManager::class, function (Server $c) {
611
+            return new TempManager(
612
+                $c->getLogger(),
613
+                $c->getConfig()
614
+            );
615
+        });
616
+        $this->registerAlias('TempManager', TempManager::class);
617
+        $this->registerAlias(ITempManager::class, TempManager::class);
618
+
619
+        $this->registerService(AppManager::class, function (Server $c) {
620
+            return new \OC\App\AppManager(
621
+                $c->getUserSession(),
622
+                $c->getAppConfig(),
623
+                $c->getGroupManager(),
624
+                $c->getMemCacheFactory(),
625
+                $c->getEventDispatcher()
626
+            );
627
+        });
628
+        $this->registerAlias('AppManager', AppManager::class);
629
+        $this->registerAlias(IAppManager::class, AppManager::class);
630
+
631
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
632
+            return new DateTimeZone(
633
+                $c->getConfig(),
634
+                $c->getSession()
635
+            );
636
+        });
637
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
638
+
639
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
640
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
641
+
642
+            return new DateTimeFormatter(
643
+                $c->getDateTimeZone()->getTimeZone(),
644
+                $c->getL10N('lib', $language)
645
+            );
646
+        });
647
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
648
+
649
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
650
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
651
+            $listener = new UserMountCacheListener($mountCache);
652
+            $listener->listen($c->getUserManager());
653
+            return $mountCache;
654
+        });
655
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
656
+
657
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
658
+            $loader = \OC\Files\Filesystem::getLoader();
659
+            $mountCache = $c->query('UserMountCache');
660
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
661
+
662
+            // builtin providers
663
+
664
+            $config = $c->getConfig();
665
+            $manager->registerProvider(new CacheMountProvider($config));
666
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
667
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
668
+
669
+            return $manager;
670
+        });
671
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
672
+
673
+        $this->registerService('IniWrapper', function ($c) {
674
+            return new IniGetWrapper();
675
+        });
676
+        $this->registerService('AsyncCommandBus', function (Server $c) {
677
+            $jobList = $c->getJobList();
678
+            return new AsyncBus($jobList);
679
+        });
680
+        $this->registerService('TrustedDomainHelper', function ($c) {
681
+            return new TrustedDomainHelper($this->getConfig());
682
+        });
683
+        $this->registerService('Throttler', function(Server $c) {
684
+            return new Throttler(
685
+                $c->getDatabaseConnection(),
686
+                new TimeFactory(),
687
+                $c->getLogger(),
688
+                $c->getConfig()
689
+            );
690
+        });
691
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
692
+            // IConfig and IAppManager requires a working database. This code
693
+            // might however be called when ownCloud is not yet setup.
694
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
695
+                $config = $c->getConfig();
696
+                $appManager = $c->getAppManager();
697
+            } else {
698
+                $config = null;
699
+                $appManager = null;
700
+            }
701
+
702
+            return new Checker(
703
+                    new EnvironmentHelper(),
704
+                    new FileAccessHelper(),
705
+                    new AppLocator(),
706
+                    $config,
707
+                    $c->getMemCacheFactory(),
708
+                    $appManager,
709
+                    $c->getTempManager()
710
+            );
711
+        });
712
+        $this->registerService(\OCP\IRequest::class, function ($c) {
713
+            if (isset($this['urlParams'])) {
714
+                $urlParams = $this['urlParams'];
715
+            } else {
716
+                $urlParams = [];
717
+            }
718
+
719
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
720
+                && in_array('fakeinput', stream_get_wrappers())
721
+            ) {
722
+                $stream = 'fakeinput://data';
723
+            } else {
724
+                $stream = 'php://input';
725
+            }
726
+
727
+            return new Request(
728
+                [
729
+                    'get' => $_GET,
730
+                    'post' => $_POST,
731
+                    'files' => $_FILES,
732
+                    'server' => $_SERVER,
733
+                    'env' => $_ENV,
734
+                    'cookies' => $_COOKIE,
735
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
736
+                        ? $_SERVER['REQUEST_METHOD']
737
+                        : null,
738
+                    'urlParams' => $urlParams,
739
+                ],
740
+                $this->getSecureRandom(),
741
+                $this->getConfig(),
742
+                $this->getCsrfTokenManager(),
743
+                $stream
744
+            );
745
+        });
746
+        $this->registerAlias('Request', \OCP\IRequest::class);
747
+
748
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
749
+            return new Mailer(
750
+                $c->getConfig(),
751
+                $c->getLogger(),
752
+                $c->query(Defaults::class),
753
+                $c->getURLGenerator(),
754
+                $c->getL10N('lib')
755
+            );
756
+        });
757
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
758
+
759
+        $this->registerService('LDAPProvider', function(Server $c) {
760
+            $config = $c->getConfig();
761
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
762
+            if(is_null($factoryClass)) {
763
+                throw new \Exception('ldapProviderFactory not set');
764
+            }
765
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
766
+            $factory = new $factoryClass($this);
767
+            return $factory->getLDAPProvider();
768
+        });
769
+        $this->registerService('LockingProvider', function (Server $c) {
770
+            $ini = $c->getIniWrapper();
771
+            $config = $c->getConfig();
772
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
773
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
774
+                /** @var \OC\Memcache\Factory $memcacheFactory */
775
+                $memcacheFactory = $c->getMemCacheFactory();
776
+                $memcache = $memcacheFactory->createLocking('lock');
777
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
778
+                    return new MemcacheLockingProvider($memcache, $ttl);
779
+                }
780
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
781
+            }
782
+            return new NoopLockingProvider();
783
+        });
784
+
785
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
786
+            return new \OC\Files\Mount\Manager();
787
+        });
788
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
789
+
790
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
791
+            return new \OC\Files\Type\Detection(
792
+                $c->getURLGenerator(),
793
+                \OC::$configDir,
794
+                \OC::$SERVERROOT . '/resources/config/'
795
+            );
796
+        });
797
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
798
+
799
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
800
+            return new \OC\Files\Type\Loader(
801
+                $c->getDatabaseConnection()
802
+            );
803
+        });
804
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
805
+
806
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
807
+            return new Manager(
808
+                $c->query(IValidator::class)
809
+            );
810
+        });
811
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
812
+
813
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
814
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
815
+            $manager->registerCapability(function () use ($c) {
816
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
817
+            });
818
+            return $manager;
819
+        });
820
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
821
+
822
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
823
+            $config = $c->getConfig();
824
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
825
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
826
+            $factory = new $factoryClass($this);
827
+            return $factory->getManager();
828
+        });
829
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
830
+
831
+        $this->registerService('ThemingDefaults', function(Server $c) {
832
+            /*
833 833
 			 * Dark magic for autoloader.
834 834
 			 * If we do a class_exists it will try to load the class which will
835 835
 			 * make composer cache the result. Resulting in errors when enabling
836 836
 			 * the theming app.
837 837
 			 */
838
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
839
-			if (isset($prefixes['OCA\\Theming\\'])) {
840
-				$classExists = true;
841
-			} else {
842
-				$classExists = false;
843
-			}
844
-
845
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
846
-				return new ThemingDefaults(
847
-					$c->getConfig(),
848
-					$c->getL10N('theming'),
849
-					$c->getURLGenerator(),
850
-					new \OC_Defaults(),
851
-					$c->getAppDataDir('theming'),
852
-					$c->getMemCacheFactory()
853
-				);
854
-			}
855
-			return new \OC_Defaults();
856
-		});
857
-		$this->registerService(EventDispatcher::class, function () {
858
-			return new EventDispatcher();
859
-		});
860
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
861
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
862
-
863
-		$this->registerService('CryptoWrapper', function (Server $c) {
864
-			// FIXME: Instantiiated here due to cyclic dependency
865
-			$request = new Request(
866
-				[
867
-					'get' => $_GET,
868
-					'post' => $_POST,
869
-					'files' => $_FILES,
870
-					'server' => $_SERVER,
871
-					'env' => $_ENV,
872
-					'cookies' => $_COOKIE,
873
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
874
-						? $_SERVER['REQUEST_METHOD']
875
-						: null,
876
-				],
877
-				$c->getSecureRandom(),
878
-				$c->getConfig()
879
-			);
880
-
881
-			return new CryptoWrapper(
882
-				$c->getConfig(),
883
-				$c->getCrypto(),
884
-				$c->getSecureRandom(),
885
-				$request
886
-			);
887
-		});
888
-		$this->registerService('CsrfTokenManager', function (Server $c) {
889
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
890
-
891
-			return new CsrfTokenManager(
892
-				$tokenGenerator,
893
-				$c->query(SessionStorage::class)
894
-			);
895
-		});
896
-		$this->registerService(SessionStorage::class, function (Server $c) {
897
-			return new SessionStorage($c->getSession());
898
-		});
899
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
900
-			return new ContentSecurityPolicyManager();
901
-		});
902
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
903
-
904
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
905
-			return new ContentSecurityPolicyNonceManager(
906
-				$c->getCsrfTokenManager(),
907
-				$c->getRequest()
908
-			);
909
-		});
910
-
911
-		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
912
-			$config = $c->getConfig();
913
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
914
-			/** @var \OCP\Share\IProviderFactory $factory */
915
-			$factory = new $factoryClass($this);
916
-
917
-			$manager = new \OC\Share20\Manager(
918
-				$c->getLogger(),
919
-				$c->getConfig(),
920
-				$c->getSecureRandom(),
921
-				$c->getHasher(),
922
-				$c->getMountManager(),
923
-				$c->getGroupManager(),
924
-				$c->getL10N('core'),
925
-				$factory,
926
-				$c->getUserManager(),
927
-				$c->getLazyRootFolder(),
928
-				$c->getEventDispatcher()
929
-			);
930
-
931
-			return $manager;
932
-		});
933
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
934
-
935
-		$this->registerService('SettingsManager', function(Server $c) {
936
-			$manager = new \OC\Settings\Manager(
937
-				$c->getLogger(),
938
-				$c->getDatabaseConnection(),
939
-				$c->getL10N('lib'),
940
-				$c->getConfig(),
941
-				$c->getEncryptionManager(),
942
-				$c->getUserManager(),
943
-				$c->getLockingProvider(),
944
-				$c->getRequest(),
945
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
946
-				$c->getURLGenerator()
947
-			);
948
-			return $manager;
949
-		});
950
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
951
-			return new \OC\Files\AppData\Factory(
952
-				$c->getRootFolder(),
953
-				$c->getSystemConfig()
954
-			);
955
-		});
956
-
957
-		$this->registerService('LockdownManager', function (Server $c) {
958
-			return new LockdownManager(function() use ($c) {
959
-				return $c->getSession();
960
-			});
961
-		});
962
-
963
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
964
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
965
-		});
966
-
967
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
968
-			return new CloudIdManager();
969
-		});
970
-
971
-		/* To trick DI since we don't extend the DIContainer here */
972
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
973
-			return new CleanPreviewsBackgroundJob(
974
-				$c->getRootFolder(),
975
-				$c->getLogger(),
976
-				$c->getJobList(),
977
-				new TimeFactory()
978
-			);
979
-		});
980
-
981
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
982
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
983
-
984
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
985
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
986
-
987
-		$this->registerService(Defaults::class, function (Server $c) {
988
-			return new Defaults(
989
-				$c->getThemingDefaults()
990
-			);
991
-		});
992
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
993
-
994
-		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
995
-			return $c->query(\OCP\IUserSession::class)->getSession();
996
-		});
997
-
998
-		$this->registerService(IShareHelper::class, function(Server $c) {
999
-			return new ShareHelper(
1000
-				$c->query(\OCP\Share\IManager::class)
1001
-			);
1002
-		});
1003
-	}
1004
-
1005
-	/**
1006
-	 * @return \OCP\Contacts\IManager
1007
-	 */
1008
-	public function getContactsManager() {
1009
-		return $this->query('ContactsManager');
1010
-	}
1011
-
1012
-	/**
1013
-	 * @return \OC\Encryption\Manager
1014
-	 */
1015
-	public function getEncryptionManager() {
1016
-		return $this->query('EncryptionManager');
1017
-	}
1018
-
1019
-	/**
1020
-	 * @return \OC\Encryption\File
1021
-	 */
1022
-	public function getEncryptionFilesHelper() {
1023
-		return $this->query('EncryptionFileHelper');
1024
-	}
1025
-
1026
-	/**
1027
-	 * @return \OCP\Encryption\Keys\IStorage
1028
-	 */
1029
-	public function getEncryptionKeyStorage() {
1030
-		return $this->query('EncryptionKeyStorage');
1031
-	}
1032
-
1033
-	/**
1034
-	 * The current request object holding all information about the request
1035
-	 * currently being processed is returned from this method.
1036
-	 * In case the current execution was not initiated by a web request null is returned
1037
-	 *
1038
-	 * @return \OCP\IRequest
1039
-	 */
1040
-	public function getRequest() {
1041
-		return $this->query('Request');
1042
-	}
1043
-
1044
-	/**
1045
-	 * Returns the preview manager which can create preview images for a given file
1046
-	 *
1047
-	 * @return \OCP\IPreview
1048
-	 */
1049
-	public function getPreviewManager() {
1050
-		return $this->query('PreviewManager');
1051
-	}
1052
-
1053
-	/**
1054
-	 * Returns the tag manager which can get and set tags for different object types
1055
-	 *
1056
-	 * @see \OCP\ITagManager::load()
1057
-	 * @return \OCP\ITagManager
1058
-	 */
1059
-	public function getTagManager() {
1060
-		return $this->query('TagManager');
1061
-	}
1062
-
1063
-	/**
1064
-	 * Returns the system-tag manager
1065
-	 *
1066
-	 * @return \OCP\SystemTag\ISystemTagManager
1067
-	 *
1068
-	 * @since 9.0.0
1069
-	 */
1070
-	public function getSystemTagManager() {
1071
-		return $this->query('SystemTagManager');
1072
-	}
1073
-
1074
-	/**
1075
-	 * Returns the system-tag object mapper
1076
-	 *
1077
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1078
-	 *
1079
-	 * @since 9.0.0
1080
-	 */
1081
-	public function getSystemTagObjectMapper() {
1082
-		return $this->query('SystemTagObjectMapper');
1083
-	}
1084
-
1085
-	/**
1086
-	 * Returns the avatar manager, used for avatar functionality
1087
-	 *
1088
-	 * @return \OCP\IAvatarManager
1089
-	 */
1090
-	public function getAvatarManager() {
1091
-		return $this->query('AvatarManager');
1092
-	}
1093
-
1094
-	/**
1095
-	 * Returns the root folder of ownCloud's data directory
1096
-	 *
1097
-	 * @return \OCP\Files\IRootFolder
1098
-	 */
1099
-	public function getRootFolder() {
1100
-		return $this->query('LazyRootFolder');
1101
-	}
1102
-
1103
-	/**
1104
-	 * Returns the root folder of ownCloud's data directory
1105
-	 * This is the lazy variant so this gets only initialized once it
1106
-	 * is actually used.
1107
-	 *
1108
-	 * @return \OCP\Files\IRootFolder
1109
-	 */
1110
-	public function getLazyRootFolder() {
1111
-		return $this->query('LazyRootFolder');
1112
-	}
1113
-
1114
-	/**
1115
-	 * Returns a view to ownCloud's files folder
1116
-	 *
1117
-	 * @param string $userId user ID
1118
-	 * @return \OCP\Files\Folder|null
1119
-	 */
1120
-	public function getUserFolder($userId = null) {
1121
-		if ($userId === null) {
1122
-			$user = $this->getUserSession()->getUser();
1123
-			if (!$user) {
1124
-				return null;
1125
-			}
1126
-			$userId = $user->getUID();
1127
-		}
1128
-		$root = $this->getRootFolder();
1129
-		return $root->getUserFolder($userId);
1130
-	}
1131
-
1132
-	/**
1133
-	 * Returns an app-specific view in ownClouds data directory
1134
-	 *
1135
-	 * @return \OCP\Files\Folder
1136
-	 * @deprecated since 9.2.0 use IAppData
1137
-	 */
1138
-	public function getAppFolder() {
1139
-		$dir = '/' . \OC_App::getCurrentApp();
1140
-		$root = $this->getRootFolder();
1141
-		if (!$root->nodeExists($dir)) {
1142
-			$folder = $root->newFolder($dir);
1143
-		} else {
1144
-			$folder = $root->get($dir);
1145
-		}
1146
-		return $folder;
1147
-	}
1148
-
1149
-	/**
1150
-	 * @return \OC\User\Manager
1151
-	 */
1152
-	public function getUserManager() {
1153
-		return $this->query('UserManager');
1154
-	}
1155
-
1156
-	/**
1157
-	 * @return \OC\Group\Manager
1158
-	 */
1159
-	public function getGroupManager() {
1160
-		return $this->query('GroupManager');
1161
-	}
1162
-
1163
-	/**
1164
-	 * @return \OC\User\Session
1165
-	 */
1166
-	public function getUserSession() {
1167
-		return $this->query('UserSession');
1168
-	}
1169
-
1170
-	/**
1171
-	 * @return \OCP\ISession
1172
-	 */
1173
-	public function getSession() {
1174
-		return $this->query('UserSession')->getSession();
1175
-	}
1176
-
1177
-	/**
1178
-	 * @param \OCP\ISession $session
1179
-	 */
1180
-	public function setSession(\OCP\ISession $session) {
1181
-		$this->query(SessionStorage::class)->setSession($session);
1182
-		$this->query('UserSession')->setSession($session);
1183
-		$this->query(Store::class)->setSession($session);
1184
-	}
1185
-
1186
-	/**
1187
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1188
-	 */
1189
-	public function getTwoFactorAuthManager() {
1190
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1191
-	}
1192
-
1193
-	/**
1194
-	 * @return \OC\NavigationManager
1195
-	 */
1196
-	public function getNavigationManager() {
1197
-		return $this->query('NavigationManager');
1198
-	}
1199
-
1200
-	/**
1201
-	 * @return \OCP\IConfig
1202
-	 */
1203
-	public function getConfig() {
1204
-		return $this->query('AllConfig');
1205
-	}
1206
-
1207
-	/**
1208
-	 * @internal For internal use only
1209
-	 * @return \OC\SystemConfig
1210
-	 */
1211
-	public function getSystemConfig() {
1212
-		return $this->query('SystemConfig');
1213
-	}
1214
-
1215
-	/**
1216
-	 * Returns the app config manager
1217
-	 *
1218
-	 * @return \OCP\IAppConfig
1219
-	 */
1220
-	public function getAppConfig() {
1221
-		return $this->query('AppConfig');
1222
-	}
1223
-
1224
-	/**
1225
-	 * @return \OCP\L10N\IFactory
1226
-	 */
1227
-	public function getL10NFactory() {
1228
-		return $this->query('L10NFactory');
1229
-	}
1230
-
1231
-	/**
1232
-	 * get an L10N instance
1233
-	 *
1234
-	 * @param string $app appid
1235
-	 * @param string $lang
1236
-	 * @return IL10N
1237
-	 */
1238
-	public function getL10N($app, $lang = null) {
1239
-		return $this->getL10NFactory()->get($app, $lang);
1240
-	}
1241
-
1242
-	/**
1243
-	 * @return \OCP\IURLGenerator
1244
-	 */
1245
-	public function getURLGenerator() {
1246
-		return $this->query('URLGenerator');
1247
-	}
1248
-
1249
-	/**
1250
-	 * @return \OCP\IHelper
1251
-	 */
1252
-	public function getHelper() {
1253
-		return $this->query('AppHelper');
1254
-	}
1255
-
1256
-	/**
1257
-	 * @return AppFetcher
1258
-	 */
1259
-	public function getAppFetcher() {
1260
-		return $this->query('AppFetcher');
1261
-	}
1262
-
1263
-	/**
1264
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1265
-	 * getMemCacheFactory() instead.
1266
-	 *
1267
-	 * @return \OCP\ICache
1268
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1269
-	 */
1270
-	public function getCache() {
1271
-		return $this->query('UserCache');
1272
-	}
1273
-
1274
-	/**
1275
-	 * Returns an \OCP\CacheFactory instance
1276
-	 *
1277
-	 * @return \OCP\ICacheFactory
1278
-	 */
1279
-	public function getMemCacheFactory() {
1280
-		return $this->query('MemCacheFactory');
1281
-	}
1282
-
1283
-	/**
1284
-	 * Returns an \OC\RedisFactory instance
1285
-	 *
1286
-	 * @return \OC\RedisFactory
1287
-	 */
1288
-	public function getGetRedisFactory() {
1289
-		return $this->query('RedisFactory');
1290
-	}
1291
-
1292
-
1293
-	/**
1294
-	 * Returns the current session
1295
-	 *
1296
-	 * @return \OCP\IDBConnection
1297
-	 */
1298
-	public function getDatabaseConnection() {
1299
-		return $this->query('DatabaseConnection');
1300
-	}
1301
-
1302
-	/**
1303
-	 * Returns the activity manager
1304
-	 *
1305
-	 * @return \OCP\Activity\IManager
1306
-	 */
1307
-	public function getActivityManager() {
1308
-		return $this->query('ActivityManager');
1309
-	}
1310
-
1311
-	/**
1312
-	 * Returns an job list for controlling background jobs
1313
-	 *
1314
-	 * @return \OCP\BackgroundJob\IJobList
1315
-	 */
1316
-	public function getJobList() {
1317
-		return $this->query('JobList');
1318
-	}
1319
-
1320
-	/**
1321
-	 * Returns a logger instance
1322
-	 *
1323
-	 * @return \OCP\ILogger
1324
-	 */
1325
-	public function getLogger() {
1326
-		return $this->query('Logger');
1327
-	}
1328
-
1329
-	/**
1330
-	 * Returns a router for generating and matching urls
1331
-	 *
1332
-	 * @return \OCP\Route\IRouter
1333
-	 */
1334
-	public function getRouter() {
1335
-		return $this->query('Router');
1336
-	}
1337
-
1338
-	/**
1339
-	 * Returns a search instance
1340
-	 *
1341
-	 * @return \OCP\ISearch
1342
-	 */
1343
-	public function getSearch() {
1344
-		return $this->query('Search');
1345
-	}
1346
-
1347
-	/**
1348
-	 * Returns a SecureRandom instance
1349
-	 *
1350
-	 * @return \OCP\Security\ISecureRandom
1351
-	 */
1352
-	public function getSecureRandom() {
1353
-		return $this->query('SecureRandom');
1354
-	}
1355
-
1356
-	/**
1357
-	 * Returns a Crypto instance
1358
-	 *
1359
-	 * @return \OCP\Security\ICrypto
1360
-	 */
1361
-	public function getCrypto() {
1362
-		return $this->query('Crypto');
1363
-	}
1364
-
1365
-	/**
1366
-	 * Returns a Hasher instance
1367
-	 *
1368
-	 * @return \OCP\Security\IHasher
1369
-	 */
1370
-	public function getHasher() {
1371
-		return $this->query('Hasher');
1372
-	}
1373
-
1374
-	/**
1375
-	 * Returns a CredentialsManager instance
1376
-	 *
1377
-	 * @return \OCP\Security\ICredentialsManager
1378
-	 */
1379
-	public function getCredentialsManager() {
1380
-		return $this->query('CredentialsManager');
1381
-	}
1382
-
1383
-	/**
1384
-	 * Returns an instance of the HTTP helper class
1385
-	 *
1386
-	 * @deprecated Use getHTTPClientService()
1387
-	 * @return \OC\HTTPHelper
1388
-	 */
1389
-	public function getHTTPHelper() {
1390
-		return $this->query('HTTPHelper');
1391
-	}
1392
-
1393
-	/**
1394
-	 * Get the certificate manager for the user
1395
-	 *
1396
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1397
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1398
-	 */
1399
-	public function getCertificateManager($userId = '') {
1400
-		if ($userId === '') {
1401
-			$userSession = $this->getUserSession();
1402
-			$user = $userSession->getUser();
1403
-			if (is_null($user)) {
1404
-				return null;
1405
-			}
1406
-			$userId = $user->getUID();
1407
-		}
1408
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1409
-	}
1410
-
1411
-	/**
1412
-	 * Returns an instance of the HTTP client service
1413
-	 *
1414
-	 * @return \OCP\Http\Client\IClientService
1415
-	 */
1416
-	public function getHTTPClientService() {
1417
-		return $this->query('HttpClientService');
1418
-	}
1419
-
1420
-	/**
1421
-	 * Create a new event source
1422
-	 *
1423
-	 * @return \OCP\IEventSource
1424
-	 */
1425
-	public function createEventSource() {
1426
-		return new \OC_EventSource();
1427
-	}
1428
-
1429
-	/**
1430
-	 * Get the active event logger
1431
-	 *
1432
-	 * The returned logger only logs data when debug mode is enabled
1433
-	 *
1434
-	 * @return \OCP\Diagnostics\IEventLogger
1435
-	 */
1436
-	public function getEventLogger() {
1437
-		return $this->query('EventLogger');
1438
-	}
1439
-
1440
-	/**
1441
-	 * Get the active query logger
1442
-	 *
1443
-	 * The returned logger only logs data when debug mode is enabled
1444
-	 *
1445
-	 * @return \OCP\Diagnostics\IQueryLogger
1446
-	 */
1447
-	public function getQueryLogger() {
1448
-		return $this->query('QueryLogger');
1449
-	}
1450
-
1451
-	/**
1452
-	 * Get the manager for temporary files and folders
1453
-	 *
1454
-	 * @return \OCP\ITempManager
1455
-	 */
1456
-	public function getTempManager() {
1457
-		return $this->query('TempManager');
1458
-	}
1459
-
1460
-	/**
1461
-	 * Get the app manager
1462
-	 *
1463
-	 * @return \OCP\App\IAppManager
1464
-	 */
1465
-	public function getAppManager() {
1466
-		return $this->query('AppManager');
1467
-	}
1468
-
1469
-	/**
1470
-	 * Creates a new mailer
1471
-	 *
1472
-	 * @return \OCP\Mail\IMailer
1473
-	 */
1474
-	public function getMailer() {
1475
-		return $this->query('Mailer');
1476
-	}
1477
-
1478
-	/**
1479
-	 * Get the webroot
1480
-	 *
1481
-	 * @return string
1482
-	 */
1483
-	public function getWebRoot() {
1484
-		return $this->webRoot;
1485
-	}
1486
-
1487
-	/**
1488
-	 * @return \OC\OCSClient
1489
-	 */
1490
-	public function getOcsClient() {
1491
-		return $this->query('OcsClient');
1492
-	}
1493
-
1494
-	/**
1495
-	 * @return \OCP\IDateTimeZone
1496
-	 */
1497
-	public function getDateTimeZone() {
1498
-		return $this->query('DateTimeZone');
1499
-	}
1500
-
1501
-	/**
1502
-	 * @return \OCP\IDateTimeFormatter
1503
-	 */
1504
-	public function getDateTimeFormatter() {
1505
-		return $this->query('DateTimeFormatter');
1506
-	}
1507
-
1508
-	/**
1509
-	 * @return \OCP\Files\Config\IMountProviderCollection
1510
-	 */
1511
-	public function getMountProviderCollection() {
1512
-		return $this->query('MountConfigManager');
1513
-	}
1514
-
1515
-	/**
1516
-	 * Get the IniWrapper
1517
-	 *
1518
-	 * @return IniGetWrapper
1519
-	 */
1520
-	public function getIniWrapper() {
1521
-		return $this->query('IniWrapper');
1522
-	}
1523
-
1524
-	/**
1525
-	 * @return \OCP\Command\IBus
1526
-	 */
1527
-	public function getCommandBus() {
1528
-		return $this->query('AsyncCommandBus');
1529
-	}
1530
-
1531
-	/**
1532
-	 * Get the trusted domain helper
1533
-	 *
1534
-	 * @return TrustedDomainHelper
1535
-	 */
1536
-	public function getTrustedDomainHelper() {
1537
-		return $this->query('TrustedDomainHelper');
1538
-	}
1539
-
1540
-	/**
1541
-	 * Get the locking provider
1542
-	 *
1543
-	 * @return \OCP\Lock\ILockingProvider
1544
-	 * @since 8.1.0
1545
-	 */
1546
-	public function getLockingProvider() {
1547
-		return $this->query('LockingProvider');
1548
-	}
1549
-
1550
-	/**
1551
-	 * @return \OCP\Files\Mount\IMountManager
1552
-	 **/
1553
-	function getMountManager() {
1554
-		return $this->query('MountManager');
1555
-	}
1556
-
1557
-	/** @return \OCP\Files\Config\IUserMountCache */
1558
-	function getUserMountCache() {
1559
-		return $this->query('UserMountCache');
1560
-	}
1561
-
1562
-	/**
1563
-	 * Get the MimeTypeDetector
1564
-	 *
1565
-	 * @return \OCP\Files\IMimeTypeDetector
1566
-	 */
1567
-	public function getMimeTypeDetector() {
1568
-		return $this->query('MimeTypeDetector');
1569
-	}
1570
-
1571
-	/**
1572
-	 * Get the MimeTypeLoader
1573
-	 *
1574
-	 * @return \OCP\Files\IMimeTypeLoader
1575
-	 */
1576
-	public function getMimeTypeLoader() {
1577
-		return $this->query('MimeTypeLoader');
1578
-	}
1579
-
1580
-	/**
1581
-	 * Get the manager of all the capabilities
1582
-	 *
1583
-	 * @return \OC\CapabilitiesManager
1584
-	 */
1585
-	public function getCapabilitiesManager() {
1586
-		return $this->query('CapabilitiesManager');
1587
-	}
1588
-
1589
-	/**
1590
-	 * Get the EventDispatcher
1591
-	 *
1592
-	 * @return EventDispatcherInterface
1593
-	 * @since 8.2.0
1594
-	 */
1595
-	public function getEventDispatcher() {
1596
-		return $this->query('EventDispatcher');
1597
-	}
1598
-
1599
-	/**
1600
-	 * Get the Notification Manager
1601
-	 *
1602
-	 * @return \OCP\Notification\IManager
1603
-	 * @since 8.2.0
1604
-	 */
1605
-	public function getNotificationManager() {
1606
-		return $this->query('NotificationManager');
1607
-	}
1608
-
1609
-	/**
1610
-	 * @return \OCP\Comments\ICommentsManager
1611
-	 */
1612
-	public function getCommentsManager() {
1613
-		return $this->query('CommentsManager');
1614
-	}
1615
-
1616
-	/**
1617
-	 * @return \OCA\Theming\ThemingDefaults
1618
-	 */
1619
-	public function getThemingDefaults() {
1620
-		return $this->query('ThemingDefaults');
1621
-	}
1622
-
1623
-	/**
1624
-	 * @return \OC\IntegrityCheck\Checker
1625
-	 */
1626
-	public function getIntegrityCodeChecker() {
1627
-		return $this->query('IntegrityCodeChecker');
1628
-	}
1629
-
1630
-	/**
1631
-	 * @return \OC\Session\CryptoWrapper
1632
-	 */
1633
-	public function getSessionCryptoWrapper() {
1634
-		return $this->query('CryptoWrapper');
1635
-	}
1636
-
1637
-	/**
1638
-	 * @return CsrfTokenManager
1639
-	 */
1640
-	public function getCsrfTokenManager() {
1641
-		return $this->query('CsrfTokenManager');
1642
-	}
1643
-
1644
-	/**
1645
-	 * @return Throttler
1646
-	 */
1647
-	public function getBruteForceThrottler() {
1648
-		return $this->query('Throttler');
1649
-	}
1650
-
1651
-	/**
1652
-	 * @return IContentSecurityPolicyManager
1653
-	 */
1654
-	public function getContentSecurityPolicyManager() {
1655
-		return $this->query('ContentSecurityPolicyManager');
1656
-	}
1657
-
1658
-	/**
1659
-	 * @return ContentSecurityPolicyNonceManager
1660
-	 */
1661
-	public function getContentSecurityPolicyNonceManager() {
1662
-		return $this->query('ContentSecurityPolicyNonceManager');
1663
-	}
1664
-
1665
-	/**
1666
-	 * Not a public API as of 8.2, wait for 9.0
1667
-	 *
1668
-	 * @return \OCA\Files_External\Service\BackendService
1669
-	 */
1670
-	public function getStoragesBackendService() {
1671
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1672
-	}
1673
-
1674
-	/**
1675
-	 * Not a public API as of 8.2, wait for 9.0
1676
-	 *
1677
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1678
-	 */
1679
-	public function getGlobalStoragesService() {
1680
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1681
-	}
1682
-
1683
-	/**
1684
-	 * Not a public API as of 8.2, wait for 9.0
1685
-	 *
1686
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1687
-	 */
1688
-	public function getUserGlobalStoragesService() {
1689
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1690
-	}
1691
-
1692
-	/**
1693
-	 * Not a public API as of 8.2, wait for 9.0
1694
-	 *
1695
-	 * @return \OCA\Files_External\Service\UserStoragesService
1696
-	 */
1697
-	public function getUserStoragesService() {
1698
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1699
-	}
1700
-
1701
-	/**
1702
-	 * @return \OCP\Share\IManager
1703
-	 */
1704
-	public function getShareManager() {
1705
-		return $this->query('ShareManager');
1706
-	}
1707
-
1708
-	/**
1709
-	 * Returns the LDAP Provider
1710
-	 *
1711
-	 * @return \OCP\LDAP\ILDAPProvider
1712
-	 */
1713
-	public function getLDAPProvider() {
1714
-		return $this->query('LDAPProvider');
1715
-	}
1716
-
1717
-	/**
1718
-	 * @return \OCP\Settings\IManager
1719
-	 */
1720
-	public function getSettingsManager() {
1721
-		return $this->query('SettingsManager');
1722
-	}
1723
-
1724
-	/**
1725
-	 * @return \OCP\Files\IAppData
1726
-	 */
1727
-	public function getAppDataDir($app) {
1728
-		/** @var \OC\Files\AppData\Factory $factory */
1729
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1730
-		return $factory->get($app);
1731
-	}
1732
-
1733
-	/**
1734
-	 * @return \OCP\Lockdown\ILockdownManager
1735
-	 */
1736
-	public function getLockdownManager() {
1737
-		return $this->query('LockdownManager');
1738
-	}
1739
-
1740
-	/**
1741
-	 * @return \OCP\Federation\ICloudIdManager
1742
-	 */
1743
-	public function getCloudIdManager() {
1744
-		return $this->query(ICloudIdManager::class);
1745
-	}
838
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
839
+            if (isset($prefixes['OCA\\Theming\\'])) {
840
+                $classExists = true;
841
+            } else {
842
+                $classExists = false;
843
+            }
844
+
845
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
846
+                return new ThemingDefaults(
847
+                    $c->getConfig(),
848
+                    $c->getL10N('theming'),
849
+                    $c->getURLGenerator(),
850
+                    new \OC_Defaults(),
851
+                    $c->getAppDataDir('theming'),
852
+                    $c->getMemCacheFactory()
853
+                );
854
+            }
855
+            return new \OC_Defaults();
856
+        });
857
+        $this->registerService(EventDispatcher::class, function () {
858
+            return new EventDispatcher();
859
+        });
860
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
861
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
862
+
863
+        $this->registerService('CryptoWrapper', function (Server $c) {
864
+            // FIXME: Instantiiated here due to cyclic dependency
865
+            $request = new Request(
866
+                [
867
+                    'get' => $_GET,
868
+                    'post' => $_POST,
869
+                    'files' => $_FILES,
870
+                    'server' => $_SERVER,
871
+                    'env' => $_ENV,
872
+                    'cookies' => $_COOKIE,
873
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
874
+                        ? $_SERVER['REQUEST_METHOD']
875
+                        : null,
876
+                ],
877
+                $c->getSecureRandom(),
878
+                $c->getConfig()
879
+            );
880
+
881
+            return new CryptoWrapper(
882
+                $c->getConfig(),
883
+                $c->getCrypto(),
884
+                $c->getSecureRandom(),
885
+                $request
886
+            );
887
+        });
888
+        $this->registerService('CsrfTokenManager', function (Server $c) {
889
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
890
+
891
+            return new CsrfTokenManager(
892
+                $tokenGenerator,
893
+                $c->query(SessionStorage::class)
894
+            );
895
+        });
896
+        $this->registerService(SessionStorage::class, function (Server $c) {
897
+            return new SessionStorage($c->getSession());
898
+        });
899
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
900
+            return new ContentSecurityPolicyManager();
901
+        });
902
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
903
+
904
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
905
+            return new ContentSecurityPolicyNonceManager(
906
+                $c->getCsrfTokenManager(),
907
+                $c->getRequest()
908
+            );
909
+        });
910
+
911
+        $this->registerService(\OCP\Share\IManager::class, function(Server $c) {
912
+            $config = $c->getConfig();
913
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
914
+            /** @var \OCP\Share\IProviderFactory $factory */
915
+            $factory = new $factoryClass($this);
916
+
917
+            $manager = new \OC\Share20\Manager(
918
+                $c->getLogger(),
919
+                $c->getConfig(),
920
+                $c->getSecureRandom(),
921
+                $c->getHasher(),
922
+                $c->getMountManager(),
923
+                $c->getGroupManager(),
924
+                $c->getL10N('core'),
925
+                $factory,
926
+                $c->getUserManager(),
927
+                $c->getLazyRootFolder(),
928
+                $c->getEventDispatcher()
929
+            );
930
+
931
+            return $manager;
932
+        });
933
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
934
+
935
+        $this->registerService('SettingsManager', function(Server $c) {
936
+            $manager = new \OC\Settings\Manager(
937
+                $c->getLogger(),
938
+                $c->getDatabaseConnection(),
939
+                $c->getL10N('lib'),
940
+                $c->getConfig(),
941
+                $c->getEncryptionManager(),
942
+                $c->getUserManager(),
943
+                $c->getLockingProvider(),
944
+                $c->getRequest(),
945
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
946
+                $c->getURLGenerator()
947
+            );
948
+            return $manager;
949
+        });
950
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
951
+            return new \OC\Files\AppData\Factory(
952
+                $c->getRootFolder(),
953
+                $c->getSystemConfig()
954
+            );
955
+        });
956
+
957
+        $this->registerService('LockdownManager', function (Server $c) {
958
+            return new LockdownManager(function() use ($c) {
959
+                return $c->getSession();
960
+            });
961
+        });
962
+
963
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
964
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
965
+        });
966
+
967
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
968
+            return new CloudIdManager();
969
+        });
970
+
971
+        /* To trick DI since we don't extend the DIContainer here */
972
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
973
+            return new CleanPreviewsBackgroundJob(
974
+                $c->getRootFolder(),
975
+                $c->getLogger(),
976
+                $c->getJobList(),
977
+                new TimeFactory()
978
+            );
979
+        });
980
+
981
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
982
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
983
+
984
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
985
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
986
+
987
+        $this->registerService(Defaults::class, function (Server $c) {
988
+            return new Defaults(
989
+                $c->getThemingDefaults()
990
+            );
991
+        });
992
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
993
+
994
+        $this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
995
+            return $c->query(\OCP\IUserSession::class)->getSession();
996
+        });
997
+
998
+        $this->registerService(IShareHelper::class, function(Server $c) {
999
+            return new ShareHelper(
1000
+                $c->query(\OCP\Share\IManager::class)
1001
+            );
1002
+        });
1003
+    }
1004
+
1005
+    /**
1006
+     * @return \OCP\Contacts\IManager
1007
+     */
1008
+    public function getContactsManager() {
1009
+        return $this->query('ContactsManager');
1010
+    }
1011
+
1012
+    /**
1013
+     * @return \OC\Encryption\Manager
1014
+     */
1015
+    public function getEncryptionManager() {
1016
+        return $this->query('EncryptionManager');
1017
+    }
1018
+
1019
+    /**
1020
+     * @return \OC\Encryption\File
1021
+     */
1022
+    public function getEncryptionFilesHelper() {
1023
+        return $this->query('EncryptionFileHelper');
1024
+    }
1025
+
1026
+    /**
1027
+     * @return \OCP\Encryption\Keys\IStorage
1028
+     */
1029
+    public function getEncryptionKeyStorage() {
1030
+        return $this->query('EncryptionKeyStorage');
1031
+    }
1032
+
1033
+    /**
1034
+     * The current request object holding all information about the request
1035
+     * currently being processed is returned from this method.
1036
+     * In case the current execution was not initiated by a web request null is returned
1037
+     *
1038
+     * @return \OCP\IRequest
1039
+     */
1040
+    public function getRequest() {
1041
+        return $this->query('Request');
1042
+    }
1043
+
1044
+    /**
1045
+     * Returns the preview manager which can create preview images for a given file
1046
+     *
1047
+     * @return \OCP\IPreview
1048
+     */
1049
+    public function getPreviewManager() {
1050
+        return $this->query('PreviewManager');
1051
+    }
1052
+
1053
+    /**
1054
+     * Returns the tag manager which can get and set tags for different object types
1055
+     *
1056
+     * @see \OCP\ITagManager::load()
1057
+     * @return \OCP\ITagManager
1058
+     */
1059
+    public function getTagManager() {
1060
+        return $this->query('TagManager');
1061
+    }
1062
+
1063
+    /**
1064
+     * Returns the system-tag manager
1065
+     *
1066
+     * @return \OCP\SystemTag\ISystemTagManager
1067
+     *
1068
+     * @since 9.0.0
1069
+     */
1070
+    public function getSystemTagManager() {
1071
+        return $this->query('SystemTagManager');
1072
+    }
1073
+
1074
+    /**
1075
+     * Returns the system-tag object mapper
1076
+     *
1077
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1078
+     *
1079
+     * @since 9.0.0
1080
+     */
1081
+    public function getSystemTagObjectMapper() {
1082
+        return $this->query('SystemTagObjectMapper');
1083
+    }
1084
+
1085
+    /**
1086
+     * Returns the avatar manager, used for avatar functionality
1087
+     *
1088
+     * @return \OCP\IAvatarManager
1089
+     */
1090
+    public function getAvatarManager() {
1091
+        return $this->query('AvatarManager');
1092
+    }
1093
+
1094
+    /**
1095
+     * Returns the root folder of ownCloud's data directory
1096
+     *
1097
+     * @return \OCP\Files\IRootFolder
1098
+     */
1099
+    public function getRootFolder() {
1100
+        return $this->query('LazyRootFolder');
1101
+    }
1102
+
1103
+    /**
1104
+     * Returns the root folder of ownCloud's data directory
1105
+     * This is the lazy variant so this gets only initialized once it
1106
+     * is actually used.
1107
+     *
1108
+     * @return \OCP\Files\IRootFolder
1109
+     */
1110
+    public function getLazyRootFolder() {
1111
+        return $this->query('LazyRootFolder');
1112
+    }
1113
+
1114
+    /**
1115
+     * Returns a view to ownCloud's files folder
1116
+     *
1117
+     * @param string $userId user ID
1118
+     * @return \OCP\Files\Folder|null
1119
+     */
1120
+    public function getUserFolder($userId = null) {
1121
+        if ($userId === null) {
1122
+            $user = $this->getUserSession()->getUser();
1123
+            if (!$user) {
1124
+                return null;
1125
+            }
1126
+            $userId = $user->getUID();
1127
+        }
1128
+        $root = $this->getRootFolder();
1129
+        return $root->getUserFolder($userId);
1130
+    }
1131
+
1132
+    /**
1133
+     * Returns an app-specific view in ownClouds data directory
1134
+     *
1135
+     * @return \OCP\Files\Folder
1136
+     * @deprecated since 9.2.0 use IAppData
1137
+     */
1138
+    public function getAppFolder() {
1139
+        $dir = '/' . \OC_App::getCurrentApp();
1140
+        $root = $this->getRootFolder();
1141
+        if (!$root->nodeExists($dir)) {
1142
+            $folder = $root->newFolder($dir);
1143
+        } else {
1144
+            $folder = $root->get($dir);
1145
+        }
1146
+        return $folder;
1147
+    }
1148
+
1149
+    /**
1150
+     * @return \OC\User\Manager
1151
+     */
1152
+    public function getUserManager() {
1153
+        return $this->query('UserManager');
1154
+    }
1155
+
1156
+    /**
1157
+     * @return \OC\Group\Manager
1158
+     */
1159
+    public function getGroupManager() {
1160
+        return $this->query('GroupManager');
1161
+    }
1162
+
1163
+    /**
1164
+     * @return \OC\User\Session
1165
+     */
1166
+    public function getUserSession() {
1167
+        return $this->query('UserSession');
1168
+    }
1169
+
1170
+    /**
1171
+     * @return \OCP\ISession
1172
+     */
1173
+    public function getSession() {
1174
+        return $this->query('UserSession')->getSession();
1175
+    }
1176
+
1177
+    /**
1178
+     * @param \OCP\ISession $session
1179
+     */
1180
+    public function setSession(\OCP\ISession $session) {
1181
+        $this->query(SessionStorage::class)->setSession($session);
1182
+        $this->query('UserSession')->setSession($session);
1183
+        $this->query(Store::class)->setSession($session);
1184
+    }
1185
+
1186
+    /**
1187
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1188
+     */
1189
+    public function getTwoFactorAuthManager() {
1190
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1191
+    }
1192
+
1193
+    /**
1194
+     * @return \OC\NavigationManager
1195
+     */
1196
+    public function getNavigationManager() {
1197
+        return $this->query('NavigationManager');
1198
+    }
1199
+
1200
+    /**
1201
+     * @return \OCP\IConfig
1202
+     */
1203
+    public function getConfig() {
1204
+        return $this->query('AllConfig');
1205
+    }
1206
+
1207
+    /**
1208
+     * @internal For internal use only
1209
+     * @return \OC\SystemConfig
1210
+     */
1211
+    public function getSystemConfig() {
1212
+        return $this->query('SystemConfig');
1213
+    }
1214
+
1215
+    /**
1216
+     * Returns the app config manager
1217
+     *
1218
+     * @return \OCP\IAppConfig
1219
+     */
1220
+    public function getAppConfig() {
1221
+        return $this->query('AppConfig');
1222
+    }
1223
+
1224
+    /**
1225
+     * @return \OCP\L10N\IFactory
1226
+     */
1227
+    public function getL10NFactory() {
1228
+        return $this->query('L10NFactory');
1229
+    }
1230
+
1231
+    /**
1232
+     * get an L10N instance
1233
+     *
1234
+     * @param string $app appid
1235
+     * @param string $lang
1236
+     * @return IL10N
1237
+     */
1238
+    public function getL10N($app, $lang = null) {
1239
+        return $this->getL10NFactory()->get($app, $lang);
1240
+    }
1241
+
1242
+    /**
1243
+     * @return \OCP\IURLGenerator
1244
+     */
1245
+    public function getURLGenerator() {
1246
+        return $this->query('URLGenerator');
1247
+    }
1248
+
1249
+    /**
1250
+     * @return \OCP\IHelper
1251
+     */
1252
+    public function getHelper() {
1253
+        return $this->query('AppHelper');
1254
+    }
1255
+
1256
+    /**
1257
+     * @return AppFetcher
1258
+     */
1259
+    public function getAppFetcher() {
1260
+        return $this->query('AppFetcher');
1261
+    }
1262
+
1263
+    /**
1264
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1265
+     * getMemCacheFactory() instead.
1266
+     *
1267
+     * @return \OCP\ICache
1268
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1269
+     */
1270
+    public function getCache() {
1271
+        return $this->query('UserCache');
1272
+    }
1273
+
1274
+    /**
1275
+     * Returns an \OCP\CacheFactory instance
1276
+     *
1277
+     * @return \OCP\ICacheFactory
1278
+     */
1279
+    public function getMemCacheFactory() {
1280
+        return $this->query('MemCacheFactory');
1281
+    }
1282
+
1283
+    /**
1284
+     * Returns an \OC\RedisFactory instance
1285
+     *
1286
+     * @return \OC\RedisFactory
1287
+     */
1288
+    public function getGetRedisFactory() {
1289
+        return $this->query('RedisFactory');
1290
+    }
1291
+
1292
+
1293
+    /**
1294
+     * Returns the current session
1295
+     *
1296
+     * @return \OCP\IDBConnection
1297
+     */
1298
+    public function getDatabaseConnection() {
1299
+        return $this->query('DatabaseConnection');
1300
+    }
1301
+
1302
+    /**
1303
+     * Returns the activity manager
1304
+     *
1305
+     * @return \OCP\Activity\IManager
1306
+     */
1307
+    public function getActivityManager() {
1308
+        return $this->query('ActivityManager');
1309
+    }
1310
+
1311
+    /**
1312
+     * Returns an job list for controlling background jobs
1313
+     *
1314
+     * @return \OCP\BackgroundJob\IJobList
1315
+     */
1316
+    public function getJobList() {
1317
+        return $this->query('JobList');
1318
+    }
1319
+
1320
+    /**
1321
+     * Returns a logger instance
1322
+     *
1323
+     * @return \OCP\ILogger
1324
+     */
1325
+    public function getLogger() {
1326
+        return $this->query('Logger');
1327
+    }
1328
+
1329
+    /**
1330
+     * Returns a router for generating and matching urls
1331
+     *
1332
+     * @return \OCP\Route\IRouter
1333
+     */
1334
+    public function getRouter() {
1335
+        return $this->query('Router');
1336
+    }
1337
+
1338
+    /**
1339
+     * Returns a search instance
1340
+     *
1341
+     * @return \OCP\ISearch
1342
+     */
1343
+    public function getSearch() {
1344
+        return $this->query('Search');
1345
+    }
1346
+
1347
+    /**
1348
+     * Returns a SecureRandom instance
1349
+     *
1350
+     * @return \OCP\Security\ISecureRandom
1351
+     */
1352
+    public function getSecureRandom() {
1353
+        return $this->query('SecureRandom');
1354
+    }
1355
+
1356
+    /**
1357
+     * Returns a Crypto instance
1358
+     *
1359
+     * @return \OCP\Security\ICrypto
1360
+     */
1361
+    public function getCrypto() {
1362
+        return $this->query('Crypto');
1363
+    }
1364
+
1365
+    /**
1366
+     * Returns a Hasher instance
1367
+     *
1368
+     * @return \OCP\Security\IHasher
1369
+     */
1370
+    public function getHasher() {
1371
+        return $this->query('Hasher');
1372
+    }
1373
+
1374
+    /**
1375
+     * Returns a CredentialsManager instance
1376
+     *
1377
+     * @return \OCP\Security\ICredentialsManager
1378
+     */
1379
+    public function getCredentialsManager() {
1380
+        return $this->query('CredentialsManager');
1381
+    }
1382
+
1383
+    /**
1384
+     * Returns an instance of the HTTP helper class
1385
+     *
1386
+     * @deprecated Use getHTTPClientService()
1387
+     * @return \OC\HTTPHelper
1388
+     */
1389
+    public function getHTTPHelper() {
1390
+        return $this->query('HTTPHelper');
1391
+    }
1392
+
1393
+    /**
1394
+     * Get the certificate manager for the user
1395
+     *
1396
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1397
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1398
+     */
1399
+    public function getCertificateManager($userId = '') {
1400
+        if ($userId === '') {
1401
+            $userSession = $this->getUserSession();
1402
+            $user = $userSession->getUser();
1403
+            if (is_null($user)) {
1404
+                return null;
1405
+            }
1406
+            $userId = $user->getUID();
1407
+        }
1408
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1409
+    }
1410
+
1411
+    /**
1412
+     * Returns an instance of the HTTP client service
1413
+     *
1414
+     * @return \OCP\Http\Client\IClientService
1415
+     */
1416
+    public function getHTTPClientService() {
1417
+        return $this->query('HttpClientService');
1418
+    }
1419
+
1420
+    /**
1421
+     * Create a new event source
1422
+     *
1423
+     * @return \OCP\IEventSource
1424
+     */
1425
+    public function createEventSource() {
1426
+        return new \OC_EventSource();
1427
+    }
1428
+
1429
+    /**
1430
+     * Get the active event logger
1431
+     *
1432
+     * The returned logger only logs data when debug mode is enabled
1433
+     *
1434
+     * @return \OCP\Diagnostics\IEventLogger
1435
+     */
1436
+    public function getEventLogger() {
1437
+        return $this->query('EventLogger');
1438
+    }
1439
+
1440
+    /**
1441
+     * Get the active query logger
1442
+     *
1443
+     * The returned logger only logs data when debug mode is enabled
1444
+     *
1445
+     * @return \OCP\Diagnostics\IQueryLogger
1446
+     */
1447
+    public function getQueryLogger() {
1448
+        return $this->query('QueryLogger');
1449
+    }
1450
+
1451
+    /**
1452
+     * Get the manager for temporary files and folders
1453
+     *
1454
+     * @return \OCP\ITempManager
1455
+     */
1456
+    public function getTempManager() {
1457
+        return $this->query('TempManager');
1458
+    }
1459
+
1460
+    /**
1461
+     * Get the app manager
1462
+     *
1463
+     * @return \OCP\App\IAppManager
1464
+     */
1465
+    public function getAppManager() {
1466
+        return $this->query('AppManager');
1467
+    }
1468
+
1469
+    /**
1470
+     * Creates a new mailer
1471
+     *
1472
+     * @return \OCP\Mail\IMailer
1473
+     */
1474
+    public function getMailer() {
1475
+        return $this->query('Mailer');
1476
+    }
1477
+
1478
+    /**
1479
+     * Get the webroot
1480
+     *
1481
+     * @return string
1482
+     */
1483
+    public function getWebRoot() {
1484
+        return $this->webRoot;
1485
+    }
1486
+
1487
+    /**
1488
+     * @return \OC\OCSClient
1489
+     */
1490
+    public function getOcsClient() {
1491
+        return $this->query('OcsClient');
1492
+    }
1493
+
1494
+    /**
1495
+     * @return \OCP\IDateTimeZone
1496
+     */
1497
+    public function getDateTimeZone() {
1498
+        return $this->query('DateTimeZone');
1499
+    }
1500
+
1501
+    /**
1502
+     * @return \OCP\IDateTimeFormatter
1503
+     */
1504
+    public function getDateTimeFormatter() {
1505
+        return $this->query('DateTimeFormatter');
1506
+    }
1507
+
1508
+    /**
1509
+     * @return \OCP\Files\Config\IMountProviderCollection
1510
+     */
1511
+    public function getMountProviderCollection() {
1512
+        return $this->query('MountConfigManager');
1513
+    }
1514
+
1515
+    /**
1516
+     * Get the IniWrapper
1517
+     *
1518
+     * @return IniGetWrapper
1519
+     */
1520
+    public function getIniWrapper() {
1521
+        return $this->query('IniWrapper');
1522
+    }
1523
+
1524
+    /**
1525
+     * @return \OCP\Command\IBus
1526
+     */
1527
+    public function getCommandBus() {
1528
+        return $this->query('AsyncCommandBus');
1529
+    }
1530
+
1531
+    /**
1532
+     * Get the trusted domain helper
1533
+     *
1534
+     * @return TrustedDomainHelper
1535
+     */
1536
+    public function getTrustedDomainHelper() {
1537
+        return $this->query('TrustedDomainHelper');
1538
+    }
1539
+
1540
+    /**
1541
+     * Get the locking provider
1542
+     *
1543
+     * @return \OCP\Lock\ILockingProvider
1544
+     * @since 8.1.0
1545
+     */
1546
+    public function getLockingProvider() {
1547
+        return $this->query('LockingProvider');
1548
+    }
1549
+
1550
+    /**
1551
+     * @return \OCP\Files\Mount\IMountManager
1552
+     **/
1553
+    function getMountManager() {
1554
+        return $this->query('MountManager');
1555
+    }
1556
+
1557
+    /** @return \OCP\Files\Config\IUserMountCache */
1558
+    function getUserMountCache() {
1559
+        return $this->query('UserMountCache');
1560
+    }
1561
+
1562
+    /**
1563
+     * Get the MimeTypeDetector
1564
+     *
1565
+     * @return \OCP\Files\IMimeTypeDetector
1566
+     */
1567
+    public function getMimeTypeDetector() {
1568
+        return $this->query('MimeTypeDetector');
1569
+    }
1570
+
1571
+    /**
1572
+     * Get the MimeTypeLoader
1573
+     *
1574
+     * @return \OCP\Files\IMimeTypeLoader
1575
+     */
1576
+    public function getMimeTypeLoader() {
1577
+        return $this->query('MimeTypeLoader');
1578
+    }
1579
+
1580
+    /**
1581
+     * Get the manager of all the capabilities
1582
+     *
1583
+     * @return \OC\CapabilitiesManager
1584
+     */
1585
+    public function getCapabilitiesManager() {
1586
+        return $this->query('CapabilitiesManager');
1587
+    }
1588
+
1589
+    /**
1590
+     * Get the EventDispatcher
1591
+     *
1592
+     * @return EventDispatcherInterface
1593
+     * @since 8.2.0
1594
+     */
1595
+    public function getEventDispatcher() {
1596
+        return $this->query('EventDispatcher');
1597
+    }
1598
+
1599
+    /**
1600
+     * Get the Notification Manager
1601
+     *
1602
+     * @return \OCP\Notification\IManager
1603
+     * @since 8.2.0
1604
+     */
1605
+    public function getNotificationManager() {
1606
+        return $this->query('NotificationManager');
1607
+    }
1608
+
1609
+    /**
1610
+     * @return \OCP\Comments\ICommentsManager
1611
+     */
1612
+    public function getCommentsManager() {
1613
+        return $this->query('CommentsManager');
1614
+    }
1615
+
1616
+    /**
1617
+     * @return \OCA\Theming\ThemingDefaults
1618
+     */
1619
+    public function getThemingDefaults() {
1620
+        return $this->query('ThemingDefaults');
1621
+    }
1622
+
1623
+    /**
1624
+     * @return \OC\IntegrityCheck\Checker
1625
+     */
1626
+    public function getIntegrityCodeChecker() {
1627
+        return $this->query('IntegrityCodeChecker');
1628
+    }
1629
+
1630
+    /**
1631
+     * @return \OC\Session\CryptoWrapper
1632
+     */
1633
+    public function getSessionCryptoWrapper() {
1634
+        return $this->query('CryptoWrapper');
1635
+    }
1636
+
1637
+    /**
1638
+     * @return CsrfTokenManager
1639
+     */
1640
+    public function getCsrfTokenManager() {
1641
+        return $this->query('CsrfTokenManager');
1642
+    }
1643
+
1644
+    /**
1645
+     * @return Throttler
1646
+     */
1647
+    public function getBruteForceThrottler() {
1648
+        return $this->query('Throttler');
1649
+    }
1650
+
1651
+    /**
1652
+     * @return IContentSecurityPolicyManager
1653
+     */
1654
+    public function getContentSecurityPolicyManager() {
1655
+        return $this->query('ContentSecurityPolicyManager');
1656
+    }
1657
+
1658
+    /**
1659
+     * @return ContentSecurityPolicyNonceManager
1660
+     */
1661
+    public function getContentSecurityPolicyNonceManager() {
1662
+        return $this->query('ContentSecurityPolicyNonceManager');
1663
+    }
1664
+
1665
+    /**
1666
+     * Not a public API as of 8.2, wait for 9.0
1667
+     *
1668
+     * @return \OCA\Files_External\Service\BackendService
1669
+     */
1670
+    public function getStoragesBackendService() {
1671
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1672
+    }
1673
+
1674
+    /**
1675
+     * Not a public API as of 8.2, wait for 9.0
1676
+     *
1677
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1678
+     */
1679
+    public function getGlobalStoragesService() {
1680
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1681
+    }
1682
+
1683
+    /**
1684
+     * Not a public API as of 8.2, wait for 9.0
1685
+     *
1686
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1687
+     */
1688
+    public function getUserGlobalStoragesService() {
1689
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1690
+    }
1691
+
1692
+    /**
1693
+     * Not a public API as of 8.2, wait for 9.0
1694
+     *
1695
+     * @return \OCA\Files_External\Service\UserStoragesService
1696
+     */
1697
+    public function getUserStoragesService() {
1698
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1699
+    }
1700
+
1701
+    /**
1702
+     * @return \OCP\Share\IManager
1703
+     */
1704
+    public function getShareManager() {
1705
+        return $this->query('ShareManager');
1706
+    }
1707
+
1708
+    /**
1709
+     * Returns the LDAP Provider
1710
+     *
1711
+     * @return \OCP\LDAP\ILDAPProvider
1712
+     */
1713
+    public function getLDAPProvider() {
1714
+        return $this->query('LDAPProvider');
1715
+    }
1716
+
1717
+    /**
1718
+     * @return \OCP\Settings\IManager
1719
+     */
1720
+    public function getSettingsManager() {
1721
+        return $this->query('SettingsManager');
1722
+    }
1723
+
1724
+    /**
1725
+     * @return \OCP\Files\IAppData
1726
+     */
1727
+    public function getAppDataDir($app) {
1728
+        /** @var \OC\Files\AppData\Factory $factory */
1729
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1730
+        return $factory->get($app);
1731
+    }
1732
+
1733
+    /**
1734
+     * @return \OCP\Lockdown\ILockdownManager
1735
+     */
1736
+    public function getLockdownManager() {
1737
+        return $this->query('LockdownManager');
1738
+    }
1739
+
1740
+    /**
1741
+     * @return \OCP\Federation\ICloudIdManager
1742
+     */
1743
+    public function getCloudIdManager() {
1744
+        return $this->query(ICloudIdManager::class);
1745
+    }
1746 1746
 }
Please login to merge, or discard this patch.
Spacing   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
134 134
 		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
135 135
 
136
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
136
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
137 137
 			return new PreviewManager(
138 138
 				$c->getConfig(),
139 139
 				$c->getRootFolder(),
@@ -144,13 +144,13 @@  discard block
 block discarded – undo
144 144
 		});
145 145
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
146 146
 
147
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
147
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
148 148
 			return new \OC\Preview\Watcher(
149 149
 				$c->getAppDataDir('preview')
150 150
 			);
151 151
 		});
152 152
 
153
-		$this->registerService('EncryptionManager', function (Server $c) {
153
+		$this->registerService('EncryptionManager', function(Server $c) {
154 154
 			$view = new View();
155 155
 			$util = new Encryption\Util(
156 156
 				$view,
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 			);
169 169
 		});
170 170
 
171
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
171
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
172 172
 			$util = new Encryption\Util(
173 173
 				new View(),
174 174
 				$c->getUserManager(),
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 			);
183 183
 		});
184 184
 
185
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
185
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
186 186
 			$view = new View();
187 187
 			$util = new Encryption\Util(
188 188
 				$view,
@@ -193,32 +193,32 @@  discard block
 block discarded – undo
193 193
 
194 194
 			return new Encryption\Keys\Storage($view, $util);
195 195
 		});
196
-		$this->registerService('TagMapper', function (Server $c) {
196
+		$this->registerService('TagMapper', function(Server $c) {
197 197
 			return new TagMapper($c->getDatabaseConnection());
198 198
 		});
199 199
 
200
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
200
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
201 201
 			$tagMapper = $c->query('TagMapper');
202 202
 			return new TagManager($tagMapper, $c->getUserSession());
203 203
 		});
204 204
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
205 205
 
206
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
206
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
207 207
 			$config = $c->getConfig();
208 208
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
209 209
 			/** @var \OC\SystemTag\ManagerFactory $factory */
210 210
 			$factory = new $factoryClass($this);
211 211
 			return $factory;
212 212
 		});
213
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
213
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
214 214
 			return $c->query('SystemTagManagerFactory')->getManager();
215 215
 		});
216 216
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
217 217
 
218
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
218
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
219 219
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
220 220
 		});
221
-		$this->registerService('RootFolder', function (Server $c) {
221
+		$this->registerService('RootFolder', function(Server $c) {
222 222
 			$manager = \OC\Files\Filesystem::getMountManager(null);
223 223
 			$view = new View();
224 224
 			$root = new Root(
@@ -246,30 +246,30 @@  discard block
 block discarded – undo
246 246
 		});
247 247
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
248 248
 
249
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
249
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
250 250
 			$config = $c->getConfig();
251 251
 			return new \OC\User\Manager($config);
252 252
 		});
253 253
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
254 254
 
255
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
255
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
256 256
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
257
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
257
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
258 258
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
259 259
 			});
260
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
260
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
261 261
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
262 262
 			});
263
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
263
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
264 264
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
265 265
 			});
266
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
266
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
267 267
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
268 268
 			});
269
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
269
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
270 270
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
271 271
 			});
272
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
272
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
273 273
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
274 274
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
275 275
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -289,11 +289,11 @@  discard block
 block discarded – undo
289 289
 			return new Store($session, $logger, $tokenProvider);
290 290
 		});
291 291
 		$this->registerAlias(IStore::class, Store::class);
292
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
292
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
293 293
 			$dbConnection = $c->getDatabaseConnection();
294 294
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
295 295
 		});
296
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
296
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
297 297
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
298 298
 			$crypto = $c->getCrypto();
299 299
 			$config = $c->getConfig();
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 		});
304 304
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
305 305
 
306
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
306
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
307 307
 			$manager = $c->getUserManager();
308 308
 			$session = new \OC\Session\Memory('');
309 309
 			$timeFactory = new TimeFactory();
@@ -316,40 +316,40 @@  discard block
 block discarded – undo
316 316
 			}
317 317
 
318 318
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
319
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
319
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
320 320
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
321 321
 			});
322
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
322
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
323 323
 				/** @var $user \OC\User\User */
324 324
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
325 325
 			});
326
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
326
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
327 327
 				/** @var $user \OC\User\User */
328 328
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
329 329
 			});
330
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
330
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
331 331
 				/** @var $user \OC\User\User */
332 332
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
333 333
 			});
334
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
334
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
335 335
 				/** @var $user \OC\User\User */
336 336
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
337 337
 			});
338
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
338
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
339 339
 				/** @var $user \OC\User\User */
340 340
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
341 341
 			});
342
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
342
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
343 343
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
344 344
 			});
345
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
345
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
346 346
 				/** @var $user \OC\User\User */
347 347
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
348 348
 			});
349
-			$userSession->listen('\OC\User', 'logout', function () {
349
+			$userSession->listen('\OC\User', 'logout', function() {
350 350
 				\OC_Hook::emit('OC_User', 'logout', array());
351 351
 			});
352
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
352
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
353 353
 				/** @var $user \OC\User\User */
354 354
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
355 355
 			});
@@ -357,14 +357,14 @@  discard block
 block discarded – undo
357 357
 		});
358 358
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
359 359
 
360
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
360
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
361 361
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
362 362
 		});
363 363
 
364 364
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
365 365
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
366 366
 
367
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
367
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
368 368
 			return new \OC\AllConfig(
369 369
 				$c->getSystemConfig()
370 370
 			);
@@ -372,17 +372,17 @@  discard block
 block discarded – undo
372 372
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
373 373
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
374 374
 
375
-		$this->registerService('SystemConfig', function ($c) use ($config) {
375
+		$this->registerService('SystemConfig', function($c) use ($config) {
376 376
 			return new \OC\SystemConfig($config);
377 377
 		});
378 378
 
379
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
379
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
380 380
 			return new \OC\AppConfig($c->getDatabaseConnection());
381 381
 		});
382 382
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
383 383
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
384 384
 
385
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
385
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
386 386
 			return new \OC\L10N\Factory(
387 387
 				$c->getConfig(),
388 388
 				$c->getRequest(),
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
 		});
393 393
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
394 394
 
395
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
395
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
396 396
 			$config = $c->getConfig();
397 397
 			$cacheFactory = $c->getMemCacheFactory();
398 398
 			return new \OC\URLGenerator(
@@ -402,10 +402,10 @@  discard block
 block discarded – undo
402 402
 		});
403 403
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
404 404
 
405
-		$this->registerService('AppHelper', function ($c) {
405
+		$this->registerService('AppHelper', function($c) {
406 406
 			return new \OC\AppHelper();
407 407
 		});
408
-		$this->registerService('AppFetcher', function ($c) {
408
+		$this->registerService('AppFetcher', function($c) {
409 409
 			return new AppFetcher(
410 410
 				$this->getAppDataDir('appstore'),
411 411
 				$this->getHTTPClientService(),
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 				$this->getConfig()
414 414
 			);
415 415
 		});
416
-		$this->registerService('CategoryFetcher', function ($c) {
416
+		$this->registerService('CategoryFetcher', function($c) {
417 417
 			return new CategoryFetcher(
418 418
 				$this->getAppDataDir('appstore'),
419 419
 				$this->getHTTPClientService(),
@@ -422,21 +422,21 @@  discard block
 block discarded – undo
422 422
 			);
423 423
 		});
424 424
 
425
-		$this->registerService(\OCP\ICache::class, function ($c) {
425
+		$this->registerService(\OCP\ICache::class, function($c) {
426 426
 			return new Cache\File();
427 427
 		});
428 428
 		$this->registerAlias('UserCache', \OCP\ICache::class);
429 429
 
430
-		$this->registerService(Factory::class, function (Server $c) {
430
+		$this->registerService(Factory::class, function(Server $c) {
431 431
 			$config = $c->getConfig();
432 432
 
433 433
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
434 434
 				$v = \OC_App::getAppVersions();
435
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
435
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
436 436
 				$version = implode(',', $v);
437 437
 				$instanceId = \OC_Util::getInstanceId();
438 438
 				$path = \OC::$SERVERROOT;
439
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
439
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
440 440
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
441 441
 					$config->getSystemValue('memcache.local', null),
442 442
 					$config->getSystemValue('memcache.distributed', null),
@@ -453,12 +453,12 @@  discard block
 block discarded – undo
453 453
 		$this->registerAlias('MemCacheFactory', Factory::class);
454 454
 		$this->registerAlias(ICacheFactory::class, Factory::class);
455 455
 
456
-		$this->registerService('RedisFactory', function (Server $c) {
456
+		$this->registerService('RedisFactory', function(Server $c) {
457 457
 			$systemConfig = $c->getSystemConfig();
458 458
 			return new RedisFactory($systemConfig);
459 459
 		});
460 460
 
461
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
461
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
462 462
 			return new \OC\Activity\Manager(
463 463
 				$c->getRequest(),
464 464
 				$c->getUserSession(),
@@ -468,14 +468,14 @@  discard block
 block discarded – undo
468 468
 		});
469 469
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
470 470
 
471
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
471
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
472 472
 			return new \OC\Activity\EventMerger(
473 473
 				$c->getL10N('lib')
474 474
 			);
475 475
 		});
476 476
 		$this->registerAlias(IValidator::class, Validator::class);
477 477
 
478
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
478
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
479 479
 			return new AvatarManager(
480 480
 				$c->getUserManager(),
481 481
 				$c->getAppDataDir('avatar'),
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 		});
487 487
 		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
488 488
 
489
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
489
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
490 490
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
491 491
 			$logger = Log::getLogClass($logType);
492 492
 			call_user_func(array($logger, 'init'));
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
 		});
496 496
 		$this->registerAlias('Logger', \OCP\ILogger::class);
497 497
 
498
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
498
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
499 499
 			$config = $c->getConfig();
500 500
 			return new \OC\BackgroundJob\JobList(
501 501
 				$c->getDatabaseConnection(),
@@ -505,7 +505,7 @@  discard block
 block discarded – undo
505 505
 		});
506 506
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
507 507
 
508
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
508
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
509 509
 			$cacheFactory = $c->getMemCacheFactory();
510 510
 			$logger = $c->getLogger();
511 511
 			if ($cacheFactory->isAvailable()) {
@@ -517,7 +517,7 @@  discard block
 block discarded – undo
517 517
 		});
518 518
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
519 519
 
520
-		$this->registerService(\OCP\ISearch::class, function ($c) {
520
+		$this->registerService(\OCP\ISearch::class, function($c) {
521 521
 			return new Search();
522 522
 		});
523 523
 		$this->registerAlias('Search', \OCP\ISearch::class);
@@ -537,27 +537,27 @@  discard block
 block discarded – undo
537 537
 			);
538 538
 		});
539 539
 
540
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
540
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
541 541
 			return new SecureRandom();
542 542
 		});
543 543
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
544 544
 
545
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
545
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
546 546
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
547 547
 		});
548 548
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
549 549
 
550
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
550
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
551 551
 			return new Hasher($c->getConfig());
552 552
 		});
553 553
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
554 554
 
555
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
555
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
556 556
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
557 557
 		});
558 558
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
559 559
 
560
-		$this->registerService(IDBConnection::class, function (Server $c) {
560
+		$this->registerService(IDBConnection::class, function(Server $c) {
561 561
 			$systemConfig = $c->getSystemConfig();
562 562
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
563 563
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -571,7 +571,7 @@  discard block
 block discarded – undo
571 571
 		});
572 572
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
573 573
 
574
-		$this->registerService('HTTPHelper', function (Server $c) {
574
+		$this->registerService('HTTPHelper', function(Server $c) {
575 575
 			$config = $c->getConfig();
576 576
 			return new HTTPHelper(
577 577
 				$config,
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
 			);
580 580
 		});
581 581
 
582
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
582
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
583 583
 			$user = \OC_User::getUser();
584 584
 			$uid = $user ? $user : null;
585 585
 			return new ClientService(
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
 		});
590 590
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
591 591
 
592
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
592
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
593 593
 			if ($c->getSystemConfig()->getValue('debug', false)) {
594 594
 				return new EventLogger();
595 595
 			} else {
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
 		});
599 599
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
600 600
 
601
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
601
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
602 602
 			if ($c->getSystemConfig()->getValue('debug', false)) {
603 603
 				return new QueryLogger();
604 604
 			} else {
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
 		});
608 608
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
609 609
 
610
-		$this->registerService(TempManager::class, function (Server $c) {
610
+		$this->registerService(TempManager::class, function(Server $c) {
611 611
 			return new TempManager(
612 612
 				$c->getLogger(),
613 613
 				$c->getConfig()
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 		$this->registerAlias('TempManager', TempManager::class);
617 617
 		$this->registerAlias(ITempManager::class, TempManager::class);
618 618
 
619
-		$this->registerService(AppManager::class, function (Server $c) {
619
+		$this->registerService(AppManager::class, function(Server $c) {
620 620
 			return new \OC\App\AppManager(
621 621
 				$c->getUserSession(),
622 622
 				$c->getAppConfig(),
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 		$this->registerAlias('AppManager', AppManager::class);
629 629
 		$this->registerAlias(IAppManager::class, AppManager::class);
630 630
 
631
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
631
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
632 632
 			return new DateTimeZone(
633 633
 				$c->getConfig(),
634 634
 				$c->getSession()
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
 		});
637 637
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
638 638
 
639
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
639
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
640 640
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
641 641
 
642 642
 			return new DateTimeFormatter(
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
 		});
647 647
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
648 648
 
649
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
649
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
650 650
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
651 651
 			$listener = new UserMountCacheListener($mountCache);
652 652
 			$listener->listen($c->getUserManager());
@@ -654,10 +654,10 @@  discard block
 block discarded – undo
654 654
 		});
655 655
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
656 656
 
657
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
657
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
658 658
 			$loader = \OC\Files\Filesystem::getLoader();
659 659
 			$mountCache = $c->query('UserMountCache');
660
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
660
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
661 661
 
662 662
 			// builtin providers
663 663
 
@@ -670,14 +670,14 @@  discard block
 block discarded – undo
670 670
 		});
671 671
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
672 672
 
673
-		$this->registerService('IniWrapper', function ($c) {
673
+		$this->registerService('IniWrapper', function($c) {
674 674
 			return new IniGetWrapper();
675 675
 		});
676
-		$this->registerService('AsyncCommandBus', function (Server $c) {
676
+		$this->registerService('AsyncCommandBus', function(Server $c) {
677 677
 			$jobList = $c->getJobList();
678 678
 			return new AsyncBus($jobList);
679 679
 		});
680
-		$this->registerService('TrustedDomainHelper', function ($c) {
680
+		$this->registerService('TrustedDomainHelper', function($c) {
681 681
 			return new TrustedDomainHelper($this->getConfig());
682 682
 		});
683 683
 		$this->registerService('Throttler', function(Server $c) {
@@ -688,10 +688,10 @@  discard block
 block discarded – undo
688 688
 				$c->getConfig()
689 689
 			);
690 690
 		});
691
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
691
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
692 692
 			// IConfig and IAppManager requires a working database. This code
693 693
 			// might however be called when ownCloud is not yet setup.
694
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
694
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
695 695
 				$config = $c->getConfig();
696 696
 				$appManager = $c->getAppManager();
697 697
 			} else {
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
 					$c->getTempManager()
710 710
 			);
711 711
 		});
712
-		$this->registerService(\OCP\IRequest::class, function ($c) {
712
+		$this->registerService(\OCP\IRequest::class, function($c) {
713 713
 			if (isset($this['urlParams'])) {
714 714
 				$urlParams = $this['urlParams'];
715 715
 			} else {
@@ -745,7 +745,7 @@  discard block
 block discarded – undo
745 745
 		});
746 746
 		$this->registerAlias('Request', \OCP\IRequest::class);
747 747
 
748
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
748
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
749 749
 			return new Mailer(
750 750
 				$c->getConfig(),
751 751
 				$c->getLogger(),
@@ -759,14 +759,14 @@  discard block
 block discarded – undo
759 759
 		$this->registerService('LDAPProvider', function(Server $c) {
760 760
 			$config = $c->getConfig();
761 761
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
762
-			if(is_null($factoryClass)) {
762
+			if (is_null($factoryClass)) {
763 763
 				throw new \Exception('ldapProviderFactory not set');
764 764
 			}
765 765
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
766 766
 			$factory = new $factoryClass($this);
767 767
 			return $factory->getLDAPProvider();
768 768
 		});
769
-		$this->registerService('LockingProvider', function (Server $c) {
769
+		$this->registerService('LockingProvider', function(Server $c) {
770 770
 			$ini = $c->getIniWrapper();
771 771
 			$config = $c->getConfig();
772 772
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -782,37 +782,37 @@  discard block
 block discarded – undo
782 782
 			return new NoopLockingProvider();
783 783
 		});
784 784
 
785
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
785
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
786 786
 			return new \OC\Files\Mount\Manager();
787 787
 		});
788 788
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
789 789
 
790
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
790
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
791 791
 			return new \OC\Files\Type\Detection(
792 792
 				$c->getURLGenerator(),
793 793
 				\OC::$configDir,
794
-				\OC::$SERVERROOT . '/resources/config/'
794
+				\OC::$SERVERROOT.'/resources/config/'
795 795
 			);
796 796
 		});
797 797
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
798 798
 
799
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
799
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
800 800
 			return new \OC\Files\Type\Loader(
801 801
 				$c->getDatabaseConnection()
802 802
 			);
803 803
 		});
804 804
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
805 805
 
806
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
806
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
807 807
 			return new Manager(
808 808
 				$c->query(IValidator::class)
809 809
 			);
810 810
 		});
811 811
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
812 812
 
813
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
813
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
814 814
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
815
-			$manager->registerCapability(function () use ($c) {
815
+			$manager->registerCapability(function() use ($c) {
816 816
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
817 817
 			});
818 818
 			return $manager;
@@ -854,13 +854,13 @@  discard block
 block discarded – undo
854 854
 			}
855 855
 			return new \OC_Defaults();
856 856
 		});
857
-		$this->registerService(EventDispatcher::class, function () {
857
+		$this->registerService(EventDispatcher::class, function() {
858 858
 			return new EventDispatcher();
859 859
 		});
860 860
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
861 861
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
862 862
 
863
-		$this->registerService('CryptoWrapper', function (Server $c) {
863
+		$this->registerService('CryptoWrapper', function(Server $c) {
864 864
 			// FIXME: Instantiiated here due to cyclic dependency
865 865
 			$request = new Request(
866 866
 				[
@@ -885,7 +885,7 @@  discard block
 block discarded – undo
885 885
 				$request
886 886
 			);
887 887
 		});
888
-		$this->registerService('CsrfTokenManager', function (Server $c) {
888
+		$this->registerService('CsrfTokenManager', function(Server $c) {
889 889
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
890 890
 
891 891
 			return new CsrfTokenManager(
@@ -893,10 +893,10 @@  discard block
 block discarded – undo
893 893
 				$c->query(SessionStorage::class)
894 894
 			);
895 895
 		});
896
-		$this->registerService(SessionStorage::class, function (Server $c) {
896
+		$this->registerService(SessionStorage::class, function(Server $c) {
897 897
 			return new SessionStorage($c->getSession());
898 898
 		});
899
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
899
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
900 900
 			return new ContentSecurityPolicyManager();
901 901
 		});
902 902
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
@@ -947,29 +947,29 @@  discard block
 block discarded – undo
947 947
 			);
948 948
 			return $manager;
949 949
 		});
950
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
950
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
951 951
 			return new \OC\Files\AppData\Factory(
952 952
 				$c->getRootFolder(),
953 953
 				$c->getSystemConfig()
954 954
 			);
955 955
 		});
956 956
 
957
-		$this->registerService('LockdownManager', function (Server $c) {
957
+		$this->registerService('LockdownManager', function(Server $c) {
958 958
 			return new LockdownManager(function() use ($c) {
959 959
 				return $c->getSession();
960 960
 			});
961 961
 		});
962 962
 
963
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
963
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
964 964
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
965 965
 		});
966 966
 
967
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
967
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
968 968
 			return new CloudIdManager();
969 969
 		});
970 970
 
971 971
 		/* To trick DI since we don't extend the DIContainer here */
972
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
972
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
973 973
 			return new CleanPreviewsBackgroundJob(
974 974
 				$c->getRootFolder(),
975 975
 				$c->getLogger(),
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
985 985
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
986 986
 
987
-		$this->registerService(Defaults::class, function (Server $c) {
987
+		$this->registerService(Defaults::class, function(Server $c) {
988 988
 			return new Defaults(
989 989
 				$c->getThemingDefaults()
990 990
 			);
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 	 * @deprecated since 9.2.0 use IAppData
1137 1137
 	 */
1138 1138
 	public function getAppFolder() {
1139
-		$dir = '/' . \OC_App::getCurrentApp();
1139
+		$dir = '/'.\OC_App::getCurrentApp();
1140 1140
 		$root = $this->getRootFolder();
1141 1141
 		if (!$root->nodeExists($dir)) {
1142 1142
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/Response.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 
227 227
 	/**
228 228
 	 * By default renders no output
229
-	 * @return null
229
+	 * @return string
230 230
 	 * @since 6.0.0
231 231
 	 */
232 232
 	public function render() {
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 
260 260
 	/**
261 261
 	 * Get the currently used Content-Security-Policy
262
-	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
262
+	 * @return ContentSecurityPolicy|null Used Content-Security-Policy or null if
263 263
 	 *                                    none specified.
264 264
 	 * @since 8.1.0
265 265
 	 */
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -91,8 +91,8 @@  discard block
 block discarded – undo
91 91
 	 */
92 92
 	public function cacheFor($cacheSeconds) {
93 93
 
94
-		if($cacheSeconds > 0) {
95
-			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
94
+		if ($cacheSeconds > 0) {
95
+			$this->addHeader('Cache-Control', 'max-age='.$cacheSeconds.', must-revalidate');
96 96
 		} else {
97 97
 			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98 98
 		}
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 	 * @since 8.0.0
147 147
 	 */
148 148
 	public function invalidateCookies(array $cookieNames) {
149
-		foreach($cookieNames as $cookieName) {
149
+		foreach ($cookieNames as $cookieName) {
150 150
 			$this->invalidateCookie($cookieName);
151 151
 		}
152 152
 		return $this;
@@ -170,11 +170,11 @@  discard block
 block discarded – undo
170 170
 	 * @since 6.0.0 - return value was added in 7.0.0
171 171
 	 */
172 172
 	public function addHeader($name, $value) {
173
-		$name = trim($name);  // always remove leading and trailing whitespace
173
+		$name = trim($name); // always remove leading and trailing whitespace
174 174
 		                      // to be able to reliably check for security
175 175
 		                      // headers
176 176
 
177
-		if(is_null($value)) {
177
+		if (is_null($value)) {
178 178
 			unset($this->headers[$name]);
179 179
 		} else {
180 180
 			$this->headers[$name] = $value;
@@ -205,19 +205,19 @@  discard block
 block discarded – undo
205 205
 	public function getHeaders() {
206 206
 		$mergeWith = [];
207 207
 
208
-		if($this->lastModified) {
208
+		if ($this->lastModified) {
209 209
 			$mergeWith['Last-Modified'] =
210 210
 				$this->lastModified->format(\DateTime::RFC2822);
211 211
 		}
212 212
 
213 213
 		// Build Content-Security-Policy and use default if none has been specified
214
-		if(is_null($this->contentSecurityPolicy)) {
214
+		if (is_null($this->contentSecurityPolicy)) {
215 215
 			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
216 216
 		}
217 217
 		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218 218
 
219
-		if($this->ETag) {
220
-			$mergeWith['ETag'] = '"' . $this->ETag . '"';
219
+		if ($this->ETag) {
220
+			$mergeWith['ETag'] = '"'.$this->ETag.'"';
221 221
 		}
222 222
 
223 223
 		return array_merge($mergeWith, $this->headers);
Please login to merge, or discard this patch.
Indentation   +300 added lines, -300 removed lines patch added patch discarded remove patch
@@ -42,304 +42,304 @@
 block discarded – undo
42 42
  */
43 43
 class Response {
44 44
 
45
-	/**
46
-	 * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
47
-	 * @var array
48
-	 */
49
-	private $headers = array(
50
-		'Cache-Control' => 'no-cache, no-store, must-revalidate'
51
-	);
52
-
53
-
54
-	/**
55
-	 * Cookies that will be need to be constructed as header
56
-	 * @var array
57
-	 */
58
-	private $cookies = array();
59
-
60
-
61
-	/**
62
-	 * HTTP status code - defaults to STATUS OK
63
-	 * @var int
64
-	 */
65
-	private $status = Http::STATUS_OK;
66
-
67
-
68
-	/**
69
-	 * Last modified date
70
-	 * @var \DateTime
71
-	 */
72
-	private $lastModified;
73
-
74
-
75
-	/**
76
-	 * ETag
77
-	 * @var string
78
-	 */
79
-	private $ETag;
80
-
81
-	/** @var ContentSecurityPolicy|null Used Content-Security-Policy */
82
-	private $contentSecurityPolicy = null;
83
-
84
-	/** @var bool */
85
-	private $throttled = false;
86
-
87
-	/**
88
-	 * Caches the response
89
-	 * @param int $cacheSeconds the amount of seconds that should be cached
90
-	 * if 0 then caching will be disabled
91
-	 * @return $this
92
-	 * @since 6.0.0 - return value was added in 7.0.0
93
-	 */
94
-	public function cacheFor($cacheSeconds) {
95
-
96
-		if($cacheSeconds > 0) {
97
-			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
98
-		} else {
99
-			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
100
-		}
101
-
102
-		return $this;
103
-	}
104
-
105
-	/**
106
-	 * Adds a new cookie to the response
107
-	 * @param string $name The name of the cookie
108
-	 * @param string $value The value of the cookie
109
-	 * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
110
-	 * 									to null cookie will be considered as session
111
-	 * 									cookie.
112
-	 * @return $this
113
-	 * @since 8.0.0
114
-	 */
115
-	public function addCookie($name, $value, \DateTime $expireDate = null) {
116
-		$this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
117
-		return $this;
118
-	}
119
-
120
-
121
-	/**
122
-	 * Set the specified cookies
123
-	 * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
124
-	 * @return $this
125
-	 * @since 8.0.0
126
-	 */
127
-	public function setCookies(array $cookies) {
128
-		$this->cookies = $cookies;
129
-		return $this;
130
-	}
131
-
132
-
133
-	/**
134
-	 * Invalidates the specified cookie
135
-	 * @param string $name
136
-	 * @return $this
137
-	 * @since 8.0.0
138
-	 */
139
-	public function invalidateCookie($name) {
140
-		$this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
141
-		return $this;
142
-	}
143
-
144
-	/**
145
-	 * Invalidates the specified cookies
146
-	 * @param array $cookieNames array('foo', 'bar')
147
-	 * @return $this
148
-	 * @since 8.0.0
149
-	 */
150
-	public function invalidateCookies(array $cookieNames) {
151
-		foreach($cookieNames as $cookieName) {
152
-			$this->invalidateCookie($cookieName);
153
-		}
154
-		return $this;
155
-	}
156
-
157
-	/**
158
-	 * Returns the cookies
159
-	 * @return array
160
-	 * @since 8.0.0
161
-	 */
162
-	public function getCookies() {
163
-		return $this->cookies;
164
-	}
165
-
166
-	/**
167
-	 * Adds a new header to the response that will be called before the render
168
-	 * function
169
-	 * @param string $name The name of the HTTP header
170
-	 * @param string $value The value, null will delete it
171
-	 * @return $this
172
-	 * @since 6.0.0 - return value was added in 7.0.0
173
-	 */
174
-	public function addHeader($name, $value) {
175
-		$name = trim($name);  // always remove leading and trailing whitespace
176
-		                      // to be able to reliably check for security
177
-		                      // headers
178
-
179
-		if(is_null($value)) {
180
-			unset($this->headers[$name]);
181
-		} else {
182
-			$this->headers[$name] = $value;
183
-		}
184
-
185
-		return $this;
186
-	}
187
-
188
-
189
-	/**
190
-	 * Set the headers
191
-	 * @param array $headers value header pairs
192
-	 * @return $this
193
-	 * @since 8.0.0
194
-	 */
195
-	public function setHeaders(array $headers) {
196
-		$this->headers = $headers;
197
-
198
-		return $this;
199
-	}
200
-
201
-
202
-	/**
203
-	 * Returns the set headers
204
-	 * @return array the headers
205
-	 * @since 6.0.0
206
-	 */
207
-	public function getHeaders() {
208
-		$mergeWith = [];
209
-
210
-		if($this->lastModified) {
211
-			$mergeWith['Last-Modified'] =
212
-				$this->lastModified->format(\DateTime::RFC2822);
213
-		}
214
-
215
-		// Build Content-Security-Policy and use default if none has been specified
216
-		if(is_null($this->contentSecurityPolicy)) {
217
-			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
218
-		}
219
-		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
220
-
221
-		if($this->ETag) {
222
-			$mergeWith['ETag'] = '"' . $this->ETag . '"';
223
-		}
224
-
225
-		return array_merge($mergeWith, $this->headers);
226
-	}
227
-
228
-
229
-	/**
230
-	 * By default renders no output
231
-	 * @return null
232
-	 * @since 6.0.0
233
-	 */
234
-	public function render() {
235
-		return null;
236
-	}
237
-
238
-
239
-	/**
240
-	 * Set response status
241
-	 * @param int $status a HTTP status code, see also the STATUS constants
242
-	 * @return Response Reference to this object
243
-	 * @since 6.0.0 - return value was added in 7.0.0
244
-	 */
245
-	public function setStatus($status) {
246
-		$this->status = $status;
247
-
248
-		return $this;
249
-	}
250
-
251
-	/**
252
-	 * Set a Content-Security-Policy
253
-	 * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
254
-	 * @return $this
255
-	 * @since 8.1.0
256
-	 */
257
-	public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
258
-		$this->contentSecurityPolicy = $csp;
259
-		return $this;
260
-	}
261
-
262
-	/**
263
-	 * Get the currently used Content-Security-Policy
264
-	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
265
-	 *                                    none specified.
266
-	 * @since 8.1.0
267
-	 */
268
-	public function getContentSecurityPolicy() {
269
-		return $this->contentSecurityPolicy;
270
-	}
271
-
272
-
273
-	/**
274
-	 * Get response status
275
-	 * @since 6.0.0
276
-	 */
277
-	public function getStatus() {
278
-		return $this->status;
279
-	}
280
-
281
-
282
-	/**
283
-	 * Get the ETag
284
-	 * @return string the etag
285
-	 * @since 6.0.0
286
-	 */
287
-	public function getETag() {
288
-		return $this->ETag;
289
-	}
290
-
291
-
292
-	/**
293
-	 * Get "last modified" date
294
-	 * @return \DateTime RFC2822 formatted last modified date
295
-	 * @since 6.0.0
296
-	 */
297
-	public function getLastModified() {
298
-		return $this->lastModified;
299
-	}
300
-
301
-
302
-	/**
303
-	 * Set the ETag
304
-	 * @param string $ETag
305
-	 * @return Response Reference to this object
306
-	 * @since 6.0.0 - return value was added in 7.0.0
307
-	 */
308
-	public function setETag($ETag) {
309
-		$this->ETag = $ETag;
310
-
311
-		return $this;
312
-	}
313
-
314
-
315
-	/**
316
-	 * Set "last modified" date
317
-	 * @param \DateTime $lastModified
318
-	 * @return Response Reference to this object
319
-	 * @since 6.0.0 - return value was added in 7.0.0
320
-	 */
321
-	public function setLastModified($lastModified) {
322
-		$this->lastModified = $lastModified;
323
-
324
-		return $this;
325
-	}
326
-
327
-	/**
328
-	 * Marks the response as to throttle. Will be throttled when the
329
-	 * @BruteForceProtection annotation is added.
330
-	 *
331
-	 * @since 12.0.0
332
-	 */
333
-	public function throttle() {
334
-		$this->throttled = true;
335
-	}
336
-
337
-	/**
338
-	 * Whether the current response is throttled.
339
-	 *
340
-	 * @since 12.0.0
341
-	 */
342
-	public function isThrottled() {
343
-		return $this->throttled;
344
-	}
45
+    /**
46
+     * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
47
+     * @var array
48
+     */
49
+    private $headers = array(
50
+        'Cache-Control' => 'no-cache, no-store, must-revalidate'
51
+    );
52
+
53
+
54
+    /**
55
+     * Cookies that will be need to be constructed as header
56
+     * @var array
57
+     */
58
+    private $cookies = array();
59
+
60
+
61
+    /**
62
+     * HTTP status code - defaults to STATUS OK
63
+     * @var int
64
+     */
65
+    private $status = Http::STATUS_OK;
66
+
67
+
68
+    /**
69
+     * Last modified date
70
+     * @var \DateTime
71
+     */
72
+    private $lastModified;
73
+
74
+
75
+    /**
76
+     * ETag
77
+     * @var string
78
+     */
79
+    private $ETag;
80
+
81
+    /** @var ContentSecurityPolicy|null Used Content-Security-Policy */
82
+    private $contentSecurityPolicy = null;
83
+
84
+    /** @var bool */
85
+    private $throttled = false;
86
+
87
+    /**
88
+     * Caches the response
89
+     * @param int $cacheSeconds the amount of seconds that should be cached
90
+     * if 0 then caching will be disabled
91
+     * @return $this
92
+     * @since 6.0.0 - return value was added in 7.0.0
93
+     */
94
+    public function cacheFor($cacheSeconds) {
95
+
96
+        if($cacheSeconds > 0) {
97
+            $this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
98
+        } else {
99
+            $this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
100
+        }
101
+
102
+        return $this;
103
+    }
104
+
105
+    /**
106
+     * Adds a new cookie to the response
107
+     * @param string $name The name of the cookie
108
+     * @param string $value The value of the cookie
109
+     * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
110
+     * 									to null cookie will be considered as session
111
+     * 									cookie.
112
+     * @return $this
113
+     * @since 8.0.0
114
+     */
115
+    public function addCookie($name, $value, \DateTime $expireDate = null) {
116
+        $this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
117
+        return $this;
118
+    }
119
+
120
+
121
+    /**
122
+     * Set the specified cookies
123
+     * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
124
+     * @return $this
125
+     * @since 8.0.0
126
+     */
127
+    public function setCookies(array $cookies) {
128
+        $this->cookies = $cookies;
129
+        return $this;
130
+    }
131
+
132
+
133
+    /**
134
+     * Invalidates the specified cookie
135
+     * @param string $name
136
+     * @return $this
137
+     * @since 8.0.0
138
+     */
139
+    public function invalidateCookie($name) {
140
+        $this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
141
+        return $this;
142
+    }
143
+
144
+    /**
145
+     * Invalidates the specified cookies
146
+     * @param array $cookieNames array('foo', 'bar')
147
+     * @return $this
148
+     * @since 8.0.0
149
+     */
150
+    public function invalidateCookies(array $cookieNames) {
151
+        foreach($cookieNames as $cookieName) {
152
+            $this->invalidateCookie($cookieName);
153
+        }
154
+        return $this;
155
+    }
156
+
157
+    /**
158
+     * Returns the cookies
159
+     * @return array
160
+     * @since 8.0.0
161
+     */
162
+    public function getCookies() {
163
+        return $this->cookies;
164
+    }
165
+
166
+    /**
167
+     * Adds a new header to the response that will be called before the render
168
+     * function
169
+     * @param string $name The name of the HTTP header
170
+     * @param string $value The value, null will delete it
171
+     * @return $this
172
+     * @since 6.0.0 - return value was added in 7.0.0
173
+     */
174
+    public function addHeader($name, $value) {
175
+        $name = trim($name);  // always remove leading and trailing whitespace
176
+                                // to be able to reliably check for security
177
+                                // headers
178
+
179
+        if(is_null($value)) {
180
+            unset($this->headers[$name]);
181
+        } else {
182
+            $this->headers[$name] = $value;
183
+        }
184
+
185
+        return $this;
186
+    }
187
+
188
+
189
+    /**
190
+     * Set the headers
191
+     * @param array $headers value header pairs
192
+     * @return $this
193
+     * @since 8.0.0
194
+     */
195
+    public function setHeaders(array $headers) {
196
+        $this->headers = $headers;
197
+
198
+        return $this;
199
+    }
200
+
201
+
202
+    /**
203
+     * Returns the set headers
204
+     * @return array the headers
205
+     * @since 6.0.0
206
+     */
207
+    public function getHeaders() {
208
+        $mergeWith = [];
209
+
210
+        if($this->lastModified) {
211
+            $mergeWith['Last-Modified'] =
212
+                $this->lastModified->format(\DateTime::RFC2822);
213
+        }
214
+
215
+        // Build Content-Security-Policy and use default if none has been specified
216
+        if(is_null($this->contentSecurityPolicy)) {
217
+            $this->setContentSecurityPolicy(new ContentSecurityPolicy());
218
+        }
219
+        $this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
220
+
221
+        if($this->ETag) {
222
+            $mergeWith['ETag'] = '"' . $this->ETag . '"';
223
+        }
224
+
225
+        return array_merge($mergeWith, $this->headers);
226
+    }
227
+
228
+
229
+    /**
230
+     * By default renders no output
231
+     * @return null
232
+     * @since 6.0.0
233
+     */
234
+    public function render() {
235
+        return null;
236
+    }
237
+
238
+
239
+    /**
240
+     * Set response status
241
+     * @param int $status a HTTP status code, see also the STATUS constants
242
+     * @return Response Reference to this object
243
+     * @since 6.0.0 - return value was added in 7.0.0
244
+     */
245
+    public function setStatus($status) {
246
+        $this->status = $status;
247
+
248
+        return $this;
249
+    }
250
+
251
+    /**
252
+     * Set a Content-Security-Policy
253
+     * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
254
+     * @return $this
255
+     * @since 8.1.0
256
+     */
257
+    public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
258
+        $this->contentSecurityPolicy = $csp;
259
+        return $this;
260
+    }
261
+
262
+    /**
263
+     * Get the currently used Content-Security-Policy
264
+     * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
265
+     *                                    none specified.
266
+     * @since 8.1.0
267
+     */
268
+    public function getContentSecurityPolicy() {
269
+        return $this->contentSecurityPolicy;
270
+    }
271
+
272
+
273
+    /**
274
+     * Get response status
275
+     * @since 6.0.0
276
+     */
277
+    public function getStatus() {
278
+        return $this->status;
279
+    }
280
+
281
+
282
+    /**
283
+     * Get the ETag
284
+     * @return string the etag
285
+     * @since 6.0.0
286
+     */
287
+    public function getETag() {
288
+        return $this->ETag;
289
+    }
290
+
291
+
292
+    /**
293
+     * Get "last modified" date
294
+     * @return \DateTime RFC2822 formatted last modified date
295
+     * @since 6.0.0
296
+     */
297
+    public function getLastModified() {
298
+        return $this->lastModified;
299
+    }
300
+
301
+
302
+    /**
303
+     * Set the ETag
304
+     * @param string $ETag
305
+     * @return Response Reference to this object
306
+     * @since 6.0.0 - return value was added in 7.0.0
307
+     */
308
+    public function setETag($ETag) {
309
+        $this->ETag = $ETag;
310
+
311
+        return $this;
312
+    }
313
+
314
+
315
+    /**
316
+     * Set "last modified" date
317
+     * @param \DateTime $lastModified
318
+     * @return Response Reference to this object
319
+     * @since 6.0.0 - return value was added in 7.0.0
320
+     */
321
+    public function setLastModified($lastModified) {
322
+        $this->lastModified = $lastModified;
323
+
324
+        return $this;
325
+    }
326
+
327
+    /**
328
+     * Marks the response as to throttle. Will be throttled when the
329
+     * @BruteForceProtection annotation is added.
330
+     *
331
+     * @since 12.0.0
332
+     */
333
+    public function throttle() {
334
+        $this->throttled = true;
335
+    }
336
+
337
+    /**
338
+     * Whether the current response is throttled.
339
+     *
340
+     * @since 12.0.0
341
+     */
342
+    public function isThrottled() {
343
+        return $this->throttled;
344
+    }
345 345
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/PublishPlugin.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@
 block discarded – undo
134 134
 	 * @param RequestInterface $request
135 135
 	 * @param ResponseInterface $response
136 136
 	 *
137
-	 * @return void|bool
137
+	 * @return null|false
138 138
 	 */
139 139
 	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140 140
 		$path = $request->getPath();
Please login to merge, or discard this patch.
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -34,194 +34,194 @@
 block discarded – undo
34 34
 use OCP\IConfig;
35 35
 
36 36
 class PublishPlugin extends ServerPlugin {
37
-	const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
-
39
-	/**
40
-	 * Reference to SabreDAV server object.
41
-	 *
42
-	 * @var \Sabre\DAV\Server
43
-	 */
44
-	protected $server;
45
-
46
-	/**
47
-	 * Config instance to get instance secret.
48
-	 *
49
-	 * @var IConfig
50
-	 */
51
-	protected $config;
52
-
53
-	/**
54
-	 * URL Generator for absolute URLs.
55
-	 *
56
-	 * @var IURLGenerator
57
-	 */
58
-	protected $urlGenerator;
59
-
60
-	/**
61
-	 * PublishPlugin constructor.
62
-	 *
63
-	 * @param IConfig $config
64
-	 * @param IURLGenerator $urlGenerator
65
-	 */
66
-	public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
-		$this->config = $config;
68
-		$this->urlGenerator = $urlGenerator;
69
-	}
70
-
71
-	/**
72
-	 * This method should return a list of server-features.
73
-	 *
74
-	 * This is for example 'versioning' and is added to the DAV: header
75
-	 * in an OPTIONS response.
76
-	 *
77
-	 * @return string[]
78
-	 */
79
-	public function getFeatures() {
80
-		// May have to be changed to be detected
81
-		return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
-	}
83
-
84
-	/**
85
-	 * Returns a plugin name.
86
-	 *
87
-	 * Using this name other plugins will be able to access other plugins
88
-	 * using Sabre\DAV\Server::getPlugin
89
-	 *
90
-	 * @return string
91
-	 */
92
-	public function getPluginName()	{
93
-		return 'oc-calendar-publishing';
94
-	}
95
-
96
-	/**
97
-	 * This initializes the plugin.
98
-	 *
99
-	 * This function is called by Sabre\DAV\Server, after
100
-	 * addPlugin is called.
101
-	 *
102
-	 * This method should set up the required event subscriptions.
103
-	 *
104
-	 * @param Server $server
105
-	 */
106
-	public function initialize(Server $server) {
107
-		$this->server = $server;
108
-
109
-		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
111
-	}
112
-
113
-	public function propFind(PropFind $propFind, INode $node) {
114
-		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
-				if ($node->getPublishStatus()) {
117
-					// We return the publish-url only if the calendar is published.
118
-					$token = $node->getPublishStatus();
119
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
-
121
-					return new Publisher($publishUrl, true);
122
-				}
123
-			});
124
-
125
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
-				return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
-			});
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * We intercept this to handle POST requests on calendars.
133
-	 *
134
-	 * @param RequestInterface $request
135
-	 * @param ResponseInterface $response
136
-	 *
137
-	 * @return void|bool
138
-	 */
139
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
-		$path = $request->getPath();
141
-
142
-		// Only handling xml
143
-		$contentType = $request->getHeader('Content-Type');
144
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
-			return;
146
-		}
147
-
148
-		// Making sure the node exists
149
-		try {
150
-			$node = $this->server->tree->getNodeForPath($path);
151
-		} catch (NotFound $e) {
152
-			return;
153
-		}
154
-
155
-		$requestBody = $request->getBodyAsString();
156
-
157
-		// If this request handler could not deal with this POST request, it
158
-		// will return 'null' and other plugins get a chance to handle the
159
-		// request.
160
-		//
161
-		// However, we already requested the full body. This is a problem,
162
-		// because a body can only be read once. This is why we preemptively
163
-		// re-populated the request body with the existing data.
164
-		$request->setBody($requestBody);
165
-
166
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
-
168
-		switch ($documentType) {
169
-
170
-			case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
-
172
-			// We can only deal with IShareableCalendar objects
173
-			if (!$node instanceof Calendar) {
174
-				return;
175
-			}
176
-			$this->server->transactionType = 'post-publish-calendar';
177
-
178
-			// Getting ACL info
179
-			$acl = $this->server->getPlugin('acl');
180
-
181
-			// If there's no ACL support, we allow everything
182
-			if ($acl) {
183
-				$acl->checkPrivileges($path, '{DAV:}write');
184
-			}
185
-
186
-			$node->setPublishStatus(true);
187
-
188
-			// iCloud sends back the 202, so we will too.
189
-			$response->setStatus(202);
190
-
191
-			// Adding this because sending a response body may cause issues,
192
-			// and I wanted some type of indicator the response was handled.
193
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
194
-
195
-			// Breaking the event chain
196
-			return false;
197
-
198
-			case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
-
200
-			// We can only deal with IShareableCalendar objects
201
-			if (!$node instanceof Calendar) {
202
-				return;
203
-			}
204
-			$this->server->transactionType = 'post-unpublish-calendar';
205
-
206
-			// Getting ACL info
207
-			$acl = $this->server->getPlugin('acl');
208
-
209
-			// If there's no ACL support, we allow everything
210
-			if ($acl) {
211
-				$acl->checkPrivileges($path, '{DAV:}write');
212
-			}
213
-
214
-			$node->setPublishStatus(false);
215
-
216
-			$response->setStatus(200);
217
-
218
-			// Adding this because sending a response body may cause issues,
219
-			// and I wanted some type of indicator the response was handled.
220
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
221
-
222
-			// Breaking the event chain
223
-			return false;
37
+    const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
+
39
+    /**
40
+     * Reference to SabreDAV server object.
41
+     *
42
+     * @var \Sabre\DAV\Server
43
+     */
44
+    protected $server;
45
+
46
+    /**
47
+     * Config instance to get instance secret.
48
+     *
49
+     * @var IConfig
50
+     */
51
+    protected $config;
52
+
53
+    /**
54
+     * URL Generator for absolute URLs.
55
+     *
56
+     * @var IURLGenerator
57
+     */
58
+    protected $urlGenerator;
59
+
60
+    /**
61
+     * PublishPlugin constructor.
62
+     *
63
+     * @param IConfig $config
64
+     * @param IURLGenerator $urlGenerator
65
+     */
66
+    public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
+        $this->config = $config;
68
+        $this->urlGenerator = $urlGenerator;
69
+    }
70
+
71
+    /**
72
+     * This method should return a list of server-features.
73
+     *
74
+     * This is for example 'versioning' and is added to the DAV: header
75
+     * in an OPTIONS response.
76
+     *
77
+     * @return string[]
78
+     */
79
+    public function getFeatures() {
80
+        // May have to be changed to be detected
81
+        return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
+    }
83
+
84
+    /**
85
+     * Returns a plugin name.
86
+     *
87
+     * Using this name other plugins will be able to access other plugins
88
+     * using Sabre\DAV\Server::getPlugin
89
+     *
90
+     * @return string
91
+     */
92
+    public function getPluginName()	{
93
+        return 'oc-calendar-publishing';
94
+    }
95
+
96
+    /**
97
+     * This initializes the plugin.
98
+     *
99
+     * This function is called by Sabre\DAV\Server, after
100
+     * addPlugin is called.
101
+     *
102
+     * This method should set up the required event subscriptions.
103
+     *
104
+     * @param Server $server
105
+     */
106
+    public function initialize(Server $server) {
107
+        $this->server = $server;
108
+
109
+        $this->server->on('method:POST', [$this, 'httpPost']);
110
+        $this->server->on('propFind',    [$this, 'propFind']);
111
+    }
112
+
113
+    public function propFind(PropFind $propFind, INode $node) {
114
+        if ($node instanceof Calendar) {
115
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
+                if ($node->getPublishStatus()) {
117
+                    // We return the publish-url only if the calendar is published.
118
+                    $token = $node->getPublishStatus();
119
+                    $publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
+
121
+                    return new Publisher($publishUrl, true);
122
+                }
123
+            });
124
+
125
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
+                return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
+            });
128
+        }
129
+    }
130
+
131
+    /**
132
+     * We intercept this to handle POST requests on calendars.
133
+     *
134
+     * @param RequestInterface $request
135
+     * @param ResponseInterface $response
136
+     *
137
+     * @return void|bool
138
+     */
139
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
+        $path = $request->getPath();
141
+
142
+        // Only handling xml
143
+        $contentType = $request->getHeader('Content-Type');
144
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
+            return;
146
+        }
147
+
148
+        // Making sure the node exists
149
+        try {
150
+            $node = $this->server->tree->getNodeForPath($path);
151
+        } catch (NotFound $e) {
152
+            return;
153
+        }
154
+
155
+        $requestBody = $request->getBodyAsString();
156
+
157
+        // If this request handler could not deal with this POST request, it
158
+        // will return 'null' and other plugins get a chance to handle the
159
+        // request.
160
+        //
161
+        // However, we already requested the full body. This is a problem,
162
+        // because a body can only be read once. This is why we preemptively
163
+        // re-populated the request body with the existing data.
164
+        $request->setBody($requestBody);
165
+
166
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
+
168
+        switch ($documentType) {
169
+
170
+            case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
+
172
+            // We can only deal with IShareableCalendar objects
173
+            if (!$node instanceof Calendar) {
174
+                return;
175
+            }
176
+            $this->server->transactionType = 'post-publish-calendar';
177
+
178
+            // Getting ACL info
179
+            $acl = $this->server->getPlugin('acl');
180
+
181
+            // If there's no ACL support, we allow everything
182
+            if ($acl) {
183
+                $acl->checkPrivileges($path, '{DAV:}write');
184
+            }
185
+
186
+            $node->setPublishStatus(true);
187
+
188
+            // iCloud sends back the 202, so we will too.
189
+            $response->setStatus(202);
190
+
191
+            // Adding this because sending a response body may cause issues,
192
+            // and I wanted some type of indicator the response was handled.
193
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
194
+
195
+            // Breaking the event chain
196
+            return false;
197
+
198
+            case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
+
200
+            // We can only deal with IShareableCalendar objects
201
+            if (!$node instanceof Calendar) {
202
+                return;
203
+            }
204
+            $this->server->transactionType = 'post-unpublish-calendar';
205
+
206
+            // Getting ACL info
207
+            $acl = $this->server->getPlugin('acl');
208
+
209
+            // If there's no ACL support, we allow everything
210
+            if ($acl) {
211
+                $acl->checkPrivileges($path, '{DAV:}write');
212
+            }
213
+
214
+            $node->setPublishStatus(false);
215
+
216
+            $response->setStatus(200);
217
+
218
+            // Adding this because sending a response body may cause issues,
219
+            // and I wanted some type of indicator the response was handled.
220
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
221
+
222
+            // Breaking the event chain
223
+            return false;
224 224
 
225
-		}
226
-	}
225
+        }
226
+    }
227 227
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 *
90 90
 	 * @return string
91 91
 	 */
92
-	public function getPluginName()	{
92
+	public function getPluginName() {
93 93
 		return 'oc-calendar-publishing';
94 94
 	}
95 95
 
@@ -107,12 +107,12 @@  discard block
 block discarded – undo
107 107
 		$this->server = $server;
108 108
 
109 109
 		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
110
+		$this->server->on('propFind', [$this, 'propFind']);
111 111
 	}
112 112
 
113 113
 	public function propFind(PropFind $propFind, INode $node) {
114 114
 		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
115
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function() use ($node) {
116 116
 				if ($node->getPublishStatus()) {
117 117
 					// We return the publish-url only if the calendar is published.
118 118
 					$token = $node->getPublishStatus();
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookRoot.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
 
31 31
 	/**
32 32
 	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
33
+	 * @param CardDavBackend $carddavBackend
34 34
 	 * @param string $principalPrefix
35 35
 	 */
36 36
 	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,46 +25,46 @@
 block discarded – undo
25 25
 
26 26
 class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot {
27 27
 
28
-	/** @var IL10N */
29
-	protected $l10n;
28
+    /** @var IL10N */
29
+    protected $l10n;
30 30
 
31
-	/**
32
-	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
-	 * @param string $principalPrefix
35
-	 */
36
-	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
-		parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
-		$this->l10n = \OC::$server->getL10N('dav');
39
-	}
31
+    /**
32
+     * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
+     * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
+     * @param string $principalPrefix
35
+     */
36
+    public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
+        parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
+        $this->l10n = \OC::$server->getL10N('dav');
39
+    }
40 40
 
41
-	/**
42
-	 * This method returns a node for a principal.
43
-	 *
44
-	 * The passed array contains principal information, and is guaranteed to
45
-	 * at least contain a uri item. Other properties may or may not be
46
-	 * supplied by the authentication backend.
47
-	 *
48
-	 * @param array $principal
49
-	 * @return \Sabre\DAV\INode
50
-	 */
51
-	function getChildForPrincipal(array $principal) {
41
+    /**
42
+     * This method returns a node for a principal.
43
+     *
44
+     * The passed array contains principal information, and is guaranteed to
45
+     * at least contain a uri item. Other properties may or may not be
46
+     * supplied by the authentication backend.
47
+     *
48
+     * @param array $principal
49
+     * @return \Sabre\DAV\INode
50
+     */
51
+    function getChildForPrincipal(array $principal) {
52 52
 
53
-		return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
53
+        return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
54 54
 
55
-	}
55
+    }
56 56
 
57
-	function getName() {
57
+    function getName() {
58 58
 
59
-		if ($this->principalPrefix === 'principals') {
60
-			return parent::getName();
61
-		}
62
-		// Grabbing all the components of the principal path.
63
-		$parts = explode('/', $this->principalPrefix);
59
+        if ($this->principalPrefix === 'principals') {
60
+            return parent::getName();
61
+        }
62
+        // Grabbing all the components of the principal path.
63
+        $parts = explode('/', $this->principalPrefix);
64 64
 
65
-		// We are only interested in the second part.
66
-		return $parts[1];
65
+        // We are only interested in the second part.
66
+        return $parts[1];
67 67
 
68
-	}
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -770,7 +770,7 @@
 block discarded – undo
770 770
 
771 771
 	/**
772 772
 	 * @param Share[] $shares
773
-	 * @param $userId
773
+	 * @param string $userId
774 774
 	 * @return Share[] The updates shares if no update is found for a share return the original
775 775
 	 */
776 776
 	private function resolveGroupShares($shares, $userId) {
Please login to merge, or discard this patch.
Indentation   +1101 added lines, -1101 removed lines patch added patch discarded remove patch
@@ -47,1138 +47,1138 @@
 block discarded – undo
47 47
  */
48 48
 class DefaultShareProvider implements IShareProvider {
49 49
 
50
-	// Special share type for user modified group shares
51
-	const SHARE_TYPE_USERGROUP = 2;
52
-
53
-	/** @var IDBConnection */
54
-	private $dbConn;
55
-
56
-	/** @var IUserManager */
57
-	private $userManager;
58
-
59
-	/** @var IGroupManager */
60
-	private $groupManager;
61
-
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-
65
-	/**
66
-	 * DefaultShareProvider constructor.
67
-	 *
68
-	 * @param IDBConnection $connection
69
-	 * @param IUserManager $userManager
70
-	 * @param IGroupManager $groupManager
71
-	 * @param IRootFolder $rootFolder
72
-	 */
73
-	public function __construct(
74
-			IDBConnection $connection,
75
-			IUserManager $userManager,
76
-			IGroupManager $groupManager,
77
-			IRootFolder $rootFolder) {
78
-		$this->dbConn = $connection;
79
-		$this->userManager = $userManager;
80
-		$this->groupManager = $groupManager;
81
-		$this->rootFolder = $rootFolder;
82
-	}
83
-
84
-	/**
85
-	 * Return the identifier of this provider.
86
-	 *
87
-	 * @return string Containing only [a-zA-Z0-9]
88
-	 */
89
-	public function identifier() {
90
-		return 'ocinternal';
91
-	}
92
-
93
-	/**
94
-	 * Share a path
95
-	 *
96
-	 * @param \OCP\Share\IShare $share
97
-	 * @return \OCP\Share\IShare The share object
98
-	 * @throws ShareNotFound
99
-	 * @throws \Exception
100
-	 */
101
-	public function create(\OCP\Share\IShare $share) {
102
-		$qb = $this->dbConn->getQueryBuilder();
103
-
104
-		$qb->insert('share');
105
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
-
107
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
-			//Set the UID of the user we share with
109
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
-			//Set the GID of the group we share with
112
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-			//Set the token of the share
115
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
-
117
-			//If a password is set store it
118
-			if ($share->getPassword() !== null) {
119
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
-			}
121
-
122
-			//If an expiration date is set store it
123
-			if ($share->getExpirationDate() !== null) {
124
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
-			}
126
-
127
-			if (method_exists($share, 'getParent')) {
128
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
-			}
130
-		} else {
131
-			throw new \Exception('invalid share type!');
132
-		}
133
-
134
-		// Set what is shares
135
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
136
-		if ($share->getNode() instanceof \OCP\Files\File) {
137
-			$qb->setParameter('itemType', 'file');
138
-		} else {
139
-			$qb->setParameter('itemType', 'folder');
140
-		}
141
-
142
-		// Set the file id
143
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
-
146
-		// set the permissions
147
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
-
149
-		// Set who created this share
150
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
-
152
-		// Set who is the owner of this file/folder (and this the owner of the share)
153
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
-
155
-		// Set the file target
156
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
-
158
-		// Set the time this share was created
159
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
160
-
161
-		// insert the data and fetch the id of the share
162
-		$this->dbConn->beginTransaction();
163
-		$qb->execute();
164
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
165
-
166
-		// Now fetch the inserted share and create a complete share object
167
-		$qb = $this->dbConn->getQueryBuilder();
168
-		$qb->select('*')
169
-			->from('share')
170
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
-
172
-		$cursor = $qb->execute();
173
-		$data = $cursor->fetch();
174
-		$this->dbConn->commit();
175
-		$cursor->closeCursor();
176
-
177
-		if ($data === false) {
178
-			throw new ShareNotFound();
179
-		}
180
-
181
-		$share = $this->createShare($data);
182
-		return $share;
183
-	}
184
-
185
-	/**
186
-	 * Update a share
187
-	 *
188
-	 * @param \OCP\Share\IShare $share
189
-	 * @return \OCP\Share\IShare The share object
190
-	 */
191
-	public function update(\OCP\Share\IShare $share) {
192
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
-			/*
50
+    // Special share type for user modified group shares
51
+    const SHARE_TYPE_USERGROUP = 2;
52
+
53
+    /** @var IDBConnection */
54
+    private $dbConn;
55
+
56
+    /** @var IUserManager */
57
+    private $userManager;
58
+
59
+    /** @var IGroupManager */
60
+    private $groupManager;
61
+
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+
65
+    /**
66
+     * DefaultShareProvider constructor.
67
+     *
68
+     * @param IDBConnection $connection
69
+     * @param IUserManager $userManager
70
+     * @param IGroupManager $groupManager
71
+     * @param IRootFolder $rootFolder
72
+     */
73
+    public function __construct(
74
+            IDBConnection $connection,
75
+            IUserManager $userManager,
76
+            IGroupManager $groupManager,
77
+            IRootFolder $rootFolder) {
78
+        $this->dbConn = $connection;
79
+        $this->userManager = $userManager;
80
+        $this->groupManager = $groupManager;
81
+        $this->rootFolder = $rootFolder;
82
+    }
83
+
84
+    /**
85
+     * Return the identifier of this provider.
86
+     *
87
+     * @return string Containing only [a-zA-Z0-9]
88
+     */
89
+    public function identifier() {
90
+        return 'ocinternal';
91
+    }
92
+
93
+    /**
94
+     * Share a path
95
+     *
96
+     * @param \OCP\Share\IShare $share
97
+     * @return \OCP\Share\IShare The share object
98
+     * @throws ShareNotFound
99
+     * @throws \Exception
100
+     */
101
+    public function create(\OCP\Share\IShare $share) {
102
+        $qb = $this->dbConn->getQueryBuilder();
103
+
104
+        $qb->insert('share');
105
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
+
107
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
+            //Set the UID of the user we share with
109
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
+            //Set the GID of the group we share with
112
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+            //Set the token of the share
115
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
+
117
+            //If a password is set store it
118
+            if ($share->getPassword() !== null) {
119
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
+            }
121
+
122
+            //If an expiration date is set store it
123
+            if ($share->getExpirationDate() !== null) {
124
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
+            }
126
+
127
+            if (method_exists($share, 'getParent')) {
128
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
+            }
130
+        } else {
131
+            throw new \Exception('invalid share type!');
132
+        }
133
+
134
+        // Set what is shares
135
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
136
+        if ($share->getNode() instanceof \OCP\Files\File) {
137
+            $qb->setParameter('itemType', 'file');
138
+        } else {
139
+            $qb->setParameter('itemType', 'folder');
140
+        }
141
+
142
+        // Set the file id
143
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
+
146
+        // set the permissions
147
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
+
149
+        // Set who created this share
150
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
+
152
+        // Set who is the owner of this file/folder (and this the owner of the share)
153
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
+
155
+        // Set the file target
156
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
+
158
+        // Set the time this share was created
159
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
160
+
161
+        // insert the data and fetch the id of the share
162
+        $this->dbConn->beginTransaction();
163
+        $qb->execute();
164
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
165
+
166
+        // Now fetch the inserted share and create a complete share object
167
+        $qb = $this->dbConn->getQueryBuilder();
168
+        $qb->select('*')
169
+            ->from('share')
170
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
+
172
+        $cursor = $qb->execute();
173
+        $data = $cursor->fetch();
174
+        $this->dbConn->commit();
175
+        $cursor->closeCursor();
176
+
177
+        if ($data === false) {
178
+            throw new ShareNotFound();
179
+        }
180
+
181
+        $share = $this->createShare($data);
182
+        return $share;
183
+    }
184
+
185
+    /**
186
+     * Update a share
187
+     *
188
+     * @param \OCP\Share\IShare $share
189
+     * @return \OCP\Share\IShare The share object
190
+     */
191
+    public function update(\OCP\Share\IShare $share) {
192
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
+            /*
194 194
 			 * We allow updating the recipient on user shares.
195 195
 			 */
196
-			$qb = $this->dbConn->getQueryBuilder();
197
-			$qb->update('share')
198
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
-				->execute();
207
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
-			$qb = $this->dbConn->getQueryBuilder();
209
-			$qb->update('share')
210
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
-				->execute();
218
-
219
-			/*
196
+            $qb = $this->dbConn->getQueryBuilder();
197
+            $qb->update('share')
198
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
+                ->execute();
207
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
+            $qb = $this->dbConn->getQueryBuilder();
209
+            $qb->update('share')
210
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
+                ->execute();
218
+
219
+            /*
220 220
 			 * Update all user defined group shares
221 221
 			 */
222
-			$qb = $this->dbConn->getQueryBuilder();
223
-			$qb->update('share')
224
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
-				->execute();
231
-
232
-			/*
222
+            $qb = $this->dbConn->getQueryBuilder();
223
+            $qb->update('share')
224
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
+                ->execute();
231
+
232
+            /*
233 233
 			 * Now update the permissions for all children that have not set it to 0
234 234
 			 */
235
-			$qb = $this->dbConn->getQueryBuilder();
236
-			$qb->update('share')
237
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
-				->execute();
241
-
242
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
-			$qb = $this->dbConn->getQueryBuilder();
244
-			$qb->update('share')
245
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
-				->set('password', $qb->createNamedParameter($share->getPassword()))
247
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
-				->set('token', $qb->createNamedParameter($share->getToken()))
253
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
-				->execute();
255
-		}
256
-
257
-		return $share;
258
-	}
259
-
260
-	/**
261
-	 * Get all children of this share
262
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
-	 *
264
-	 * @param \OCP\Share\IShare $parent
265
-	 * @return \OCP\Share\IShare[]
266
-	 */
267
-	public function getChildren(\OCP\Share\IShare $parent) {
268
-		$children = [];
269
-
270
-		$qb = $this->dbConn->getQueryBuilder();
271
-		$qb->select('*')
272
-			->from('share')
273
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
-			->andWhere(
275
-				$qb->expr()->in(
276
-					'share_type',
277
-					$qb->createNamedParameter([
278
-						\OCP\Share::SHARE_TYPE_USER,
279
-						\OCP\Share::SHARE_TYPE_GROUP,
280
-						\OCP\Share::SHARE_TYPE_LINK,
281
-					], IQueryBuilder::PARAM_INT_ARRAY)
282
-				)
283
-			)
284
-			->andWhere($qb->expr()->orX(
285
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
-			))
288
-			->orderBy('id');
289
-
290
-		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
292
-			$children[] = $this->createShare($data);
293
-		}
294
-		$cursor->closeCursor();
295
-
296
-		return $children;
297
-	}
298
-
299
-	/**
300
-	 * Delete a share
301
-	 *
302
-	 * @param \OCP\Share\IShare $share
303
-	 */
304
-	public function delete(\OCP\Share\IShare $share) {
305
-		$qb = $this->dbConn->getQueryBuilder();
306
-		$qb->delete('share')
307
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
-
309
-		/*
235
+            $qb = $this->dbConn->getQueryBuilder();
236
+            $qb->update('share')
237
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
+                ->execute();
241
+
242
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
+            $qb = $this->dbConn->getQueryBuilder();
244
+            $qb->update('share')
245
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
247
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
+                ->set('token', $qb->createNamedParameter($share->getToken()))
253
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
+                ->execute();
255
+        }
256
+
257
+        return $share;
258
+    }
259
+
260
+    /**
261
+     * Get all children of this share
262
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
+     *
264
+     * @param \OCP\Share\IShare $parent
265
+     * @return \OCP\Share\IShare[]
266
+     */
267
+    public function getChildren(\OCP\Share\IShare $parent) {
268
+        $children = [];
269
+
270
+        $qb = $this->dbConn->getQueryBuilder();
271
+        $qb->select('*')
272
+            ->from('share')
273
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
+            ->andWhere(
275
+                $qb->expr()->in(
276
+                    'share_type',
277
+                    $qb->createNamedParameter([
278
+                        \OCP\Share::SHARE_TYPE_USER,
279
+                        \OCP\Share::SHARE_TYPE_GROUP,
280
+                        \OCP\Share::SHARE_TYPE_LINK,
281
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
282
+                )
283
+            )
284
+            ->andWhere($qb->expr()->orX(
285
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
+            ))
288
+            ->orderBy('id');
289
+
290
+        $cursor = $qb->execute();
291
+        while($data = $cursor->fetch()) {
292
+            $children[] = $this->createShare($data);
293
+        }
294
+        $cursor->closeCursor();
295
+
296
+        return $children;
297
+    }
298
+
299
+    /**
300
+     * Delete a share
301
+     *
302
+     * @param \OCP\Share\IShare $share
303
+     */
304
+    public function delete(\OCP\Share\IShare $share) {
305
+        $qb = $this->dbConn->getQueryBuilder();
306
+        $qb->delete('share')
307
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
+
309
+        /*
310 310
 		 * If the share is a group share delete all possible
311 311
 		 * user defined groups shares.
312 312
 		 */
313
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
-		}
316
-
317
-		$qb->execute();
318
-	}
319
-
320
-	/**
321
-	 * Unshare a share from the recipient. If this is a group share
322
-	 * this means we need a special entry in the share db.
323
-	 *
324
-	 * @param \OCP\Share\IShare $share
325
-	 * @param string $recipient UserId of recipient
326
-	 * @throws BackendError
327
-	 * @throws ProviderException
328
-	 */
329
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
-
332
-			$group = $this->groupManager->get($share->getSharedWith());
333
-			$user = $this->userManager->get($recipient);
334
-
335
-			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
-			}
338
-
339
-			if (!$group->inGroup($user)) {
340
-				throw new ProviderException('Recipient not in receiving group');
341
-			}
342
-
343
-			// Try to fetch user specific share
344
-			$qb = $this->dbConn->getQueryBuilder();
345
-			$stmt = $qb->select('*')
346
-				->from('share')
347
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
-				->andWhere($qb->expr()->orX(
351
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
-				))
354
-				->execute();
355
-
356
-			$data = $stmt->fetch();
357
-
358
-			/*
313
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
+        }
316
+
317
+        $qb->execute();
318
+    }
319
+
320
+    /**
321
+     * Unshare a share from the recipient. If this is a group share
322
+     * this means we need a special entry in the share db.
323
+     *
324
+     * @param \OCP\Share\IShare $share
325
+     * @param string $recipient UserId of recipient
326
+     * @throws BackendError
327
+     * @throws ProviderException
328
+     */
329
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
+
332
+            $group = $this->groupManager->get($share->getSharedWith());
333
+            $user = $this->userManager->get($recipient);
334
+
335
+            if (is_null($group)) {
336
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
+            }
338
+
339
+            if (!$group->inGroup($user)) {
340
+                throw new ProviderException('Recipient not in receiving group');
341
+            }
342
+
343
+            // Try to fetch user specific share
344
+            $qb = $this->dbConn->getQueryBuilder();
345
+            $stmt = $qb->select('*')
346
+                ->from('share')
347
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
+                ->andWhere($qb->expr()->orX(
351
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
+                ))
354
+                ->execute();
355
+
356
+            $data = $stmt->fetch();
357
+
358
+            /*
359 359
 			 * Check if there already is a user specific group share.
360 360
 			 * If there is update it (if required).
361 361
 			 */
362
-			if ($data === false) {
363
-				$qb = $this->dbConn->getQueryBuilder();
364
-
365
-				$type = $share->getNodeType();
366
-
367
-				//Insert new share
368
-				$qb->insert('share')
369
-					->values([
370
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
-						'share_with' => $qb->createNamedParameter($recipient),
372
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
-						'parent' => $qb->createNamedParameter($share->getId()),
375
-						'item_type' => $qb->createNamedParameter($type),
376
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
377
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
378
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
379
-						'permissions' => $qb->createNamedParameter(0),
380
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
-					])->execute();
382
-
383
-			} else if ($data['permissions'] !== 0) {
384
-
385
-				// Update existing usergroup share
386
-				$qb = $this->dbConn->getQueryBuilder();
387
-				$qb->update('share')
388
-					->set('permissions', $qb->createNamedParameter(0))
389
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
-					->execute();
391
-			}
392
-
393
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
-
395
-			if ($share->getSharedWith() !== $recipient) {
396
-				throw new ProviderException('Recipient does not match');
397
-			}
398
-
399
-			// We can just delete user and link shares
400
-			$this->delete($share);
401
-		} else {
402
-			throw new ProviderException('Invalid shareType');
403
-		}
404
-	}
405
-
406
-	/**
407
-	 * @inheritdoc
408
-	 */
409
-	public function move(\OCP\Share\IShare $share, $recipient) {
410
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
-			// Just update the target
412
-			$qb = $this->dbConn->getQueryBuilder();
413
-			$qb->update('share')
414
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
-				->execute();
417
-
418
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
-
420
-			// Check if there is a usergroup share
421
-			$qb = $this->dbConn->getQueryBuilder();
422
-			$stmt = $qb->select('id')
423
-				->from('share')
424
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
-				->andWhere($qb->expr()->orX(
428
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
-				))
431
-				->setMaxResults(1)
432
-				->execute();
433
-
434
-			$data = $stmt->fetch();
435
-			$stmt->closeCursor();
436
-
437
-			if ($data === false) {
438
-				// No usergroup share yet. Create one.
439
-				$qb = $this->dbConn->getQueryBuilder();
440
-				$qb->insert('share')
441
-					->values([
442
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
-						'share_with' => $qb->createNamedParameter($recipient),
444
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
-						'parent' => $qb->createNamedParameter($share->getId()),
447
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
451
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
-					])->execute();
454
-			} else {
455
-				// Already a usergroup share. Update it.
456
-				$qb = $this->dbConn->getQueryBuilder();
457
-				$qb->update('share')
458
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
-					->execute();
461
-			}
462
-		}
463
-
464
-		return $share;
465
-	}
466
-
467
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
468
-		$qb = $this->dbConn->getQueryBuilder();
469
-		$qb->select('*')
470
-			->from('share', 's')
471
-			->andWhere($qb->expr()->orX(
472
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
-			));
475
-
476
-		$qb->andWhere($qb->expr()->orX(
477
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
-		));
481
-
482
-		/**
483
-		 * Reshares for this user are shares where they are the owner.
484
-		 */
485
-		if ($reshares === false) {
486
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
-		} else {
488
-			$qb->andWhere(
489
-				$qb->expr()->orX(
490
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
-				)
493
-			);
494
-		}
495
-
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
-
499
-		$qb->orderBy('id');
500
-
501
-		$cursor = $qb->execute();
502
-		$shares = [];
503
-		while ($data = $cursor->fetch()) {
504
-			$shares[$data['fileid']][] = $this->createShare($data);
505
-		}
506
-		$cursor->closeCursor();
507
-
508
-		return $shares;
509
-	}
510
-
511
-	/**
512
-	 * @inheritdoc
513
-	 */
514
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
-		$qb = $this->dbConn->getQueryBuilder();
516
-		$qb->select('*')
517
-			->from('share')
518
-			->andWhere($qb->expr()->orX(
519
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
-			));
522
-
523
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
-
525
-		/**
526
-		 * Reshares for this user are shares where they are the owner.
527
-		 */
528
-		if ($reshares === false) {
529
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
-		} else {
531
-			$qb->andWhere(
532
-				$qb->expr()->orX(
533
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
-				)
536
-			);
537
-		}
538
-
539
-		if ($node !== null) {
540
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
-		}
542
-
543
-		if ($limit !== -1) {
544
-			$qb->setMaxResults($limit);
545
-		}
546
-
547
-		$qb->setFirstResult($offset);
548
-		$qb->orderBy('id');
549
-
550
-		$cursor = $qb->execute();
551
-		$shares = [];
552
-		while($data = $cursor->fetch()) {
553
-			$shares[] = $this->createShare($data);
554
-		}
555
-		$cursor->closeCursor();
556
-
557
-		return $shares;
558
-	}
559
-
560
-	/**
561
-	 * @inheritdoc
562
-	 */
563
-	public function getShareById($id, $recipientId = null) {
564
-		$qb = $this->dbConn->getQueryBuilder();
565
-
566
-		$qb->select('*')
567
-			->from('share')
568
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
-			->andWhere(
570
-				$qb->expr()->in(
571
-					'share_type',
572
-					$qb->createNamedParameter([
573
-						\OCP\Share::SHARE_TYPE_USER,
574
-						\OCP\Share::SHARE_TYPE_GROUP,
575
-						\OCP\Share::SHARE_TYPE_LINK,
576
-					], IQueryBuilder::PARAM_INT_ARRAY)
577
-				)
578
-			)
579
-			->andWhere($qb->expr()->orX(
580
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
-			));
583
-
584
-		$cursor = $qb->execute();
585
-		$data = $cursor->fetch();
586
-		$cursor->closeCursor();
587
-
588
-		if ($data === false) {
589
-			throw new ShareNotFound();
590
-		}
591
-
592
-		try {
593
-			$share = $this->createShare($data);
594
-		} catch (InvalidShare $e) {
595
-			throw new ShareNotFound();
596
-		}
597
-
598
-		// If the recipient is set for a group share resolve to that user
599
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
601
-		}
602
-
603
-		return $share;
604
-	}
605
-
606
-	/**
607
-	 * Get shares for a given path
608
-	 *
609
-	 * @param \OCP\Files\Node $path
610
-	 * @return \OCP\Share\IShare[]
611
-	 */
612
-	public function getSharesByPath(Node $path) {
613
-		$qb = $this->dbConn->getQueryBuilder();
614
-
615
-		$cursor = $qb->select('*')
616
-			->from('share')
617
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
-			->andWhere(
619
-				$qb->expr()->orX(
620
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
-				)
623
-			)
624
-			->andWhere($qb->expr()->orX(
625
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
-			))
628
-			->execute();
629
-
630
-		$shares = [];
631
-		while($data = $cursor->fetch()) {
632
-			$shares[] = $this->createShare($data);
633
-		}
634
-		$cursor->closeCursor();
635
-
636
-		return $shares;
637
-	}
638
-
639
-	/**
640
-	 * Returns whether the given database result can be interpreted as
641
-	 * a share with accessible file (not trashed, not deleted)
642
-	 */
643
-	private function isAccessibleResult($data) {
644
-		// exclude shares leading to deleted file entries
645
-		if ($data['fileid'] === null) {
646
-			return false;
647
-		}
648
-
649
-		// exclude shares leading to trashbin on home storages
650
-		$pathSections = explode('/', $data['path'], 2);
651
-		// FIXME: would not detect rare md5'd home storage case properly
652
-		if ($pathSections[0] !== 'files'
653
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
-			return false;
655
-		}
656
-		return true;
657
-	}
658
-
659
-	/**
660
-	 * @inheritdoc
661
-	 */
662
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
-		/** @var Share[] $shares */
664
-		$shares = [];
665
-
666
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
-			//Get shares directly with this user
668
-			$qb = $this->dbConn->getQueryBuilder();
669
-			$qb->select('s.*',
670
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
-			)
674
-				->selectAlias('st.id', 'storage_string_id')
675
-				->from('share', 's')
676
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
-
679
-			// Order by id
680
-			$qb->orderBy('s.id');
681
-
682
-			// Set limit and offset
683
-			if ($limit !== -1) {
684
-				$qb->setMaxResults($limit);
685
-			}
686
-			$qb->setFirstResult($offset);
687
-
688
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
-				->andWhere($qb->expr()->orX(
691
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
-				));
694
-
695
-			// Filter by node if provided
696
-			if ($node !== null) {
697
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
-			}
699
-
700
-			$cursor = $qb->execute();
701
-
702
-			while($data = $cursor->fetch()) {
703
-				if ($this->isAccessibleResult($data)) {
704
-					$shares[] = $this->createShare($data);
705
-				}
706
-			}
707
-			$cursor->closeCursor();
708
-
709
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
-			$user = $this->userManager->get($userId);
711
-			$allGroups = $this->groupManager->getUserGroups($user);
712
-
713
-			/** @var Share[] $shares2 */
714
-			$shares2 = [];
715
-
716
-			$start = 0;
717
-			while(true) {
718
-				$groups = array_slice($allGroups, $start, 100);
719
-				$start += 100;
720
-
721
-				if ($groups === []) {
722
-					break;
723
-				}
724
-
725
-				$qb = $this->dbConn->getQueryBuilder();
726
-				$qb->select('s.*',
727
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
-				)
731
-					->selectAlias('st.id', 'storage_string_id')
732
-					->from('share', 's')
733
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
-					->orderBy('s.id')
736
-					->setFirstResult(0);
737
-
738
-				if ($limit !== -1) {
739
-					$qb->setMaxResults($limit - count($shares));
740
-				}
741
-
742
-				// Filter by node if provided
743
-				if ($node !== null) {
744
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
-				}
746
-
747
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
-
749
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
-						$groups,
752
-						IQueryBuilder::PARAM_STR_ARRAY
753
-					)))
754
-					->andWhere($qb->expr()->orX(
755
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
-					));
758
-
759
-				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
761
-					if ($offset > 0) {
762
-						$offset--;
763
-						continue;
764
-					}
765
-
766
-					if ($this->isAccessibleResult($data)) {
767
-						$shares2[] = $this->createShare($data);
768
-					}
769
-				}
770
-				$cursor->closeCursor();
771
-			}
772
-
773
-			/*
362
+            if ($data === false) {
363
+                $qb = $this->dbConn->getQueryBuilder();
364
+
365
+                $type = $share->getNodeType();
366
+
367
+                //Insert new share
368
+                $qb->insert('share')
369
+                    ->values([
370
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
+                        'share_with' => $qb->createNamedParameter($recipient),
372
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
+                        'parent' => $qb->createNamedParameter($share->getId()),
375
+                        'item_type' => $qb->createNamedParameter($type),
376
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
377
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
378
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
379
+                        'permissions' => $qb->createNamedParameter(0),
380
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
+                    ])->execute();
382
+
383
+            } else if ($data['permissions'] !== 0) {
384
+
385
+                // Update existing usergroup share
386
+                $qb = $this->dbConn->getQueryBuilder();
387
+                $qb->update('share')
388
+                    ->set('permissions', $qb->createNamedParameter(0))
389
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
+                    ->execute();
391
+            }
392
+
393
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
+
395
+            if ($share->getSharedWith() !== $recipient) {
396
+                throw new ProviderException('Recipient does not match');
397
+            }
398
+
399
+            // We can just delete user and link shares
400
+            $this->delete($share);
401
+        } else {
402
+            throw new ProviderException('Invalid shareType');
403
+        }
404
+    }
405
+
406
+    /**
407
+     * @inheritdoc
408
+     */
409
+    public function move(\OCP\Share\IShare $share, $recipient) {
410
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
+            // Just update the target
412
+            $qb = $this->dbConn->getQueryBuilder();
413
+            $qb->update('share')
414
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
+                ->execute();
417
+
418
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
+
420
+            // Check if there is a usergroup share
421
+            $qb = $this->dbConn->getQueryBuilder();
422
+            $stmt = $qb->select('id')
423
+                ->from('share')
424
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
+                ->andWhere($qb->expr()->orX(
428
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
+                ))
431
+                ->setMaxResults(1)
432
+                ->execute();
433
+
434
+            $data = $stmt->fetch();
435
+            $stmt->closeCursor();
436
+
437
+            if ($data === false) {
438
+                // No usergroup share yet. Create one.
439
+                $qb = $this->dbConn->getQueryBuilder();
440
+                $qb->insert('share')
441
+                    ->values([
442
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
+                        'share_with' => $qb->createNamedParameter($recipient),
444
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
+                        'parent' => $qb->createNamedParameter($share->getId()),
447
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
451
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
+                    ])->execute();
454
+            } else {
455
+                // Already a usergroup share. Update it.
456
+                $qb = $this->dbConn->getQueryBuilder();
457
+                $qb->update('share')
458
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
+                    ->execute();
461
+            }
462
+        }
463
+
464
+        return $share;
465
+    }
466
+
467
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
468
+        $qb = $this->dbConn->getQueryBuilder();
469
+        $qb->select('*')
470
+            ->from('share', 's')
471
+            ->andWhere($qb->expr()->orX(
472
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
+            ));
475
+
476
+        $qb->andWhere($qb->expr()->orX(
477
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
+        ));
481
+
482
+        /**
483
+         * Reshares for this user are shares where they are the owner.
484
+         */
485
+        if ($reshares === false) {
486
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
+        } else {
488
+            $qb->andWhere(
489
+                $qb->expr()->orX(
490
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
+                )
493
+            );
494
+        }
495
+
496
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
+
499
+        $qb->orderBy('id');
500
+
501
+        $cursor = $qb->execute();
502
+        $shares = [];
503
+        while ($data = $cursor->fetch()) {
504
+            $shares[$data['fileid']][] = $this->createShare($data);
505
+        }
506
+        $cursor->closeCursor();
507
+
508
+        return $shares;
509
+    }
510
+
511
+    /**
512
+     * @inheritdoc
513
+     */
514
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
+        $qb = $this->dbConn->getQueryBuilder();
516
+        $qb->select('*')
517
+            ->from('share')
518
+            ->andWhere($qb->expr()->orX(
519
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
+            ));
522
+
523
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
+
525
+        /**
526
+         * Reshares for this user are shares where they are the owner.
527
+         */
528
+        if ($reshares === false) {
529
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
+        } else {
531
+            $qb->andWhere(
532
+                $qb->expr()->orX(
533
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
+                )
536
+            );
537
+        }
538
+
539
+        if ($node !== null) {
540
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
+        }
542
+
543
+        if ($limit !== -1) {
544
+            $qb->setMaxResults($limit);
545
+        }
546
+
547
+        $qb->setFirstResult($offset);
548
+        $qb->orderBy('id');
549
+
550
+        $cursor = $qb->execute();
551
+        $shares = [];
552
+        while($data = $cursor->fetch()) {
553
+            $shares[] = $this->createShare($data);
554
+        }
555
+        $cursor->closeCursor();
556
+
557
+        return $shares;
558
+    }
559
+
560
+    /**
561
+     * @inheritdoc
562
+     */
563
+    public function getShareById($id, $recipientId = null) {
564
+        $qb = $this->dbConn->getQueryBuilder();
565
+
566
+        $qb->select('*')
567
+            ->from('share')
568
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
+            ->andWhere(
570
+                $qb->expr()->in(
571
+                    'share_type',
572
+                    $qb->createNamedParameter([
573
+                        \OCP\Share::SHARE_TYPE_USER,
574
+                        \OCP\Share::SHARE_TYPE_GROUP,
575
+                        \OCP\Share::SHARE_TYPE_LINK,
576
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
577
+                )
578
+            )
579
+            ->andWhere($qb->expr()->orX(
580
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
+            ));
583
+
584
+        $cursor = $qb->execute();
585
+        $data = $cursor->fetch();
586
+        $cursor->closeCursor();
587
+
588
+        if ($data === false) {
589
+            throw new ShareNotFound();
590
+        }
591
+
592
+        try {
593
+            $share = $this->createShare($data);
594
+        } catch (InvalidShare $e) {
595
+            throw new ShareNotFound();
596
+        }
597
+
598
+        // If the recipient is set for a group share resolve to that user
599
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
601
+        }
602
+
603
+        return $share;
604
+    }
605
+
606
+    /**
607
+     * Get shares for a given path
608
+     *
609
+     * @param \OCP\Files\Node $path
610
+     * @return \OCP\Share\IShare[]
611
+     */
612
+    public function getSharesByPath(Node $path) {
613
+        $qb = $this->dbConn->getQueryBuilder();
614
+
615
+        $cursor = $qb->select('*')
616
+            ->from('share')
617
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
+            ->andWhere(
619
+                $qb->expr()->orX(
620
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
+                )
623
+            )
624
+            ->andWhere($qb->expr()->orX(
625
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
+            ))
628
+            ->execute();
629
+
630
+        $shares = [];
631
+        while($data = $cursor->fetch()) {
632
+            $shares[] = $this->createShare($data);
633
+        }
634
+        $cursor->closeCursor();
635
+
636
+        return $shares;
637
+    }
638
+
639
+    /**
640
+     * Returns whether the given database result can be interpreted as
641
+     * a share with accessible file (not trashed, not deleted)
642
+     */
643
+    private function isAccessibleResult($data) {
644
+        // exclude shares leading to deleted file entries
645
+        if ($data['fileid'] === null) {
646
+            return false;
647
+        }
648
+
649
+        // exclude shares leading to trashbin on home storages
650
+        $pathSections = explode('/', $data['path'], 2);
651
+        // FIXME: would not detect rare md5'd home storage case properly
652
+        if ($pathSections[0] !== 'files'
653
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
+            return false;
655
+        }
656
+        return true;
657
+    }
658
+
659
+    /**
660
+     * @inheritdoc
661
+     */
662
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
+        /** @var Share[] $shares */
664
+        $shares = [];
665
+
666
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
+            //Get shares directly with this user
668
+            $qb = $this->dbConn->getQueryBuilder();
669
+            $qb->select('s.*',
670
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
+            )
674
+                ->selectAlias('st.id', 'storage_string_id')
675
+                ->from('share', 's')
676
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
+
679
+            // Order by id
680
+            $qb->orderBy('s.id');
681
+
682
+            // Set limit and offset
683
+            if ($limit !== -1) {
684
+                $qb->setMaxResults($limit);
685
+            }
686
+            $qb->setFirstResult($offset);
687
+
688
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
+                ->andWhere($qb->expr()->orX(
691
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
+                ));
694
+
695
+            // Filter by node if provided
696
+            if ($node !== null) {
697
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
+            }
699
+
700
+            $cursor = $qb->execute();
701
+
702
+            while($data = $cursor->fetch()) {
703
+                if ($this->isAccessibleResult($data)) {
704
+                    $shares[] = $this->createShare($data);
705
+                }
706
+            }
707
+            $cursor->closeCursor();
708
+
709
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
+            $user = $this->userManager->get($userId);
711
+            $allGroups = $this->groupManager->getUserGroups($user);
712
+
713
+            /** @var Share[] $shares2 */
714
+            $shares2 = [];
715
+
716
+            $start = 0;
717
+            while(true) {
718
+                $groups = array_slice($allGroups, $start, 100);
719
+                $start += 100;
720
+
721
+                if ($groups === []) {
722
+                    break;
723
+                }
724
+
725
+                $qb = $this->dbConn->getQueryBuilder();
726
+                $qb->select('s.*',
727
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
+                )
731
+                    ->selectAlias('st.id', 'storage_string_id')
732
+                    ->from('share', 's')
733
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
+                    ->orderBy('s.id')
736
+                    ->setFirstResult(0);
737
+
738
+                if ($limit !== -1) {
739
+                    $qb->setMaxResults($limit - count($shares));
740
+                }
741
+
742
+                // Filter by node if provided
743
+                if ($node !== null) {
744
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
+                }
746
+
747
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
+
749
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
+                        $groups,
752
+                        IQueryBuilder::PARAM_STR_ARRAY
753
+                    )))
754
+                    ->andWhere($qb->expr()->orX(
755
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
+                    ));
758
+
759
+                $cursor = $qb->execute();
760
+                while($data = $cursor->fetch()) {
761
+                    if ($offset > 0) {
762
+                        $offset--;
763
+                        continue;
764
+                    }
765
+
766
+                    if ($this->isAccessibleResult($data)) {
767
+                        $shares2[] = $this->createShare($data);
768
+                    }
769
+                }
770
+                $cursor->closeCursor();
771
+            }
772
+
773
+            /*
774 774
  			 * Resolve all group shares to user specific shares
775 775
  			 */
776
-			$shares = $this->resolveGroupShares($shares2, $userId);
777
-		} else {
778
-			throw new BackendError('Invalid backend');
779
-		}
780
-
781
-
782
-		return $shares;
783
-	}
784
-
785
-	/**
786
-	 * Get a share by token
787
-	 *
788
-	 * @param string $token
789
-	 * @return \OCP\Share\IShare
790
-	 * @throws ShareNotFound
791
-	 */
792
-	public function getShareByToken($token) {
793
-		$qb = $this->dbConn->getQueryBuilder();
794
-
795
-		$cursor = $qb->select('*')
796
-			->from('share')
797
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
-			->andWhere($qb->expr()->orX(
800
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
-			))
803
-			->execute();
804
-
805
-		$data = $cursor->fetch();
806
-
807
-		if ($data === false) {
808
-			throw new ShareNotFound();
809
-		}
810
-
811
-		try {
812
-			$share = $this->createShare($data);
813
-		} catch (InvalidShare $e) {
814
-			throw new ShareNotFound();
815
-		}
816
-
817
-		return $share;
818
-	}
819
-
820
-	/**
821
-	 * Create a share object from an database row
822
-	 *
823
-	 * @param mixed[] $data
824
-	 * @return \OCP\Share\IShare
825
-	 * @throws InvalidShare
826
-	 */
827
-	private function createShare($data) {
828
-		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
832
-			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
834
-
835
-		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
837
-		$share->setShareTime($shareTime);
838
-
839
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
-			$share->setSharedWith($data['share_with']);
841
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
-			$share->setSharedWith($data['share_with']);
843
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
-			$share->setPassword($data['password']);
845
-			$share->setToken($data['token']);
846
-		}
847
-
848
-		$share->setSharedBy($data['uid_initiator']);
849
-		$share->setShareOwner($data['uid_owner']);
850
-
851
-		$share->setNodeId((int)$data['file_source']);
852
-		$share->setNodeType($data['item_type']);
853
-
854
-		if ($data['expiration'] !== null) {
855
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
-			$share->setExpirationDate($expiration);
857
-		}
858
-
859
-		if (isset($data['f_permissions'])) {
860
-			$entryData = $data;
861
-			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
863
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
-				\OC::$server->getMimeTypeLoader()));
865
-		}
866
-
867
-		$share->setProviderId($this->identifier());
868
-
869
-		return $share;
870
-	}
871
-
872
-	/**
873
-	 * @param Share[] $shares
874
-	 * @param $userId
875
-	 * @return Share[] The updates shares if no update is found for a share return the original
876
-	 */
877
-	private function resolveGroupShares($shares, $userId) {
878
-		$result = [];
879
-
880
-		$start = 0;
881
-		while(true) {
882
-			/** @var Share[] $shareSlice */
883
-			$shareSlice = array_slice($shares, $start, 100);
884
-			$start += 100;
885
-
886
-			if ($shareSlice === []) {
887
-				break;
888
-			}
889
-
890
-			/** @var int[] $ids */
891
-			$ids = [];
892
-			/** @var Share[] $shareMap */
893
-			$shareMap = [];
894
-
895
-			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
897
-				$shareMap[$share->getId()] = $share;
898
-			}
899
-
900
-			$qb = $this->dbConn->getQueryBuilder();
901
-
902
-			$query = $qb->select('*')
903
-				->from('share')
904
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
-				->andWhere($qb->expr()->orX(
907
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
-				));
910
-
911
-			$stmt = $query->execute();
912
-
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
916
-			}
917
-
918
-			$stmt->closeCursor();
919
-
920
-			foreach ($shareMap as $share) {
921
-				$result[] = $share;
922
-			}
923
-		}
924
-
925
-		return $result;
926
-	}
927
-
928
-	/**
929
-	 * A user is deleted from the system
930
-	 * So clean up the relevant shares.
931
-	 *
932
-	 * @param string $uid
933
-	 * @param int $shareType
934
-	 */
935
-	public function userDeleted($uid, $shareType) {
936
-		$qb = $this->dbConn->getQueryBuilder();
937
-
938
-		$qb->delete('share');
939
-
940
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
-			/*
776
+            $shares = $this->resolveGroupShares($shares2, $userId);
777
+        } else {
778
+            throw new BackendError('Invalid backend');
779
+        }
780
+
781
+
782
+        return $shares;
783
+    }
784
+
785
+    /**
786
+     * Get a share by token
787
+     *
788
+     * @param string $token
789
+     * @return \OCP\Share\IShare
790
+     * @throws ShareNotFound
791
+     */
792
+    public function getShareByToken($token) {
793
+        $qb = $this->dbConn->getQueryBuilder();
794
+
795
+        $cursor = $qb->select('*')
796
+            ->from('share')
797
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
+            ->andWhere($qb->expr()->orX(
800
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
+            ))
803
+            ->execute();
804
+
805
+        $data = $cursor->fetch();
806
+
807
+        if ($data === false) {
808
+            throw new ShareNotFound();
809
+        }
810
+
811
+        try {
812
+            $share = $this->createShare($data);
813
+        } catch (InvalidShare $e) {
814
+            throw new ShareNotFound();
815
+        }
816
+
817
+        return $share;
818
+    }
819
+
820
+    /**
821
+     * Create a share object from an database row
822
+     *
823
+     * @param mixed[] $data
824
+     * @return \OCP\Share\IShare
825
+     * @throws InvalidShare
826
+     */
827
+    private function createShare($data) {
828
+        $share = new Share($this->rootFolder, $this->userManager);
829
+        $share->setId((int)$data['id'])
830
+            ->setShareType((int)$data['share_type'])
831
+            ->setPermissions((int)$data['permissions'])
832
+            ->setTarget($data['file_target'])
833
+            ->setMailSend((bool)$data['mail_send']);
834
+
835
+        $shareTime = new \DateTime();
836
+        $shareTime->setTimestamp((int)$data['stime']);
837
+        $share->setShareTime($shareTime);
838
+
839
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
+            $share->setSharedWith($data['share_with']);
841
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
+            $share->setSharedWith($data['share_with']);
843
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
+            $share->setPassword($data['password']);
845
+            $share->setToken($data['token']);
846
+        }
847
+
848
+        $share->setSharedBy($data['uid_initiator']);
849
+        $share->setShareOwner($data['uid_owner']);
850
+
851
+        $share->setNodeId((int)$data['file_source']);
852
+        $share->setNodeType($data['item_type']);
853
+
854
+        if ($data['expiration'] !== null) {
855
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
+            $share->setExpirationDate($expiration);
857
+        }
858
+
859
+        if (isset($data['f_permissions'])) {
860
+            $entryData = $data;
861
+            $entryData['permissions'] = $entryData['f_permissions'];
862
+            $entryData['parent'] = $entryData['f_parent'];;
863
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
+                \OC::$server->getMimeTypeLoader()));
865
+        }
866
+
867
+        $share->setProviderId($this->identifier());
868
+
869
+        return $share;
870
+    }
871
+
872
+    /**
873
+     * @param Share[] $shares
874
+     * @param $userId
875
+     * @return Share[] The updates shares if no update is found for a share return the original
876
+     */
877
+    private function resolveGroupShares($shares, $userId) {
878
+        $result = [];
879
+
880
+        $start = 0;
881
+        while(true) {
882
+            /** @var Share[] $shareSlice */
883
+            $shareSlice = array_slice($shares, $start, 100);
884
+            $start += 100;
885
+
886
+            if ($shareSlice === []) {
887
+                break;
888
+            }
889
+
890
+            /** @var int[] $ids */
891
+            $ids = [];
892
+            /** @var Share[] $shareMap */
893
+            $shareMap = [];
894
+
895
+            foreach ($shareSlice as $share) {
896
+                $ids[] = (int)$share->getId();
897
+                $shareMap[$share->getId()] = $share;
898
+            }
899
+
900
+            $qb = $this->dbConn->getQueryBuilder();
901
+
902
+            $query = $qb->select('*')
903
+                ->from('share')
904
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
+                ->andWhere($qb->expr()->orX(
907
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
+                ));
910
+
911
+            $stmt = $query->execute();
912
+
913
+            while($data = $stmt->fetch()) {
914
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
916
+            }
917
+
918
+            $stmt->closeCursor();
919
+
920
+            foreach ($shareMap as $share) {
921
+                $result[] = $share;
922
+            }
923
+        }
924
+
925
+        return $result;
926
+    }
927
+
928
+    /**
929
+     * A user is deleted from the system
930
+     * So clean up the relevant shares.
931
+     *
932
+     * @param string $uid
933
+     * @param int $shareType
934
+     */
935
+    public function userDeleted($uid, $shareType) {
936
+        $qb = $this->dbConn->getQueryBuilder();
937
+
938
+        $qb->delete('share');
939
+
940
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
+            /*
942 942
 			 * Delete all user shares that are owned by this user
943 943
 			 * or that are received by this user
944 944
 			 */
945 945
 
946
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
946
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
947 947
 
948
-			$qb->andWhere(
949
-				$qb->expr()->orX(
950
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
-				)
953
-			);
954
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
-			/*
948
+            $qb->andWhere(
949
+                $qb->expr()->orX(
950
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
+                )
953
+            );
954
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
+            /*
956 956
 			 * Delete all group shares that are owned by this user
957 957
 			 * Or special user group shares that are received by this user
958 958
 			 */
959
-			$qb->where(
960
-				$qb->expr()->andX(
961
-					$qb->expr()->orX(
962
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
-					),
965
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
-				)
967
-			);
968
-
969
-			$qb->orWhere(
970
-				$qb->expr()->andX(
971
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
-				)
974
-			);
975
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
-			/*
959
+            $qb->where(
960
+                $qb->expr()->andX(
961
+                    $qb->expr()->orX(
962
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
+                    ),
965
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
+                )
967
+            );
968
+
969
+            $qb->orWhere(
970
+                $qb->expr()->andX(
971
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
+                )
974
+            );
975
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
+            /*
977 977
 			 * Delete all link shares owned by this user.
978 978
 			 * And all link shares initiated by this user (until #22327 is in)
979 979
 			 */
980
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
-
982
-			$qb->andWhere(
983
-				$qb->expr()->orX(
984
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
-				)
987
-			);
988
-		}
989
-
990
-		$qb->execute();
991
-	}
992
-
993
-	/**
994
-	 * Delete all shares received by this group. As well as any custom group
995
-	 * shares for group members.
996
-	 *
997
-	 * @param string $gid
998
-	 */
999
-	public function groupDeleted($gid) {
1000
-		/*
980
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
+
982
+            $qb->andWhere(
983
+                $qb->expr()->orX(
984
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
+                )
987
+            );
988
+        }
989
+
990
+        $qb->execute();
991
+    }
992
+
993
+    /**
994
+     * Delete all shares received by this group. As well as any custom group
995
+     * shares for group members.
996
+     *
997
+     * @param string $gid
998
+     */
999
+    public function groupDeleted($gid) {
1000
+        /*
1001 1001
 		 * First delete all custom group shares for group members
1002 1002
 		 */
1003
-		$qb = $this->dbConn->getQueryBuilder();
1004
-		$qb->select('id')
1005
-			->from('share')
1006
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
-
1009
-		$cursor = $qb->execute();
1010
-		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1013
-		}
1014
-		$cursor->closeCursor();
1015
-
1016
-		if (!empty($ids)) {
1017
-			$chunks = array_chunk($ids, 100);
1018
-			foreach ($chunks as $chunk) {
1019
-				$qb->delete('share')
1020
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
-				$qb->execute();
1023
-			}
1024
-		}
1025
-
1026
-		/*
1003
+        $qb = $this->dbConn->getQueryBuilder();
1004
+        $qb->select('id')
1005
+            ->from('share')
1006
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
+
1009
+        $cursor = $qb->execute();
1010
+        $ids = [];
1011
+        while($row = $cursor->fetch()) {
1012
+            $ids[] = (int)$row['id'];
1013
+        }
1014
+        $cursor->closeCursor();
1015
+
1016
+        if (!empty($ids)) {
1017
+            $chunks = array_chunk($ids, 100);
1018
+            foreach ($chunks as $chunk) {
1019
+                $qb->delete('share')
1020
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
+                $qb->execute();
1023
+            }
1024
+        }
1025
+
1026
+        /*
1027 1027
 		 * Now delete all the group shares
1028 1028
 		 */
1029
-		$qb = $this->dbConn->getQueryBuilder();
1030
-		$qb->delete('share')
1031
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
-		$qb->execute();
1034
-	}
1035
-
1036
-	/**
1037
-	 * Delete custom group shares to this group for this user
1038
-	 *
1039
-	 * @param string $uid
1040
-	 * @param string $gid
1041
-	 */
1042
-	public function userDeletedFromGroup($uid, $gid) {
1043
-		/*
1029
+        $qb = $this->dbConn->getQueryBuilder();
1030
+        $qb->delete('share')
1031
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
+        $qb->execute();
1034
+    }
1035
+
1036
+    /**
1037
+     * Delete custom group shares to this group for this user
1038
+     *
1039
+     * @param string $uid
1040
+     * @param string $gid
1041
+     */
1042
+    public function userDeletedFromGroup($uid, $gid) {
1043
+        /*
1044 1044
 		 * Get all group shares
1045 1045
 		 */
1046
-		$qb = $this->dbConn->getQueryBuilder();
1047
-		$qb->select('id')
1048
-			->from('share')
1049
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
-
1052
-		$cursor = $qb->execute();
1053
-		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1056
-		}
1057
-		$cursor->closeCursor();
1058
-
1059
-		if (!empty($ids)) {
1060
-			$chunks = array_chunk($ids, 100);
1061
-			foreach ($chunks as $chunk) {
1062
-				/*
1046
+        $qb = $this->dbConn->getQueryBuilder();
1047
+        $qb->select('id')
1048
+            ->from('share')
1049
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
+
1052
+        $cursor = $qb->execute();
1053
+        $ids = [];
1054
+        while($row = $cursor->fetch()) {
1055
+            $ids[] = (int)$row['id'];
1056
+        }
1057
+        $cursor->closeCursor();
1058
+
1059
+        if (!empty($ids)) {
1060
+            $chunks = array_chunk($ids, 100);
1061
+            foreach ($chunks as $chunk) {
1062
+                /*
1063 1063
 				 * Delete all special shares wit this users for the found group shares
1064 1064
 				 */
1065
-				$qb->delete('share')
1066
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
-				$qb->execute();
1070
-			}
1071
-		}
1072
-	}
1073
-
1074
-	/**
1075
-	 * @inheritdoc
1076
-	 */
1077
-	public function getAccessList($nodes, $currentAccess) {
1078
-		$ids = [];
1079
-		foreach ($nodes as $node) {
1080
-			$ids[] = $node->getId();
1081
-		}
1082
-
1083
-		$qb = $this->dbConn->getQueryBuilder();
1084
-
1085
-		$or = $qb->expr()->orX(
1086
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1087
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1088
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1089
-		);
1090
-
1091
-		if ($currentAccess) {
1092
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1093
-		}
1094
-
1095
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1096
-			->from('share')
1097
-			->where(
1098
-				$or
1099
-			)
1100
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1101
-			->andWhere($qb->expr()->orX(
1102
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1103
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1104
-			));
1105
-		$cursor = $qb->execute();
1106
-
1107
-		$users = [];
1108
-		$link = false;
1109
-		while($row = $cursor->fetch()) {
1110
-			$type = (int)$row['share_type'];
1111
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112
-				$uid = $row['share_with'];
1113
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1114
-				$users[$uid][$row['id']] = $row;
1115
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1116
-				$gid = $row['share_with'];
1117
-				$group = $this->groupManager->get($gid);
1118
-
1119
-				if ($gid === null) {
1120
-					continue;
1121
-				}
1122
-
1123
-				$userList = $group->getUsers();
1124
-				foreach ($userList as $user) {
1125
-					$uid = $user->getUID();
1126
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1127
-					$users[$uid][$row['id']] = $row;
1128
-				}
1129
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1130
-				$link = true;
1131
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1132
-				$uid = $row['share_with'];
1133
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1134
-				$users[$uid][$row['id']] = $row;
1135
-			}
1136
-		}
1137
-		$cursor->closeCursor();
1138
-
1139
-		if ($currentAccess === true) {
1140
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1141
-			$users = array_filter($users);
1142
-		} else {
1143
-			$users = array_keys($users);
1144
-		}
1145
-
1146
-		return ['users' => $users, 'public' => $link];
1147
-	}
1148
-
1149
-	/**
1150
-	 * For each user the path with the fewest slashes is returned
1151
-	 * @param array $shares
1152
-	 * @return array
1153
-	 */
1154
-	protected function filterSharesOfUser(array $shares) {
1155
-		// Group shares when the user has a share exception
1156
-		foreach ($shares as $id => $share) {
1157
-			$type = (int) $share['share_type'];
1158
-			$permissions = (int) $share['permissions'];
1159
-
1160
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1161
-				unset($shares[$share['parent']]);
1162
-
1163
-				if ($permissions === 0) {
1164
-					unset($shares[$id]);
1165
-				}
1166
-			}
1167
-		}
1168
-
1169
-		$best = [];
1170
-		$bestDepth = 0;
1171
-		foreach ($shares as $id => $share) {
1172
-			$depth = substr_count($share['file_target'], '/');
1173
-			if (empty($best) || $depth < $bestDepth) {
1174
-				$bestDepth = $depth;
1175
-				$best = [
1176
-					'node_id' => $share['file_source'],
1177
-					'node_path' => $share['file_target'],
1178
-				];
1179
-			}
1180
-		}
1181
-
1182
-		return $best;
1183
-	}
1065
+                $qb->delete('share')
1066
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
+                $qb->execute();
1070
+            }
1071
+        }
1072
+    }
1073
+
1074
+    /**
1075
+     * @inheritdoc
1076
+     */
1077
+    public function getAccessList($nodes, $currentAccess) {
1078
+        $ids = [];
1079
+        foreach ($nodes as $node) {
1080
+            $ids[] = $node->getId();
1081
+        }
1082
+
1083
+        $qb = $this->dbConn->getQueryBuilder();
1084
+
1085
+        $or = $qb->expr()->orX(
1086
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1087
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1088
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1089
+        );
1090
+
1091
+        if ($currentAccess) {
1092
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1093
+        }
1094
+
1095
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1096
+            ->from('share')
1097
+            ->where(
1098
+                $or
1099
+            )
1100
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1101
+            ->andWhere($qb->expr()->orX(
1102
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1103
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1104
+            ));
1105
+        $cursor = $qb->execute();
1106
+
1107
+        $users = [];
1108
+        $link = false;
1109
+        while($row = $cursor->fetch()) {
1110
+            $type = (int)$row['share_type'];
1111
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112
+                $uid = $row['share_with'];
1113
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1114
+                $users[$uid][$row['id']] = $row;
1115
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1116
+                $gid = $row['share_with'];
1117
+                $group = $this->groupManager->get($gid);
1118
+
1119
+                if ($gid === null) {
1120
+                    continue;
1121
+                }
1122
+
1123
+                $userList = $group->getUsers();
1124
+                foreach ($userList as $user) {
1125
+                    $uid = $user->getUID();
1126
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1127
+                    $users[$uid][$row['id']] = $row;
1128
+                }
1129
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1130
+                $link = true;
1131
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1132
+                $uid = $row['share_with'];
1133
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1134
+                $users[$uid][$row['id']] = $row;
1135
+            }
1136
+        }
1137
+        $cursor->closeCursor();
1138
+
1139
+        if ($currentAccess === true) {
1140
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1141
+            $users = array_filter($users);
1142
+        } else {
1143
+            $users = array_keys($users);
1144
+        }
1145
+
1146
+        return ['users' => $users, 'public' => $link];
1147
+    }
1148
+
1149
+    /**
1150
+     * For each user the path with the fewest slashes is returned
1151
+     * @param array $shares
1152
+     * @return array
1153
+     */
1154
+    protected function filterSharesOfUser(array $shares) {
1155
+        // Group shares when the user has a share exception
1156
+        foreach ($shares as $id => $share) {
1157
+            $type = (int) $share['share_type'];
1158
+            $permissions = (int) $share['permissions'];
1159
+
1160
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1161
+                unset($shares[$share['parent']]);
1162
+
1163
+                if ($permissions === 0) {
1164
+                    unset($shares[$id]);
1165
+                }
1166
+            }
1167
+        }
1168
+
1169
+        $best = [];
1170
+        $bestDepth = 0;
1171
+        foreach ($shares as $id => $share) {
1172
+            $depth = substr_count($share['file_target'], '/');
1173
+            if (empty($best) || $depth < $bestDepth) {
1174
+                $bestDepth = $depth;
1175
+                $best = [
1176
+                    'node_id' => $share['file_source'],
1177
+                    'node_path' => $share['file_target'],
1178
+                ];
1179
+            }
1180
+        }
1181
+
1182
+        return $best;
1183
+    }
1184 1184
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 			->orderBy('id');
289 289
 
290 290
 		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
291
+		while ($data = $cursor->fetch()) {
292 292
 			$children[] = $this->createShare($data);
293 293
 		}
294 294
 		$cursor->closeCursor();
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 			$user = $this->userManager->get($recipient);
334 334
 
335 335
 			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
336
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
337 337
 			}
338 338
 
339 339
 			if (!$group->inGroup($user)) {
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 			);
494 494
 		}
495 495
 
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497 497
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498 498
 
499 499
 		$qb->orderBy('id');
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 
550 550
 		$cursor = $qb->execute();
551 551
 		$shares = [];
552
-		while($data = $cursor->fetch()) {
552
+		while ($data = $cursor->fetch()) {
553 553
 			$shares[] = $this->createShare($data);
554 554
 		}
555 555
 		$cursor->closeCursor();
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 			->execute();
629 629
 
630 630
 		$shares = [];
631
-		while($data = $cursor->fetch()) {
631
+		while ($data = $cursor->fetch()) {
632 632
 			$shares[] = $this->createShare($data);
633 633
 		}
634 634
 		$cursor->closeCursor();
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 
700 700
 			$cursor = $qb->execute();
701 701
 
702
-			while($data = $cursor->fetch()) {
702
+			while ($data = $cursor->fetch()) {
703 703
 				if ($this->isAccessibleResult($data)) {
704 704
 					$shares[] = $this->createShare($data);
705 705
 				}
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 			$shares2 = [];
715 715
 
716 716
 			$start = 0;
717
-			while(true) {
717
+			while (true) {
718 718
 				$groups = array_slice($allGroups, $start, 100);
719 719
 				$start += 100;
720 720
 
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 					));
758 758
 
759 759
 				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
760
+				while ($data = $cursor->fetch()) {
761 761
 					if ($offset > 0) {
762 762
 						$offset--;
763 763
 						continue;
@@ -826,14 +826,14 @@  discard block
 block discarded – undo
826 826
 	 */
827 827
 	private function createShare($data) {
828 828
 		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
829
+		$share->setId((int) $data['id'])
830
+			->setShareType((int) $data['share_type'])
831
+			->setPermissions((int) $data['permissions'])
832 832
 			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
833
+			->setMailSend((bool) $data['mail_send']);
834 834
 
835 835
 		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
836
+		$shareTime->setTimestamp((int) $data['stime']);
837 837
 		$share->setShareTime($shareTime);
838 838
 
839 839
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 		$share->setSharedBy($data['uid_initiator']);
849 849
 		$share->setShareOwner($data['uid_owner']);
850 850
 
851
-		$share->setNodeId((int)$data['file_source']);
851
+		$share->setNodeId((int) $data['file_source']);
852 852
 		$share->setNodeType($data['item_type']);
853 853
 
854 854
 		if ($data['expiration'] !== null) {
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
 		if (isset($data['f_permissions'])) {
860 860
 			$entryData = $data;
861 861
 			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
862
+			$entryData['parent'] = $entryData['f_parent']; ;
863 863
 			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864 864
 				\OC::$server->getMimeTypeLoader()));
865 865
 		}
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 		$result = [];
879 879
 
880 880
 		$start = 0;
881
-		while(true) {
881
+		while (true) {
882 882
 			/** @var Share[] $shareSlice */
883 883
 			$shareSlice = array_slice($shares, $start, 100);
884 884
 			$start += 100;
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 			$shareMap = [];
894 894
 
895 895
 			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
896
+				$ids[] = (int) $share->getId();
897 897
 				$shareMap[$share->getId()] = $share;
898 898
 			}
899 899
 
@@ -910,8 +910,8 @@  discard block
 block discarded – undo
910 910
 
911 911
 			$stmt = $query->execute();
912 912
 
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
913
+			while ($data = $stmt->fetch()) {
914
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
915 915
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
916 916
 			}
917 917
 
@@ -1008,8 +1008,8 @@  discard block
 block discarded – undo
1008 1008
 
1009 1009
 		$cursor = $qb->execute();
1010 1010
 		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1011
+		while ($row = $cursor->fetch()) {
1012
+			$ids[] = (int) $row['id'];
1013 1013
 		}
1014 1014
 		$cursor->closeCursor();
1015 1015
 
@@ -1051,8 +1051,8 @@  discard block
 block discarded – undo
1051 1051
 
1052 1052
 		$cursor = $qb->execute();
1053 1053
 		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1054
+		while ($row = $cursor->fetch()) {
1055
+			$ids[] = (int) $row['id'];
1056 1056
 		}
1057 1057
 		$cursor->closeCursor();
1058 1058
 
@@ -1106,8 +1106,8 @@  discard block
 block discarded – undo
1106 1106
 
1107 1107
 		$users = [];
1108 1108
 		$link = false;
1109
-		while($row = $cursor->fetch()) {
1110
-			$type = (int)$row['share_type'];
1109
+		while ($row = $cursor->fetch()) {
1110
+			$type = (int) $row['share_type'];
1111 1111
 			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112 1112
 				$uid = $row['share_with'];
1113 1113
 				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 4 patches
Doc Comments   +10 added lines, -4 removed lines patch added patch discarded remove patch
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 *
159 159
 	 * By default this excludes the automatically generated birthday calendar
160 160
 	 *
161
-	 * @param $principalUri
161
+	 * @param string $principalUri
162 162
 	 * @param bool $excludeBirthday
163 163
 	 * @return int
164 164
 	 */
@@ -303,6 +303,9 @@  discard block
 block discarded – undo
303 303
 		return array_values($calendars);
304 304
 	}
305 305
 
306
+	/**
307
+	 * @param string $principalUri
308
+	 */
306 309
 	public function getUsersOwnCalendars($principalUri) {
307 310
 		$principalUri = $this->convertPrincipal($principalUri, true);
308 311
 		$fields = array_values($this->propertyMap);
@@ -851,7 +854,7 @@  discard block
 block discarded – undo
851 854
 	 * calendar-data. If the result of a subsequent GET to this object is not
852 855
 	 * the exact same as this request body, you should omit the ETag.
853 856
 	 *
854
-	 * @param mixed $calendarId
857
+	 * @param integer $calendarId
855 858
 	 * @param string $objectUri
856 859
 	 * @param string $calendarData
857 860
 	 * @return string
@@ -894,7 +897,7 @@  discard block
 block discarded – undo
894 897
 	 * calendar-data. If the result of a subsequent GET to this object is not
895 898
 	 * the exact same as this request body, you should omit the ETag.
896 899
 	 *
897
-	 * @param mixed $calendarId
900
+	 * @param integer $calendarId
898 901
 	 * @param string $objectUri
899 902
 	 * @param string $calendarData
900 903
 	 * @return string
@@ -1309,7 +1312,7 @@  discard block
 block discarded – undo
1309 1312
 	 * @param string $principalUri
1310 1313
 	 * @param string $uri
1311 1314
 	 * @param array $properties
1312
-	 * @return mixed
1315
+	 * @return integer
1313 1316
 	 */
1314 1317
 	function createSubscription($principalUri, $uri, array $properties) {
1315 1318
 
@@ -1712,6 +1715,9 @@  discard block
 block discarded – undo
1712 1715
 		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1713 1716
 	}
1714 1717
 
1718
+	/**
1719
+	 * @param boolean $toV2
1720
+	 */
1715 1721
 	private function convertPrincipal($principalUri, $toV2) {
1716 1722
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1717 1723
 			list(, $name) = URLUtil::splitPath($principalUri);
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -808,7 +808,9 @@
 block discarded – undo
808 808
 		$stmt = $query->execute();
809 809
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810 810
 
811
-		if(!$row) return null;
811
+		if(!$row) {
812
+		    return null;
813
+		}
812 814
 
813 815
 		return [
814 816
 				'id'            => $row['id'],
Please login to merge, or discard this patch.
Indentation   +1785 added lines, -1785 removed lines patch added patch discarded remove patch
@@ -59,1790 +59,1790 @@
 block discarded – undo
59 59
  */
60 60
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
61 61
 
62
-	const PERSONAL_CALENDAR_URI = 'personal';
63
-	const PERSONAL_CALENDAR_NAME = 'Personal';
64
-
65
-	/**
66
-	 * We need to specify a max date, because we need to stop *somewhere*
67
-	 *
68
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
69
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
-	 * in 2038-01-19 to avoid problems when the date is converted
71
-	 * to a unix timestamp.
72
-	 */
73
-	const MAX_DATE = '2038-01-01';
74
-
75
-	const ACCESS_PUBLIC = 4;
76
-	const CLASSIFICATION_PUBLIC = 0;
77
-	const CLASSIFICATION_PRIVATE = 1;
78
-	const CLASSIFICATION_CONFIDENTIAL = 2;
79
-
80
-	/**
81
-	 * List of CalDAV properties, and how they map to database field names
82
-	 * Add your own properties by simply adding on to this array.
83
-	 *
84
-	 * Note that only string-based properties are supported here.
85
-	 *
86
-	 * @var array
87
-	 */
88
-	public $propertyMap = [
89
-		'{DAV:}displayname'                          => 'displayname',
90
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
-	];
95
-
96
-	/**
97
-	 * List of subscription properties, and how they map to database field names.
98
-	 *
99
-	 * @var array
100
-	 */
101
-	public $subscriptionPropertyMap = [
102
-		'{DAV:}displayname'                                           => 'displayname',
103
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
-	];
110
-
111
-	/**
112
-	 * @var string[] Map of uid => display name
113
-	 */
114
-	protected $userDisplayNames;
115
-
116
-	/** @var IDBConnection */
117
-	private $db;
118
-
119
-	/** @var Backend */
120
-	private $sharingBackend;
121
-
122
-	/** @var Principal */
123
-	private $principalBackend;
124
-
125
-	/** @var IUserManager */
126
-	private $userManager;
127
-
128
-	/** @var ISecureRandom */
129
-	private $random;
130
-
131
-	/** @var EventDispatcherInterface */
132
-	private $dispatcher;
133
-
134
-	/** @var bool */
135
-	private $legacyEndpoint;
136
-
137
-	/**
138
-	 * CalDavBackend constructor.
139
-	 *
140
-	 * @param IDBConnection $db
141
-	 * @param Principal $principalBackend
142
-	 * @param IUserManager $userManager
143
-	 * @param ISecureRandom $random
144
-	 * @param EventDispatcherInterface $dispatcher
145
-	 * @param bool $legacyEndpoint
146
-	 */
147
-	public function __construct(IDBConnection $db,
148
-								Principal $principalBackend,
149
-								IUserManager $userManager,
150
-								ISecureRandom $random,
151
-								EventDispatcherInterface $dispatcher,
152
-								$legacyEndpoint = false) {
153
-		$this->db = $db;
154
-		$this->principalBackend = $principalBackend;
155
-		$this->userManager = $userManager;
156
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
-		$this->random = $random;
158
-		$this->dispatcher = $dispatcher;
159
-		$this->legacyEndpoint = $legacyEndpoint;
160
-	}
161
-
162
-	/**
163
-	 * Return the number of calendars for a principal
164
-	 *
165
-	 * By default this excludes the automatically generated birthday calendar
166
-	 *
167
-	 * @param $principalUri
168
-	 * @param bool $excludeBirthday
169
-	 * @return int
170
-	 */
171
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
-		$principalUri = $this->convertPrincipal($principalUri, true);
173
-		$query = $this->db->getQueryBuilder();
174
-		$query->select($query->createFunction('COUNT(*)'))
175
-			->from('calendars')
176
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
-
178
-		if ($excludeBirthday) {
179
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
-		}
181
-
182
-		return (int)$query->execute()->fetchColumn();
183
-	}
184
-
185
-	/**
186
-	 * Returns a list of calendars for a principal.
187
-	 *
188
-	 * Every project is an array with the following keys:
189
-	 *  * id, a unique id that will be used by other functions to modify the
190
-	 *    calendar. This can be the same as the uri or a database key.
191
-	 *  * uri, which the basename of the uri with which the calendar is
192
-	 *    accessed.
193
-	 *  * principaluri. The owner of the calendar. Almost always the same as
194
-	 *    principalUri passed to this method.
195
-	 *
196
-	 * Furthermore it can contain webdav properties in clark notation. A very
197
-	 * common one is '{DAV:}displayname'.
198
-	 *
199
-	 * Many clients also require:
200
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
-	 * For this property, you can just return an instance of
202
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
-	 *
204
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
-	 * ACL will automatically be put in read-only mode.
206
-	 *
207
-	 * @param string $principalUri
208
-	 * @return array
209
-	 */
210
-	function getCalendarsForUser($principalUri) {
211
-		$principalUriOriginal = $principalUri;
212
-		$principalUri = $this->convertPrincipal($principalUri, true);
213
-		$fields = array_values($this->propertyMap);
214
-		$fields[] = 'id';
215
-		$fields[] = 'uri';
216
-		$fields[] = 'synctoken';
217
-		$fields[] = 'components';
218
-		$fields[] = 'principaluri';
219
-		$fields[] = 'transparent';
220
-
221
-		// Making fields a comma-delimited list
222
-		$query = $this->db->getQueryBuilder();
223
-		$query->select($fields)->from('calendars')
224
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
-				->orderBy('calendarorder', 'ASC');
226
-		$stmt = $query->execute();
227
-
228
-		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
-
231
-			$components = [];
232
-			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
234
-			}
235
-
236
-			$calendar = [
237
-				'id' => $row['id'],
238
-				'uri' => $row['uri'],
239
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
-			];
246
-
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
248
-				$calendar[$xmlName] = $row[$dbName];
249
-			}
250
-
251
-			$this->addOwnerPrincipal($calendar);
252
-
253
-			if (!isset($calendars[$calendar['id']])) {
254
-				$calendars[$calendar['id']] = $calendar;
255
-			}
256
-		}
257
-
258
-		$stmt->closeCursor();
259
-
260
-		// query for shared calendars
261
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
262
-		$principals[]= $principalUri;
263
-
264
-		$fields = array_values($this->propertyMap);
265
-		$fields[] = 'a.id';
266
-		$fields[] = 'a.uri';
267
-		$fields[] = 'a.synctoken';
268
-		$fields[] = 'a.components';
269
-		$fields[] = 'a.principaluri';
270
-		$fields[] = 'a.transparent';
271
-		$fields[] = 's.access';
272
-		$query = $this->db->getQueryBuilder();
273
-		$result = $query->select($fields)
274
-			->from('dav_shares', 's')
275
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
276
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
277
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
278
-			->setParameter('type', 'calendar')
279
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
280
-			->execute();
281
-
282
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
283
-		while($row = $result->fetch()) {
284
-			if ($row['principaluri'] === $principalUri) {
285
-				continue;
286
-			}
287
-
288
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
289
-			if (isset($calendars[$row['id']])) {
290
-				if ($readOnly) {
291
-					// New share can not have more permissions then the old one.
292
-					continue;
293
-				}
294
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
295
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
296
-					// Old share is already read-write, no more permissions can be gained
297
-					continue;
298
-				}
299
-			}
300
-
301
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
302
-			$uri = $row['uri'] . '_shared_by_' . $name;
303
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
304
-			$components = [];
305
-			if ($row['components']) {
306
-				$components = explode(',',$row['components']);
307
-			}
308
-			$calendar = [
309
-				'id' => $row['id'],
310
-				'uri' => $uri,
311
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
312
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
313
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
314
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
315
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
316
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
317
-				$readOnlyPropertyName => $readOnly,
318
-			];
319
-
320
-			foreach($this->propertyMap as $xmlName=>$dbName) {
321
-				$calendar[$xmlName] = $row[$dbName];
322
-			}
323
-
324
-			$this->addOwnerPrincipal($calendar);
325
-
326
-			$calendars[$calendar['id']] = $calendar;
327
-		}
328
-		$result->closeCursor();
329
-
330
-		return array_values($calendars);
331
-	}
332
-
333
-	public function getUsersOwnCalendars($principalUri) {
334
-		$principalUri = $this->convertPrincipal($principalUri, true);
335
-		$fields = array_values($this->propertyMap);
336
-		$fields[] = 'id';
337
-		$fields[] = 'uri';
338
-		$fields[] = 'synctoken';
339
-		$fields[] = 'components';
340
-		$fields[] = 'principaluri';
341
-		$fields[] = 'transparent';
342
-		// Making fields a comma-delimited list
343
-		$query = $this->db->getQueryBuilder();
344
-		$query->select($fields)->from('calendars')
345
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
346
-			->orderBy('calendarorder', 'ASC');
347
-		$stmt = $query->execute();
348
-		$calendars = [];
349
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
350
-			$components = [];
351
-			if ($row['components']) {
352
-				$components = explode(',',$row['components']);
353
-			}
354
-			$calendar = [
355
-				'id' => $row['id'],
356
-				'uri' => $row['uri'],
357
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
358
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
359
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
360
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
361
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
362
-			];
363
-			foreach($this->propertyMap as $xmlName=>$dbName) {
364
-				$calendar[$xmlName] = $row[$dbName];
365
-			}
366
-
367
-			$this->addOwnerPrincipal($calendar);
368
-
369
-			if (!isset($calendars[$calendar['id']])) {
370
-				$calendars[$calendar['id']] = $calendar;
371
-			}
372
-		}
373
-		$stmt->closeCursor();
374
-		return array_values($calendars);
375
-	}
376
-
377
-
378
-	private function getUserDisplayName($uid) {
379
-		if (!isset($this->userDisplayNames[$uid])) {
380
-			$user = $this->userManager->get($uid);
381
-
382
-			if ($user instanceof IUser) {
383
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
384
-			} else {
385
-				$this->userDisplayNames[$uid] = $uid;
386
-			}
387
-		}
388
-
389
-		return $this->userDisplayNames[$uid];
390
-	}
62
+    const PERSONAL_CALENDAR_URI = 'personal';
63
+    const PERSONAL_CALENDAR_NAME = 'Personal';
64
+
65
+    /**
66
+     * We need to specify a max date, because we need to stop *somewhere*
67
+     *
68
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
69
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
+     * in 2038-01-19 to avoid problems when the date is converted
71
+     * to a unix timestamp.
72
+     */
73
+    const MAX_DATE = '2038-01-01';
74
+
75
+    const ACCESS_PUBLIC = 4;
76
+    const CLASSIFICATION_PUBLIC = 0;
77
+    const CLASSIFICATION_PRIVATE = 1;
78
+    const CLASSIFICATION_CONFIDENTIAL = 2;
79
+
80
+    /**
81
+     * List of CalDAV properties, and how they map to database field names
82
+     * Add your own properties by simply adding on to this array.
83
+     *
84
+     * Note that only string-based properties are supported here.
85
+     *
86
+     * @var array
87
+     */
88
+    public $propertyMap = [
89
+        '{DAV:}displayname'                          => 'displayname',
90
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
+    ];
95
+
96
+    /**
97
+     * List of subscription properties, and how they map to database field names.
98
+     *
99
+     * @var array
100
+     */
101
+    public $subscriptionPropertyMap = [
102
+        '{DAV:}displayname'                                           => 'displayname',
103
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
+    ];
110
+
111
+    /**
112
+     * @var string[] Map of uid => display name
113
+     */
114
+    protected $userDisplayNames;
115
+
116
+    /** @var IDBConnection */
117
+    private $db;
118
+
119
+    /** @var Backend */
120
+    private $sharingBackend;
121
+
122
+    /** @var Principal */
123
+    private $principalBackend;
124
+
125
+    /** @var IUserManager */
126
+    private $userManager;
127
+
128
+    /** @var ISecureRandom */
129
+    private $random;
130
+
131
+    /** @var EventDispatcherInterface */
132
+    private $dispatcher;
133
+
134
+    /** @var bool */
135
+    private $legacyEndpoint;
136
+
137
+    /**
138
+     * CalDavBackend constructor.
139
+     *
140
+     * @param IDBConnection $db
141
+     * @param Principal $principalBackend
142
+     * @param IUserManager $userManager
143
+     * @param ISecureRandom $random
144
+     * @param EventDispatcherInterface $dispatcher
145
+     * @param bool $legacyEndpoint
146
+     */
147
+    public function __construct(IDBConnection $db,
148
+                                Principal $principalBackend,
149
+                                IUserManager $userManager,
150
+                                ISecureRandom $random,
151
+                                EventDispatcherInterface $dispatcher,
152
+                                $legacyEndpoint = false) {
153
+        $this->db = $db;
154
+        $this->principalBackend = $principalBackend;
155
+        $this->userManager = $userManager;
156
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
+        $this->random = $random;
158
+        $this->dispatcher = $dispatcher;
159
+        $this->legacyEndpoint = $legacyEndpoint;
160
+    }
161
+
162
+    /**
163
+     * Return the number of calendars for a principal
164
+     *
165
+     * By default this excludes the automatically generated birthday calendar
166
+     *
167
+     * @param $principalUri
168
+     * @param bool $excludeBirthday
169
+     * @return int
170
+     */
171
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
+        $principalUri = $this->convertPrincipal($principalUri, true);
173
+        $query = $this->db->getQueryBuilder();
174
+        $query->select($query->createFunction('COUNT(*)'))
175
+            ->from('calendars')
176
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
+
178
+        if ($excludeBirthday) {
179
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
+        }
181
+
182
+        return (int)$query->execute()->fetchColumn();
183
+    }
184
+
185
+    /**
186
+     * Returns a list of calendars for a principal.
187
+     *
188
+     * Every project is an array with the following keys:
189
+     *  * id, a unique id that will be used by other functions to modify the
190
+     *    calendar. This can be the same as the uri or a database key.
191
+     *  * uri, which the basename of the uri with which the calendar is
192
+     *    accessed.
193
+     *  * principaluri. The owner of the calendar. Almost always the same as
194
+     *    principalUri passed to this method.
195
+     *
196
+     * Furthermore it can contain webdav properties in clark notation. A very
197
+     * common one is '{DAV:}displayname'.
198
+     *
199
+     * Many clients also require:
200
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
+     * For this property, you can just return an instance of
202
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
+     *
204
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
+     * ACL will automatically be put in read-only mode.
206
+     *
207
+     * @param string $principalUri
208
+     * @return array
209
+     */
210
+    function getCalendarsForUser($principalUri) {
211
+        $principalUriOriginal = $principalUri;
212
+        $principalUri = $this->convertPrincipal($principalUri, true);
213
+        $fields = array_values($this->propertyMap);
214
+        $fields[] = 'id';
215
+        $fields[] = 'uri';
216
+        $fields[] = 'synctoken';
217
+        $fields[] = 'components';
218
+        $fields[] = 'principaluri';
219
+        $fields[] = 'transparent';
220
+
221
+        // Making fields a comma-delimited list
222
+        $query = $this->db->getQueryBuilder();
223
+        $query->select($fields)->from('calendars')
224
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
+                ->orderBy('calendarorder', 'ASC');
226
+        $stmt = $query->execute();
227
+
228
+        $calendars = [];
229
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
+
231
+            $components = [];
232
+            if ($row['components']) {
233
+                $components = explode(',',$row['components']);
234
+            }
235
+
236
+            $calendar = [
237
+                'id' => $row['id'],
238
+                'uri' => $row['uri'],
239
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
+            ];
246
+
247
+            foreach($this->propertyMap as $xmlName=>$dbName) {
248
+                $calendar[$xmlName] = $row[$dbName];
249
+            }
250
+
251
+            $this->addOwnerPrincipal($calendar);
252
+
253
+            if (!isset($calendars[$calendar['id']])) {
254
+                $calendars[$calendar['id']] = $calendar;
255
+            }
256
+        }
257
+
258
+        $stmt->closeCursor();
259
+
260
+        // query for shared calendars
261
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
262
+        $principals[]= $principalUri;
263
+
264
+        $fields = array_values($this->propertyMap);
265
+        $fields[] = 'a.id';
266
+        $fields[] = 'a.uri';
267
+        $fields[] = 'a.synctoken';
268
+        $fields[] = 'a.components';
269
+        $fields[] = 'a.principaluri';
270
+        $fields[] = 'a.transparent';
271
+        $fields[] = 's.access';
272
+        $query = $this->db->getQueryBuilder();
273
+        $result = $query->select($fields)
274
+            ->from('dav_shares', 's')
275
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
276
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
277
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
278
+            ->setParameter('type', 'calendar')
279
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
280
+            ->execute();
281
+
282
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
283
+        while($row = $result->fetch()) {
284
+            if ($row['principaluri'] === $principalUri) {
285
+                continue;
286
+            }
287
+
288
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
289
+            if (isset($calendars[$row['id']])) {
290
+                if ($readOnly) {
291
+                    // New share can not have more permissions then the old one.
292
+                    continue;
293
+                }
294
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
295
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
296
+                    // Old share is already read-write, no more permissions can be gained
297
+                    continue;
298
+                }
299
+            }
300
+
301
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
302
+            $uri = $row['uri'] . '_shared_by_' . $name;
303
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
304
+            $components = [];
305
+            if ($row['components']) {
306
+                $components = explode(',',$row['components']);
307
+            }
308
+            $calendar = [
309
+                'id' => $row['id'],
310
+                'uri' => $uri,
311
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
312
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
313
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
314
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
315
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
316
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
317
+                $readOnlyPropertyName => $readOnly,
318
+            ];
319
+
320
+            foreach($this->propertyMap as $xmlName=>$dbName) {
321
+                $calendar[$xmlName] = $row[$dbName];
322
+            }
323
+
324
+            $this->addOwnerPrincipal($calendar);
325
+
326
+            $calendars[$calendar['id']] = $calendar;
327
+        }
328
+        $result->closeCursor();
329
+
330
+        return array_values($calendars);
331
+    }
332
+
333
+    public function getUsersOwnCalendars($principalUri) {
334
+        $principalUri = $this->convertPrincipal($principalUri, true);
335
+        $fields = array_values($this->propertyMap);
336
+        $fields[] = 'id';
337
+        $fields[] = 'uri';
338
+        $fields[] = 'synctoken';
339
+        $fields[] = 'components';
340
+        $fields[] = 'principaluri';
341
+        $fields[] = 'transparent';
342
+        // Making fields a comma-delimited list
343
+        $query = $this->db->getQueryBuilder();
344
+        $query->select($fields)->from('calendars')
345
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
346
+            ->orderBy('calendarorder', 'ASC');
347
+        $stmt = $query->execute();
348
+        $calendars = [];
349
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
350
+            $components = [];
351
+            if ($row['components']) {
352
+                $components = explode(',',$row['components']);
353
+            }
354
+            $calendar = [
355
+                'id' => $row['id'],
356
+                'uri' => $row['uri'],
357
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
358
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
359
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
360
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
361
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
362
+            ];
363
+            foreach($this->propertyMap as $xmlName=>$dbName) {
364
+                $calendar[$xmlName] = $row[$dbName];
365
+            }
366
+
367
+            $this->addOwnerPrincipal($calendar);
368
+
369
+            if (!isset($calendars[$calendar['id']])) {
370
+                $calendars[$calendar['id']] = $calendar;
371
+            }
372
+        }
373
+        $stmt->closeCursor();
374
+        return array_values($calendars);
375
+    }
376
+
377
+
378
+    private function getUserDisplayName($uid) {
379
+        if (!isset($this->userDisplayNames[$uid])) {
380
+            $user = $this->userManager->get($uid);
381
+
382
+            if ($user instanceof IUser) {
383
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
384
+            } else {
385
+                $this->userDisplayNames[$uid] = $uid;
386
+            }
387
+        }
388
+
389
+        return $this->userDisplayNames[$uid];
390
+    }
391 391
 	
392
-	/**
393
-	 * @return array
394
-	 */
395
-	public function getPublicCalendars() {
396
-		$fields = array_values($this->propertyMap);
397
-		$fields[] = 'a.id';
398
-		$fields[] = 'a.uri';
399
-		$fields[] = 'a.synctoken';
400
-		$fields[] = 'a.components';
401
-		$fields[] = 'a.principaluri';
402
-		$fields[] = 'a.transparent';
403
-		$fields[] = 's.access';
404
-		$fields[] = 's.publicuri';
405
-		$calendars = [];
406
-		$query = $this->db->getQueryBuilder();
407
-		$result = $query->select($fields)
408
-			->from('dav_shares', 's')
409
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
410
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
411
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
412
-			->execute();
413
-
414
-		while($row = $result->fetch()) {
415
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
416
-			$row['displayname'] = $row['displayname'] . "($name)";
417
-			$components = [];
418
-			if ($row['components']) {
419
-				$components = explode(',',$row['components']);
420
-			}
421
-			$calendar = [
422
-				'id' => $row['id'],
423
-				'uri' => $row['publicuri'],
424
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
425
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
426
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
427
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
428
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
429
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
430
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
431
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
432
-			];
433
-
434
-			foreach($this->propertyMap as $xmlName=>$dbName) {
435
-				$calendar[$xmlName] = $row[$dbName];
436
-			}
437
-
438
-			$this->addOwnerPrincipal($calendar);
439
-
440
-			if (!isset($calendars[$calendar['id']])) {
441
-				$calendars[$calendar['id']] = $calendar;
442
-			}
443
-		}
444
-		$result->closeCursor();
445
-
446
-		return array_values($calendars);
447
-	}
448
-
449
-	/**
450
-	 * @param string $uri
451
-	 * @return array
452
-	 * @throws NotFound
453
-	 */
454
-	public function getPublicCalendar($uri) {
455
-		$fields = array_values($this->propertyMap);
456
-		$fields[] = 'a.id';
457
-		$fields[] = 'a.uri';
458
-		$fields[] = 'a.synctoken';
459
-		$fields[] = 'a.components';
460
-		$fields[] = 'a.principaluri';
461
-		$fields[] = 'a.transparent';
462
-		$fields[] = 's.access';
463
-		$fields[] = 's.publicuri';
464
-		$query = $this->db->getQueryBuilder();
465
-		$result = $query->select($fields)
466
-			->from('dav_shares', 's')
467
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
468
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
469
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
470
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
471
-			->execute();
472
-
473
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
474
-
475
-		$result->closeCursor();
476
-
477
-		if ($row === false) {
478
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
479
-		}
480
-
481
-		list(, $name) = URLUtil::splitPath($row['principaluri']);
482
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
483
-		$components = [];
484
-		if ($row['components']) {
485
-			$components = explode(',',$row['components']);
486
-		}
487
-		$calendar = [
488
-			'id' => $row['id'],
489
-			'uri' => $row['publicuri'],
490
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
491
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
492
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
493
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
495
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
496
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
497
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
498
-		];
499
-
500
-		foreach($this->propertyMap as $xmlName=>$dbName) {
501
-			$calendar[$xmlName] = $row[$dbName];
502
-		}
503
-
504
-		$this->addOwnerPrincipal($calendar);
505
-
506
-		return $calendar;
507
-
508
-	}
509
-
510
-	/**
511
-	 * @param string $principal
512
-	 * @param string $uri
513
-	 * @return array|null
514
-	 */
515
-	public function getCalendarByUri($principal, $uri) {
516
-		$fields = array_values($this->propertyMap);
517
-		$fields[] = 'id';
518
-		$fields[] = 'uri';
519
-		$fields[] = 'synctoken';
520
-		$fields[] = 'components';
521
-		$fields[] = 'principaluri';
522
-		$fields[] = 'transparent';
523
-
524
-		// Making fields a comma-delimited list
525
-		$query = $this->db->getQueryBuilder();
526
-		$query->select($fields)->from('calendars')
527
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
528
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
529
-			->setMaxResults(1);
530
-		$stmt = $query->execute();
531
-
532
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
533
-		$stmt->closeCursor();
534
-		if ($row === false) {
535
-			return null;
536
-		}
537
-
538
-		$components = [];
539
-		if ($row['components']) {
540
-			$components = explode(',',$row['components']);
541
-		}
542
-
543
-		$calendar = [
544
-			'id' => $row['id'],
545
-			'uri' => $row['uri'],
546
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
547
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
548
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
549
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
550
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
551
-		];
552
-
553
-		foreach($this->propertyMap as $xmlName=>$dbName) {
554
-			$calendar[$xmlName] = $row[$dbName];
555
-		}
556
-
557
-		$this->addOwnerPrincipal($calendar);
558
-
559
-		return $calendar;
560
-	}
561
-
562
-	public function getCalendarById($calendarId) {
563
-		$fields = array_values($this->propertyMap);
564
-		$fields[] = 'id';
565
-		$fields[] = 'uri';
566
-		$fields[] = 'synctoken';
567
-		$fields[] = 'components';
568
-		$fields[] = 'principaluri';
569
-		$fields[] = 'transparent';
570
-
571
-		// Making fields a comma-delimited list
572
-		$query = $this->db->getQueryBuilder();
573
-		$query->select($fields)->from('calendars')
574
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
575
-			->setMaxResults(1);
576
-		$stmt = $query->execute();
577
-
578
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
579
-		$stmt->closeCursor();
580
-		if ($row === false) {
581
-			return null;
582
-		}
583
-
584
-		$components = [];
585
-		if ($row['components']) {
586
-			$components = explode(',',$row['components']);
587
-		}
588
-
589
-		$calendar = [
590
-			'id' => $row['id'],
591
-			'uri' => $row['uri'],
592
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
593
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
594
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
595
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
596
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
597
-		];
598
-
599
-		foreach($this->propertyMap as $xmlName=>$dbName) {
600
-			$calendar[$xmlName] = $row[$dbName];
601
-		}
602
-
603
-		$this->addOwnerPrincipal($calendar);
604
-
605
-		return $calendar;
606
-	}
607
-
608
-	/**
609
-	 * Creates a new calendar for a principal.
610
-	 *
611
-	 * If the creation was a success, an id must be returned that can be used to reference
612
-	 * this calendar in other methods, such as updateCalendar.
613
-	 *
614
-	 * @param string $principalUri
615
-	 * @param string $calendarUri
616
-	 * @param array $properties
617
-	 * @return int
618
-	 */
619
-	function createCalendar($principalUri, $calendarUri, array $properties) {
620
-		$values = [
621
-			'principaluri' => $this->convertPrincipal($principalUri, true),
622
-			'uri'          => $calendarUri,
623
-			'synctoken'    => 1,
624
-			'transparent'  => 0,
625
-			'components'   => 'VEVENT,VTODO',
626
-			'displayname'  => $calendarUri
627
-		];
628
-
629
-		// Default value
630
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
631
-		if (isset($properties[$sccs])) {
632
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
633
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
634
-			}
635
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
636
-		}
637
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
638
-		if (isset($properties[$transp])) {
639
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
640
-		}
641
-
642
-		foreach($this->propertyMap as $xmlName=>$dbName) {
643
-			if (isset($properties[$xmlName])) {
644
-				$values[$dbName] = $properties[$xmlName];
645
-			}
646
-		}
647
-
648
-		$query = $this->db->getQueryBuilder();
649
-		$query->insert('calendars');
650
-		foreach($values as $column => $value) {
651
-			$query->setValue($column, $query->createNamedParameter($value));
652
-		}
653
-		$query->execute();
654
-		$calendarId = $query->getLastInsertId();
655
-
656
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
657
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
658
-			[
659
-				'calendarId' => $calendarId,
660
-				'calendarData' => $this->getCalendarById($calendarId),
661
-		]));
662
-
663
-		return $calendarId;
664
-	}
665
-
666
-	/**
667
-	 * Updates properties for a calendar.
668
-	 *
669
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
670
-	 * To do the actual updates, you must tell this object which properties
671
-	 * you're going to process with the handle() method.
672
-	 *
673
-	 * Calling the handle method is like telling the PropPatch object "I
674
-	 * promise I can handle updating this property".
675
-	 *
676
-	 * Read the PropPatch documentation for more info and examples.
677
-	 *
678
-	 * @param PropPatch $propPatch
679
-	 * @return void
680
-	 */
681
-	function updateCalendar($calendarId, PropPatch $propPatch) {
682
-		$supportedProperties = array_keys($this->propertyMap);
683
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
684
-
685
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
686
-			$newValues = [];
687
-			foreach ($mutations as $propertyName => $propertyValue) {
688
-
689
-				switch ($propertyName) {
690
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
691
-						$fieldName = 'transparent';
692
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
693
-						break;
694
-					default :
695
-						$fieldName = $this->propertyMap[$propertyName];
696
-						$newValues[$fieldName] = $propertyValue;
697
-						break;
698
-				}
699
-
700
-			}
701
-			$query = $this->db->getQueryBuilder();
702
-			$query->update('calendars');
703
-			foreach ($newValues as $fieldName => $value) {
704
-				$query->set($fieldName, $query->createNamedParameter($value));
705
-			}
706
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
707
-			$query->execute();
708
-
709
-			$this->addChange($calendarId, "", 2);
710
-
711
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
712
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
713
-				[
714
-					'calendarId' => $calendarId,
715
-					'calendarData' => $this->getCalendarById($calendarId),
716
-					'shares' => $this->getShares($calendarId),
717
-					'propertyMutations' => $mutations,
718
-			]));
719
-
720
-			return true;
721
-		});
722
-	}
723
-
724
-	/**
725
-	 * Delete a calendar and all it's objects
726
-	 *
727
-	 * @param mixed $calendarId
728
-	 * @return void
729
-	 */
730
-	function deleteCalendar($calendarId) {
731
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
732
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
733
-			[
734
-				'calendarId' => $calendarId,
735
-				'calendarData' => $this->getCalendarById($calendarId),
736
-				'shares' => $this->getShares($calendarId),
737
-		]));
738
-
739
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
740
-		$stmt->execute([$calendarId]);
741
-
742
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
743
-		$stmt->execute([$calendarId]);
744
-
745
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
746
-		$stmt->execute([$calendarId]);
747
-
748
-		$this->sharingBackend->deleteAllShares($calendarId);
749
-	}
750
-
751
-	/**
752
-	 * Delete all of an user's shares
753
-	 *
754
-	 * @param string $principaluri
755
-	 * @return void
756
-	 */
757
-	function deleteAllSharesByUser($principaluri) {
758
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
759
-	}
760
-
761
-	/**
762
-	 * Returns all calendar objects within a calendar.
763
-	 *
764
-	 * Every item contains an array with the following keys:
765
-	 *   * calendardata - The iCalendar-compatible calendar data
766
-	 *   * uri - a unique key which will be used to construct the uri. This can
767
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
768
-	 *     good idea. This is only the basename, or filename, not the full
769
-	 *     path.
770
-	 *   * lastmodified - a timestamp of the last modification time
771
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
772
-	 *   '"abcdef"')
773
-	 *   * size - The size of the calendar objects, in bytes.
774
-	 *   * component - optional, a string containing the type of object, such
775
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
776
-	 *     the Content-Type header.
777
-	 *
778
-	 * Note that the etag is optional, but it's highly encouraged to return for
779
-	 * speed reasons.
780
-	 *
781
-	 * The calendardata is also optional. If it's not returned
782
-	 * 'getCalendarObject' will be called later, which *is* expected to return
783
-	 * calendardata.
784
-	 *
785
-	 * If neither etag or size are specified, the calendardata will be
786
-	 * used/fetched to determine these numbers. If both are specified the
787
-	 * amount of times this is needed is reduced by a great degree.
788
-	 *
789
-	 * @param mixed $calendarId
790
-	 * @return array
791
-	 */
792
-	function getCalendarObjects($calendarId) {
793
-		$query = $this->db->getQueryBuilder();
794
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
795
-			->from('calendarobjects')
796
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
797
-		$stmt = $query->execute();
798
-
799
-		$result = [];
800
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
801
-			$result[] = [
802
-					'id'           => $row['id'],
803
-					'uri'          => $row['uri'],
804
-					'lastmodified' => $row['lastmodified'],
805
-					'etag'         => '"' . $row['etag'] . '"',
806
-					'calendarid'   => $row['calendarid'],
807
-					'size'         => (int)$row['size'],
808
-					'component'    => strtolower($row['componenttype']),
809
-					'classification'=> (int)$row['classification']
810
-			];
811
-		}
812
-
813
-		return $result;
814
-	}
815
-
816
-	/**
817
-	 * Returns information from a single calendar object, based on it's object
818
-	 * uri.
819
-	 *
820
-	 * The object uri is only the basename, or filename and not a full path.
821
-	 *
822
-	 * The returned array must have the same keys as getCalendarObjects. The
823
-	 * 'calendardata' object is required here though, while it's not required
824
-	 * for getCalendarObjects.
825
-	 *
826
-	 * This method must return null if the object did not exist.
827
-	 *
828
-	 * @param mixed $calendarId
829
-	 * @param string $objectUri
830
-	 * @return array|null
831
-	 */
832
-	function getCalendarObject($calendarId, $objectUri) {
833
-
834
-		$query = $this->db->getQueryBuilder();
835
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
836
-				->from('calendarobjects')
837
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
838
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
839
-		$stmt = $query->execute();
840
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
841
-
842
-		if(!$row) return null;
843
-
844
-		return [
845
-				'id'            => $row['id'],
846
-				'uri'           => $row['uri'],
847
-				'lastmodified'  => $row['lastmodified'],
848
-				'etag'          => '"' . $row['etag'] . '"',
849
-				'calendarid'    => $row['calendarid'],
850
-				'size'          => (int)$row['size'],
851
-				'calendardata'  => $this->readBlob($row['calendardata']),
852
-				'component'     => strtolower($row['componenttype']),
853
-				'classification'=> (int)$row['classification']
854
-		];
855
-	}
856
-
857
-	/**
858
-	 * Returns a list of calendar objects.
859
-	 *
860
-	 * This method should work identical to getCalendarObject, but instead
861
-	 * return all the calendar objects in the list as an array.
862
-	 *
863
-	 * If the backend supports this, it may allow for some speed-ups.
864
-	 *
865
-	 * @param mixed $calendarId
866
-	 * @param string[] $uris
867
-	 * @return array
868
-	 */
869
-	function getMultipleCalendarObjects($calendarId, array $uris) {
870
-		if (empty($uris)) {
871
-			return [];
872
-		}
873
-
874
-		$chunks = array_chunk($uris, 100);
875
-		$objects = [];
876
-
877
-		$query = $this->db->getQueryBuilder();
878
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
879
-			->from('calendarobjects')
880
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
881
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
882
-
883
-		foreach ($chunks as $uris) {
884
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
885
-			$result = $query->execute();
886
-
887
-			while ($row = $result->fetch()) {
888
-				$objects[] = [
889
-					'id'           => $row['id'],
890
-					'uri'          => $row['uri'],
891
-					'lastmodified' => $row['lastmodified'],
892
-					'etag'         => '"' . $row['etag'] . '"',
893
-					'calendarid'   => $row['calendarid'],
894
-					'size'         => (int)$row['size'],
895
-					'calendardata' => $this->readBlob($row['calendardata']),
896
-					'component'    => strtolower($row['componenttype']),
897
-					'classification' => (int)$row['classification']
898
-				];
899
-			}
900
-			$result->closeCursor();
901
-		}
902
-		return $objects;
903
-	}
904
-
905
-	/**
906
-	 * Creates a new calendar object.
907
-	 *
908
-	 * The object uri is only the basename, or filename and not a full path.
909
-	 *
910
-	 * It is possible return an etag from this function, which will be used in
911
-	 * the response to this PUT request. Note that the ETag must be surrounded
912
-	 * by double-quotes.
913
-	 *
914
-	 * However, you should only really return this ETag if you don't mangle the
915
-	 * calendar-data. If the result of a subsequent GET to this object is not
916
-	 * the exact same as this request body, you should omit the ETag.
917
-	 *
918
-	 * @param mixed $calendarId
919
-	 * @param string $objectUri
920
-	 * @param string $calendarData
921
-	 * @return string
922
-	 */
923
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
924
-		$extraData = $this->getDenormalizedData($calendarData);
925
-
926
-		$query = $this->db->getQueryBuilder();
927
-		$query->insert('calendarobjects')
928
-			->values([
929
-				'calendarid' => $query->createNamedParameter($calendarId),
930
-				'uri' => $query->createNamedParameter($objectUri),
931
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
932
-				'lastmodified' => $query->createNamedParameter(time()),
933
-				'etag' => $query->createNamedParameter($extraData['etag']),
934
-				'size' => $query->createNamedParameter($extraData['size']),
935
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
936
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
937
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
938
-				'classification' => $query->createNamedParameter($extraData['classification']),
939
-				'uid' => $query->createNamedParameter($extraData['uid']),
940
-			])
941
-			->execute();
942
-
943
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
944
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
945
-			[
946
-				'calendarId' => $calendarId,
947
-				'calendarData' => $this->getCalendarById($calendarId),
948
-				'shares' => $this->getShares($calendarId),
949
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
950
-			]
951
-		));
952
-		$this->addChange($calendarId, $objectUri, 1);
953
-
954
-		return '"' . $extraData['etag'] . '"';
955
-	}
956
-
957
-	/**
958
-	 * Updates an existing calendarobject, based on it's uri.
959
-	 *
960
-	 * The object uri is only the basename, or filename and not a full path.
961
-	 *
962
-	 * It is possible return an etag from this function, which will be used in
963
-	 * the response to this PUT request. Note that the ETag must be surrounded
964
-	 * by double-quotes.
965
-	 *
966
-	 * However, you should only really return this ETag if you don't mangle the
967
-	 * calendar-data. If the result of a subsequent GET to this object is not
968
-	 * the exact same as this request body, you should omit the ETag.
969
-	 *
970
-	 * @param mixed $calendarId
971
-	 * @param string $objectUri
972
-	 * @param string $calendarData
973
-	 * @return string
974
-	 */
975
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
976
-		$extraData = $this->getDenormalizedData($calendarData);
977
-
978
-		$query = $this->db->getQueryBuilder();
979
-		$query->update('calendarobjects')
980
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
981
-				->set('lastmodified', $query->createNamedParameter(time()))
982
-				->set('etag', $query->createNamedParameter($extraData['etag']))
983
-				->set('size', $query->createNamedParameter($extraData['size']))
984
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
985
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
986
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
987
-				->set('classification', $query->createNamedParameter($extraData['classification']))
988
-				->set('uid', $query->createNamedParameter($extraData['uid']))
989
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
990
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
991
-			->execute();
992
-
993
-		$data = $this->getCalendarObject($calendarId, $objectUri);
994
-		if (is_array($data)) {
995
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
996
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
997
-				[
998
-					'calendarId' => $calendarId,
999
-					'calendarData' => $this->getCalendarById($calendarId),
1000
-					'shares' => $this->getShares($calendarId),
1001
-					'objectData' => $data,
1002
-				]
1003
-			));
1004
-		}
1005
-		$this->addChange($calendarId, $objectUri, 2);
1006
-
1007
-		return '"' . $extraData['etag'] . '"';
1008
-	}
1009
-
1010
-	/**
1011
-	 * @param int $calendarObjectId
1012
-	 * @param int $classification
1013
-	 */
1014
-	public function setClassification($calendarObjectId, $classification) {
1015
-		if (!in_array($classification, [
1016
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1017
-		])) {
1018
-			throw new \InvalidArgumentException();
1019
-		}
1020
-		$query = $this->db->getQueryBuilder();
1021
-		$query->update('calendarobjects')
1022
-			->set('classification', $query->createNamedParameter($classification))
1023
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1024
-			->execute();
1025
-	}
1026
-
1027
-	/**
1028
-	 * Deletes an existing calendar object.
1029
-	 *
1030
-	 * The object uri is only the basename, or filename and not a full path.
1031
-	 *
1032
-	 * @param mixed $calendarId
1033
-	 * @param string $objectUri
1034
-	 * @return void
1035
-	 */
1036
-	function deleteCalendarObject($calendarId, $objectUri) {
1037
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1038
-		if (is_array($data)) {
1039
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1040
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1041
-				[
1042
-					'calendarId' => $calendarId,
1043
-					'calendarData' => $this->getCalendarById($calendarId),
1044
-					'shares' => $this->getShares($calendarId),
1045
-					'objectData' => $data,
1046
-				]
1047
-			));
1048
-		}
1049
-
1050
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1051
-		$stmt->execute([$calendarId, $objectUri]);
1052
-
1053
-		$this->addChange($calendarId, $objectUri, 3);
1054
-	}
1055
-
1056
-	/**
1057
-	 * Performs a calendar-query on the contents of this calendar.
1058
-	 *
1059
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1060
-	 * calendar-query it is possible for a client to request a specific set of
1061
-	 * object, based on contents of iCalendar properties, date-ranges and
1062
-	 * iCalendar component types (VTODO, VEVENT).
1063
-	 *
1064
-	 * This method should just return a list of (relative) urls that match this
1065
-	 * query.
1066
-	 *
1067
-	 * The list of filters are specified as an array. The exact array is
1068
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1069
-	 *
1070
-	 * Note that it is extremely likely that getCalendarObject for every path
1071
-	 * returned from this method will be called almost immediately after. You
1072
-	 * may want to anticipate this to speed up these requests.
1073
-	 *
1074
-	 * This method provides a default implementation, which parses *all* the
1075
-	 * iCalendar objects in the specified calendar.
1076
-	 *
1077
-	 * This default may well be good enough for personal use, and calendars
1078
-	 * that aren't very large. But if you anticipate high usage, big calendars
1079
-	 * or high loads, you are strongly advised to optimize certain paths.
1080
-	 *
1081
-	 * The best way to do so is override this method and to optimize
1082
-	 * specifically for 'common filters'.
1083
-	 *
1084
-	 * Requests that are extremely common are:
1085
-	 *   * requests for just VEVENTS
1086
-	 *   * requests for just VTODO
1087
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1088
-	 *
1089
-	 * ..and combinations of these requests. It may not be worth it to try to
1090
-	 * handle every possible situation and just rely on the (relatively
1091
-	 * easy to use) CalendarQueryValidator to handle the rest.
1092
-	 *
1093
-	 * Note that especially time-range-filters may be difficult to parse. A
1094
-	 * time-range filter specified on a VEVENT must for instance also handle
1095
-	 * recurrence rules correctly.
1096
-	 * A good example of how to interprete all these filters can also simply
1097
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1098
-	 * as possible, so it gives you a good idea on what type of stuff you need
1099
-	 * to think of.
1100
-	 *
1101
-	 * @param mixed $calendarId
1102
-	 * @param array $filters
1103
-	 * @return array
1104
-	 */
1105
-	function calendarQuery($calendarId, array $filters) {
1106
-		$componentType = null;
1107
-		$requirePostFilter = true;
1108
-		$timeRange = null;
1109
-
1110
-		// if no filters were specified, we don't need to filter after a query
1111
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1112
-			$requirePostFilter = false;
1113
-		}
1114
-
1115
-		// Figuring out if there's a component filter
1116
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1117
-			$componentType = $filters['comp-filters'][0]['name'];
1118
-
1119
-			// Checking if we need post-filters
1120
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1121
-				$requirePostFilter = false;
1122
-			}
1123
-			// There was a time-range filter
1124
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1125
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1126
-
1127
-				// If start time OR the end time is not specified, we can do a
1128
-				// 100% accurate mysql query.
1129
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1130
-					$requirePostFilter = false;
1131
-				}
1132
-			}
1133
-
1134
-		}
1135
-		$columns = ['uri'];
1136
-		if ($requirePostFilter) {
1137
-			$columns = ['uri', 'calendardata'];
1138
-		}
1139
-		$query = $this->db->getQueryBuilder();
1140
-		$query->select($columns)
1141
-			->from('calendarobjects')
1142
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1143
-
1144
-		if ($componentType) {
1145
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1146
-		}
1147
-
1148
-		if ($timeRange && $timeRange['start']) {
1149
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1150
-		}
1151
-		if ($timeRange && $timeRange['end']) {
1152
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1153
-		}
1154
-
1155
-		$stmt = $query->execute();
1156
-
1157
-		$result = [];
1158
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1159
-			if ($requirePostFilter) {
1160
-				if (!$this->validateFilterForObject($row, $filters)) {
1161
-					continue;
1162
-				}
1163
-			}
1164
-			$result[] = $row['uri'];
1165
-		}
1166
-
1167
-		return $result;
1168
-	}
1169
-
1170
-	/**
1171
-	 * Searches through all of a users calendars and calendar objects to find
1172
-	 * an object with a specific UID.
1173
-	 *
1174
-	 * This method should return the path to this object, relative to the
1175
-	 * calendar home, so this path usually only contains two parts:
1176
-	 *
1177
-	 * calendarpath/objectpath.ics
1178
-	 *
1179
-	 * If the uid is not found, return null.
1180
-	 *
1181
-	 * This method should only consider * objects that the principal owns, so
1182
-	 * any calendars owned by other principals that also appear in this
1183
-	 * collection should be ignored.
1184
-	 *
1185
-	 * @param string $principalUri
1186
-	 * @param string $uid
1187
-	 * @return string|null
1188
-	 */
1189
-	function getCalendarObjectByUID($principalUri, $uid) {
1190
-
1191
-		$query = $this->db->getQueryBuilder();
1192
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1193
-			->from('calendarobjects', 'co')
1194
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1195
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1196
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1197
-
1198
-		$stmt = $query->execute();
1199
-
1200
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1201
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1202
-		}
1203
-
1204
-		return null;
1205
-	}
1206
-
1207
-	/**
1208
-	 * The getChanges method returns all the changes that have happened, since
1209
-	 * the specified syncToken in the specified calendar.
1210
-	 *
1211
-	 * This function should return an array, such as the following:
1212
-	 *
1213
-	 * [
1214
-	 *   'syncToken' => 'The current synctoken',
1215
-	 *   'added'   => [
1216
-	 *      'new.txt',
1217
-	 *   ],
1218
-	 *   'modified'   => [
1219
-	 *      'modified.txt',
1220
-	 *   ],
1221
-	 *   'deleted' => [
1222
-	 *      'foo.php.bak',
1223
-	 *      'old.txt'
1224
-	 *   ]
1225
-	 * );
1226
-	 *
1227
-	 * The returned syncToken property should reflect the *current* syncToken
1228
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1229
-	 * property This is * needed here too, to ensure the operation is atomic.
1230
-	 *
1231
-	 * If the $syncToken argument is specified as null, this is an initial
1232
-	 * sync, and all members should be reported.
1233
-	 *
1234
-	 * The modified property is an array of nodenames that have changed since
1235
-	 * the last token.
1236
-	 *
1237
-	 * The deleted property is an array with nodenames, that have been deleted
1238
-	 * from collection.
1239
-	 *
1240
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1241
-	 * 1, you only have to report changes that happened only directly in
1242
-	 * immediate descendants. If it's 2, it should also include changes from
1243
-	 * the nodes below the child collections. (grandchildren)
1244
-	 *
1245
-	 * The $limit argument allows a client to specify how many results should
1246
-	 * be returned at most. If the limit is not specified, it should be treated
1247
-	 * as infinite.
1248
-	 *
1249
-	 * If the limit (infinite or not) is higher than you're willing to return,
1250
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1251
-	 *
1252
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1253
-	 * return null.
1254
-	 *
1255
-	 * The limit is 'suggestive'. You are free to ignore it.
1256
-	 *
1257
-	 * @param string $calendarId
1258
-	 * @param string $syncToken
1259
-	 * @param int $syncLevel
1260
-	 * @param int $limit
1261
-	 * @return array
1262
-	 */
1263
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1264
-		// Current synctoken
1265
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1266
-		$stmt->execute([ $calendarId ]);
1267
-		$currentToken = $stmt->fetchColumn(0);
1268
-
1269
-		if (is_null($currentToken)) {
1270
-			return null;
1271
-		}
1272
-
1273
-		$result = [
1274
-			'syncToken' => $currentToken,
1275
-			'added'     => [],
1276
-			'modified'  => [],
1277
-			'deleted'   => [],
1278
-		];
1279
-
1280
-		if ($syncToken) {
1281
-
1282
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1283
-			if ($limit>0) {
1284
-				$query.= " `LIMIT` " . (int)$limit;
1285
-			}
1286
-
1287
-			// Fetching all changes
1288
-			$stmt = $this->db->prepare($query);
1289
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1290
-
1291
-			$changes = [];
1292
-
1293
-			// This loop ensures that any duplicates are overwritten, only the
1294
-			// last change on a node is relevant.
1295
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1296
-
1297
-				$changes[$row['uri']] = $row['operation'];
1298
-
1299
-			}
1300
-
1301
-			foreach($changes as $uri => $operation) {
1302
-
1303
-				switch($operation) {
1304
-					case 1 :
1305
-						$result['added'][] = $uri;
1306
-						break;
1307
-					case 2 :
1308
-						$result['modified'][] = $uri;
1309
-						break;
1310
-					case 3 :
1311
-						$result['deleted'][] = $uri;
1312
-						break;
1313
-				}
1314
-
1315
-			}
1316
-		} else {
1317
-			// No synctoken supplied, this is the initial sync.
1318
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1319
-			$stmt = $this->db->prepare($query);
1320
-			$stmt->execute([$calendarId]);
1321
-
1322
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1323
-		}
1324
-		return $result;
1325
-
1326
-	}
1327
-
1328
-	/**
1329
-	 * Returns a list of subscriptions for a principal.
1330
-	 *
1331
-	 * Every subscription is an array with the following keys:
1332
-	 *  * id, a unique id that will be used by other functions to modify the
1333
-	 *    subscription. This can be the same as the uri or a database key.
1334
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1335
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1336
-	 *    principalUri passed to this method.
1337
-	 *
1338
-	 * Furthermore, all the subscription info must be returned too:
1339
-	 *
1340
-	 * 1. {DAV:}displayname
1341
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1342
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1343
-	 *    should not be stripped).
1344
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1345
-	 *    should not be stripped).
1346
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1347
-	 *    attachments should not be stripped).
1348
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1349
-	 *     Sabre\DAV\Property\Href).
1350
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1351
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1352
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1353
-	 *    (should just be an instance of
1354
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1355
-	 *    default components).
1356
-	 *
1357
-	 * @param string $principalUri
1358
-	 * @return array
1359
-	 */
1360
-	function getSubscriptionsForUser($principalUri) {
1361
-		$fields = array_values($this->subscriptionPropertyMap);
1362
-		$fields[] = 'id';
1363
-		$fields[] = 'uri';
1364
-		$fields[] = 'source';
1365
-		$fields[] = 'principaluri';
1366
-		$fields[] = 'lastmodified';
1367
-
1368
-		$query = $this->db->getQueryBuilder();
1369
-		$query->select($fields)
1370
-			->from('calendarsubscriptions')
1371
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1372
-			->orderBy('calendarorder', 'asc');
1373
-		$stmt =$query->execute();
1374
-
1375
-		$subscriptions = [];
1376
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1377
-
1378
-			$subscription = [
1379
-				'id'           => $row['id'],
1380
-				'uri'          => $row['uri'],
1381
-				'principaluri' => $row['principaluri'],
1382
-				'source'       => $row['source'],
1383
-				'lastmodified' => $row['lastmodified'],
1384
-
1385
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1386
-			];
1387
-
1388
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1389
-				if (!is_null($row[$dbName])) {
1390
-					$subscription[$xmlName] = $row[$dbName];
1391
-				}
1392
-			}
1393
-
1394
-			$subscriptions[] = $subscription;
1395
-
1396
-		}
1397
-
1398
-		return $subscriptions;
1399
-	}
1400
-
1401
-	/**
1402
-	 * Creates a new subscription for a principal.
1403
-	 *
1404
-	 * If the creation was a success, an id must be returned that can be used to reference
1405
-	 * this subscription in other methods, such as updateSubscription.
1406
-	 *
1407
-	 * @param string $principalUri
1408
-	 * @param string $uri
1409
-	 * @param array $properties
1410
-	 * @return mixed
1411
-	 */
1412
-	function createSubscription($principalUri, $uri, array $properties) {
1413
-
1414
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1415
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1416
-		}
1417
-
1418
-		$values = [
1419
-			'principaluri' => $principalUri,
1420
-			'uri'          => $uri,
1421
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1422
-			'lastmodified' => time(),
1423
-		];
1424
-
1425
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1426
-
1427
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1428
-			if (array_key_exists($xmlName, $properties)) {
1429
-					$values[$dbName] = $properties[$xmlName];
1430
-					if (in_array($dbName, $propertiesBoolean)) {
1431
-						$values[$dbName] = true;
1432
-				}
1433
-			}
1434
-		}
1435
-
1436
-		$valuesToInsert = array();
1437
-
1438
-		$query = $this->db->getQueryBuilder();
1439
-
1440
-		foreach (array_keys($values) as $name) {
1441
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1442
-		}
1443
-
1444
-		$query->insert('calendarsubscriptions')
1445
-			->values($valuesToInsert)
1446
-			->execute();
1447
-
1448
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1449
-	}
1450
-
1451
-	/**
1452
-	 * Updates a subscription
1453
-	 *
1454
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1455
-	 * To do the actual updates, you must tell this object which properties
1456
-	 * you're going to process with the handle() method.
1457
-	 *
1458
-	 * Calling the handle method is like telling the PropPatch object "I
1459
-	 * promise I can handle updating this property".
1460
-	 *
1461
-	 * Read the PropPatch documentation for more info and examples.
1462
-	 *
1463
-	 * @param mixed $subscriptionId
1464
-	 * @param PropPatch $propPatch
1465
-	 * @return void
1466
-	 */
1467
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1468
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1469
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1470
-
1471
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1472
-
1473
-			$newValues = [];
1474
-
1475
-			foreach($mutations as $propertyName=>$propertyValue) {
1476
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1477
-					$newValues['source'] = $propertyValue->getHref();
1478
-				} else {
1479
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1480
-					$newValues[$fieldName] = $propertyValue;
1481
-				}
1482
-			}
1483
-
1484
-			$query = $this->db->getQueryBuilder();
1485
-			$query->update('calendarsubscriptions')
1486
-				->set('lastmodified', $query->createNamedParameter(time()));
1487
-			foreach($newValues as $fieldName=>$value) {
1488
-				$query->set($fieldName, $query->createNamedParameter($value));
1489
-			}
1490
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1491
-				->execute();
1492
-
1493
-			return true;
1494
-
1495
-		});
1496
-	}
1497
-
1498
-	/**
1499
-	 * Deletes a subscription.
1500
-	 *
1501
-	 * @param mixed $subscriptionId
1502
-	 * @return void
1503
-	 */
1504
-	function deleteSubscription($subscriptionId) {
1505
-		$query = $this->db->getQueryBuilder();
1506
-		$query->delete('calendarsubscriptions')
1507
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1508
-			->execute();
1509
-	}
1510
-
1511
-	/**
1512
-	 * Returns a single scheduling object for the inbox collection.
1513
-	 *
1514
-	 * The returned array should contain the following elements:
1515
-	 *   * uri - A unique basename for the object. This will be used to
1516
-	 *           construct a full uri.
1517
-	 *   * calendardata - The iCalendar object
1518
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1519
-	 *                    timestamp, or a PHP DateTime object.
1520
-	 *   * etag - A unique token that must change if the object changed.
1521
-	 *   * size - The size of the object, in bytes.
1522
-	 *
1523
-	 * @param string $principalUri
1524
-	 * @param string $objectUri
1525
-	 * @return array
1526
-	 */
1527
-	function getSchedulingObject($principalUri, $objectUri) {
1528
-		$query = $this->db->getQueryBuilder();
1529
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1530
-			->from('schedulingobjects')
1531
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1532
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1533
-			->execute();
1534
-
1535
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1536
-
1537
-		if(!$row) {
1538
-			return null;
1539
-		}
1540
-
1541
-		return [
1542
-				'uri'          => $row['uri'],
1543
-				'calendardata' => $row['calendardata'],
1544
-				'lastmodified' => $row['lastmodified'],
1545
-				'etag'         => '"' . $row['etag'] . '"',
1546
-				'size'         => (int)$row['size'],
1547
-		];
1548
-	}
1549
-
1550
-	/**
1551
-	 * Returns all scheduling objects for the inbox collection.
1552
-	 *
1553
-	 * These objects should be returned as an array. Every item in the array
1554
-	 * should follow the same structure as returned from getSchedulingObject.
1555
-	 *
1556
-	 * The main difference is that 'calendardata' is optional.
1557
-	 *
1558
-	 * @param string $principalUri
1559
-	 * @return array
1560
-	 */
1561
-	function getSchedulingObjects($principalUri) {
1562
-		$query = $this->db->getQueryBuilder();
1563
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1564
-				->from('schedulingobjects')
1565
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1566
-				->execute();
1567
-
1568
-		$result = [];
1569
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1570
-			$result[] = [
1571
-					'calendardata' => $row['calendardata'],
1572
-					'uri'          => $row['uri'],
1573
-					'lastmodified' => $row['lastmodified'],
1574
-					'etag'         => '"' . $row['etag'] . '"',
1575
-					'size'         => (int)$row['size'],
1576
-			];
1577
-		}
1578
-
1579
-		return $result;
1580
-	}
1581
-
1582
-	/**
1583
-	 * Deletes a scheduling object from the inbox collection.
1584
-	 *
1585
-	 * @param string $principalUri
1586
-	 * @param string $objectUri
1587
-	 * @return void
1588
-	 */
1589
-	function deleteSchedulingObject($principalUri, $objectUri) {
1590
-		$query = $this->db->getQueryBuilder();
1591
-		$query->delete('schedulingobjects')
1592
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1593
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1594
-				->execute();
1595
-	}
1596
-
1597
-	/**
1598
-	 * Creates a new scheduling object. This should land in a users' inbox.
1599
-	 *
1600
-	 * @param string $principalUri
1601
-	 * @param string $objectUri
1602
-	 * @param string $objectData
1603
-	 * @return void
1604
-	 */
1605
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1606
-		$query = $this->db->getQueryBuilder();
1607
-		$query->insert('schedulingobjects')
1608
-			->values([
1609
-				'principaluri' => $query->createNamedParameter($principalUri),
1610
-				'calendardata' => $query->createNamedParameter($objectData),
1611
-				'uri' => $query->createNamedParameter($objectUri),
1612
-				'lastmodified' => $query->createNamedParameter(time()),
1613
-				'etag' => $query->createNamedParameter(md5($objectData)),
1614
-				'size' => $query->createNamedParameter(strlen($objectData))
1615
-			])
1616
-			->execute();
1617
-	}
1618
-
1619
-	/**
1620
-	 * Adds a change record to the calendarchanges table.
1621
-	 *
1622
-	 * @param mixed $calendarId
1623
-	 * @param string $objectUri
1624
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1625
-	 * @return void
1626
-	 */
1627
-	protected function addChange($calendarId, $objectUri, $operation) {
1628
-
1629
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1630
-		$stmt->execute([
1631
-			$objectUri,
1632
-			$calendarId,
1633
-			$operation,
1634
-			$calendarId
1635
-		]);
1636
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1637
-		$stmt->execute([
1638
-			$calendarId
1639
-		]);
1640
-
1641
-	}
1642
-
1643
-	/**
1644
-	 * Parses some information from calendar objects, used for optimized
1645
-	 * calendar-queries.
1646
-	 *
1647
-	 * Returns an array with the following keys:
1648
-	 *   * etag - An md5 checksum of the object without the quotes.
1649
-	 *   * size - Size of the object in bytes
1650
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1651
-	 *   * firstOccurence
1652
-	 *   * lastOccurence
1653
-	 *   * uid - value of the UID property
1654
-	 *
1655
-	 * @param string $calendarData
1656
-	 * @return array
1657
-	 */
1658
-	public function getDenormalizedData($calendarData) {
1659
-
1660
-		$vObject = Reader::read($calendarData);
1661
-		$componentType = null;
1662
-		$component = null;
1663
-		$firstOccurrence = null;
1664
-		$lastOccurrence = null;
1665
-		$uid = null;
1666
-		$classification = self::CLASSIFICATION_PUBLIC;
1667
-		foreach($vObject->getComponents() as $component) {
1668
-			if ($component->name!=='VTIMEZONE') {
1669
-				$componentType = $component->name;
1670
-				$uid = (string)$component->UID;
1671
-				break;
1672
-			}
1673
-		}
1674
-		if (!$componentType) {
1675
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1676
-		}
1677
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1678
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1679
-			// Finding the last occurrence is a bit harder
1680
-			if (!isset($component->RRULE)) {
1681
-				if (isset($component->DTEND)) {
1682
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1683
-				} elseif (isset($component->DURATION)) {
1684
-					$endDate = clone $component->DTSTART->getDateTime();
1685
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1686
-					$lastOccurrence = $endDate->getTimeStamp();
1687
-				} elseif (!$component->DTSTART->hasTime()) {
1688
-					$endDate = clone $component->DTSTART->getDateTime();
1689
-					$endDate->modify('+1 day');
1690
-					$lastOccurrence = $endDate->getTimeStamp();
1691
-				} else {
1692
-					$lastOccurrence = $firstOccurrence;
1693
-				}
1694
-			} else {
1695
-				$it = new EventIterator($vObject, (string)$component->UID);
1696
-				$maxDate = new \DateTime(self::MAX_DATE);
1697
-				if ($it->isInfinite()) {
1698
-					$lastOccurrence = $maxDate->getTimestamp();
1699
-				} else {
1700
-					$end = $it->getDtEnd();
1701
-					while($it->valid() && $end < $maxDate) {
1702
-						$end = $it->getDtEnd();
1703
-						$it->next();
1704
-
1705
-					}
1706
-					$lastOccurrence = $end->getTimestamp();
1707
-				}
1708
-
1709
-			}
1710
-		}
1711
-
1712
-		if ($component->CLASS) {
1713
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1714
-			switch ($component->CLASS->getValue()) {
1715
-				case 'PUBLIC':
1716
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1717
-					break;
1718
-				case 'CONFIDENTIAL':
1719
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1720
-					break;
1721
-			}
1722
-		}
1723
-		return [
1724
-			'etag' => md5($calendarData),
1725
-			'size' => strlen($calendarData),
1726
-			'componentType' => $componentType,
1727
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1728
-			'lastOccurence'  => $lastOccurrence,
1729
-			'uid' => $uid,
1730
-			'classification' => $classification
1731
-		];
1732
-
1733
-	}
1734
-
1735
-	private function readBlob($cardData) {
1736
-		if (is_resource($cardData)) {
1737
-			return stream_get_contents($cardData);
1738
-		}
1739
-
1740
-		return $cardData;
1741
-	}
1742
-
1743
-	/**
1744
-	 * @param IShareable $shareable
1745
-	 * @param array $add
1746
-	 * @param array $remove
1747
-	 */
1748
-	public function updateShares($shareable, $add, $remove) {
1749
-		$calendarId = $shareable->getResourceId();
1750
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1751
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1752
-			[
1753
-				'calendarId' => $calendarId,
1754
-				'calendarData' => $this->getCalendarById($calendarId),
1755
-				'shares' => $this->getShares($calendarId),
1756
-				'add' => $add,
1757
-				'remove' => $remove,
1758
-			]));
1759
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1760
-	}
1761
-
1762
-	/**
1763
-	 * @param int $resourceId
1764
-	 * @return array
1765
-	 */
1766
-	public function getShares($resourceId) {
1767
-		return $this->sharingBackend->getShares($resourceId);
1768
-	}
1769
-
1770
-	/**
1771
-	 * @param boolean $value
1772
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1773
-	 * @return string|null
1774
-	 */
1775
-	public function setPublishStatus($value, $calendar) {
1776
-		$query = $this->db->getQueryBuilder();
1777
-		if ($value) {
1778
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1779
-			$query->insert('dav_shares')
1780
-				->values([
1781
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1782
-					'type' => $query->createNamedParameter('calendar'),
1783
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1784
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1785
-					'publicuri' => $query->createNamedParameter($publicUri)
1786
-				]);
1787
-			$query->execute();
1788
-			return $publicUri;
1789
-		}
1790
-		$query->delete('dav_shares')
1791
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1792
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1793
-		$query->execute();
1794
-		return null;
1795
-	}
1796
-
1797
-	/**
1798
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1799
-	 * @return mixed
1800
-	 */
1801
-	public function getPublishStatus($calendar) {
1802
-		$query = $this->db->getQueryBuilder();
1803
-		$result = $query->select('publicuri')
1804
-			->from('dav_shares')
1805
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1806
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1807
-			->execute();
1808
-
1809
-		$row = $result->fetch();
1810
-		$result->closeCursor();
1811
-		return $row ? reset($row) : false;
1812
-	}
1813
-
1814
-	/**
1815
-	 * @param int $resourceId
1816
-	 * @param array $acl
1817
-	 * @return array
1818
-	 */
1819
-	public function applyShareAcl($resourceId, $acl) {
1820
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1821
-	}
1822
-
1823
-	private function convertPrincipal($principalUri, $toV2) {
1824
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1825
-			list(, $name) = URLUtil::splitPath($principalUri);
1826
-			if ($toV2 === true) {
1827
-				return "principals/users/$name";
1828
-			}
1829
-			return "principals/$name";
1830
-		}
1831
-		return $principalUri;
1832
-	}
1833
-
1834
-	private function addOwnerPrincipal(&$calendarInfo) {
1835
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1836
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1837
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
1838
-			$uri = $calendarInfo[$ownerPrincipalKey];
1839
-		} else {
1840
-			$uri = $calendarInfo['principaluri'];
1841
-		}
1842
-
1843
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1844
-		if (isset($principalInformation['{DAV:}displayname'])) {
1845
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1846
-		}
1847
-	}
392
+    /**
393
+     * @return array
394
+     */
395
+    public function getPublicCalendars() {
396
+        $fields = array_values($this->propertyMap);
397
+        $fields[] = 'a.id';
398
+        $fields[] = 'a.uri';
399
+        $fields[] = 'a.synctoken';
400
+        $fields[] = 'a.components';
401
+        $fields[] = 'a.principaluri';
402
+        $fields[] = 'a.transparent';
403
+        $fields[] = 's.access';
404
+        $fields[] = 's.publicuri';
405
+        $calendars = [];
406
+        $query = $this->db->getQueryBuilder();
407
+        $result = $query->select($fields)
408
+            ->from('dav_shares', 's')
409
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
410
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
411
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
412
+            ->execute();
413
+
414
+        while($row = $result->fetch()) {
415
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
416
+            $row['displayname'] = $row['displayname'] . "($name)";
417
+            $components = [];
418
+            if ($row['components']) {
419
+                $components = explode(',',$row['components']);
420
+            }
421
+            $calendar = [
422
+                'id' => $row['id'],
423
+                'uri' => $row['publicuri'],
424
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
425
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
426
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
427
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
428
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
429
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
430
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
431
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
432
+            ];
433
+
434
+            foreach($this->propertyMap as $xmlName=>$dbName) {
435
+                $calendar[$xmlName] = $row[$dbName];
436
+            }
437
+
438
+            $this->addOwnerPrincipal($calendar);
439
+
440
+            if (!isset($calendars[$calendar['id']])) {
441
+                $calendars[$calendar['id']] = $calendar;
442
+            }
443
+        }
444
+        $result->closeCursor();
445
+
446
+        return array_values($calendars);
447
+    }
448
+
449
+    /**
450
+     * @param string $uri
451
+     * @return array
452
+     * @throws NotFound
453
+     */
454
+    public function getPublicCalendar($uri) {
455
+        $fields = array_values($this->propertyMap);
456
+        $fields[] = 'a.id';
457
+        $fields[] = 'a.uri';
458
+        $fields[] = 'a.synctoken';
459
+        $fields[] = 'a.components';
460
+        $fields[] = 'a.principaluri';
461
+        $fields[] = 'a.transparent';
462
+        $fields[] = 's.access';
463
+        $fields[] = 's.publicuri';
464
+        $query = $this->db->getQueryBuilder();
465
+        $result = $query->select($fields)
466
+            ->from('dav_shares', 's')
467
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
468
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
469
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
470
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
471
+            ->execute();
472
+
473
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
474
+
475
+        $result->closeCursor();
476
+
477
+        if ($row === false) {
478
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
479
+        }
480
+
481
+        list(, $name) = URLUtil::splitPath($row['principaluri']);
482
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
483
+        $components = [];
484
+        if ($row['components']) {
485
+            $components = explode(',',$row['components']);
486
+        }
487
+        $calendar = [
488
+            'id' => $row['id'],
489
+            'uri' => $row['publicuri'],
490
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
491
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
492
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
493
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
495
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
496
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
497
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
498
+        ];
499
+
500
+        foreach($this->propertyMap as $xmlName=>$dbName) {
501
+            $calendar[$xmlName] = $row[$dbName];
502
+        }
503
+
504
+        $this->addOwnerPrincipal($calendar);
505
+
506
+        return $calendar;
507
+
508
+    }
509
+
510
+    /**
511
+     * @param string $principal
512
+     * @param string $uri
513
+     * @return array|null
514
+     */
515
+    public function getCalendarByUri($principal, $uri) {
516
+        $fields = array_values($this->propertyMap);
517
+        $fields[] = 'id';
518
+        $fields[] = 'uri';
519
+        $fields[] = 'synctoken';
520
+        $fields[] = 'components';
521
+        $fields[] = 'principaluri';
522
+        $fields[] = 'transparent';
523
+
524
+        // Making fields a comma-delimited list
525
+        $query = $this->db->getQueryBuilder();
526
+        $query->select($fields)->from('calendars')
527
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
528
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
529
+            ->setMaxResults(1);
530
+        $stmt = $query->execute();
531
+
532
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
533
+        $stmt->closeCursor();
534
+        if ($row === false) {
535
+            return null;
536
+        }
537
+
538
+        $components = [];
539
+        if ($row['components']) {
540
+            $components = explode(',',$row['components']);
541
+        }
542
+
543
+        $calendar = [
544
+            'id' => $row['id'],
545
+            'uri' => $row['uri'],
546
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
547
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
548
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
549
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
550
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
551
+        ];
552
+
553
+        foreach($this->propertyMap as $xmlName=>$dbName) {
554
+            $calendar[$xmlName] = $row[$dbName];
555
+        }
556
+
557
+        $this->addOwnerPrincipal($calendar);
558
+
559
+        return $calendar;
560
+    }
561
+
562
+    public function getCalendarById($calendarId) {
563
+        $fields = array_values($this->propertyMap);
564
+        $fields[] = 'id';
565
+        $fields[] = 'uri';
566
+        $fields[] = 'synctoken';
567
+        $fields[] = 'components';
568
+        $fields[] = 'principaluri';
569
+        $fields[] = 'transparent';
570
+
571
+        // Making fields a comma-delimited list
572
+        $query = $this->db->getQueryBuilder();
573
+        $query->select($fields)->from('calendars')
574
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
575
+            ->setMaxResults(1);
576
+        $stmt = $query->execute();
577
+
578
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
579
+        $stmt->closeCursor();
580
+        if ($row === false) {
581
+            return null;
582
+        }
583
+
584
+        $components = [];
585
+        if ($row['components']) {
586
+            $components = explode(',',$row['components']);
587
+        }
588
+
589
+        $calendar = [
590
+            'id' => $row['id'],
591
+            'uri' => $row['uri'],
592
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
593
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
594
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
595
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
596
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
597
+        ];
598
+
599
+        foreach($this->propertyMap as $xmlName=>$dbName) {
600
+            $calendar[$xmlName] = $row[$dbName];
601
+        }
602
+
603
+        $this->addOwnerPrincipal($calendar);
604
+
605
+        return $calendar;
606
+    }
607
+
608
+    /**
609
+     * Creates a new calendar for a principal.
610
+     *
611
+     * If the creation was a success, an id must be returned that can be used to reference
612
+     * this calendar in other methods, such as updateCalendar.
613
+     *
614
+     * @param string $principalUri
615
+     * @param string $calendarUri
616
+     * @param array $properties
617
+     * @return int
618
+     */
619
+    function createCalendar($principalUri, $calendarUri, array $properties) {
620
+        $values = [
621
+            'principaluri' => $this->convertPrincipal($principalUri, true),
622
+            'uri'          => $calendarUri,
623
+            'synctoken'    => 1,
624
+            'transparent'  => 0,
625
+            'components'   => 'VEVENT,VTODO',
626
+            'displayname'  => $calendarUri
627
+        ];
628
+
629
+        // Default value
630
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
631
+        if (isset($properties[$sccs])) {
632
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
633
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
634
+            }
635
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
636
+        }
637
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
638
+        if (isset($properties[$transp])) {
639
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
640
+        }
641
+
642
+        foreach($this->propertyMap as $xmlName=>$dbName) {
643
+            if (isset($properties[$xmlName])) {
644
+                $values[$dbName] = $properties[$xmlName];
645
+            }
646
+        }
647
+
648
+        $query = $this->db->getQueryBuilder();
649
+        $query->insert('calendars');
650
+        foreach($values as $column => $value) {
651
+            $query->setValue($column, $query->createNamedParameter($value));
652
+        }
653
+        $query->execute();
654
+        $calendarId = $query->getLastInsertId();
655
+
656
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
657
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
658
+            [
659
+                'calendarId' => $calendarId,
660
+                'calendarData' => $this->getCalendarById($calendarId),
661
+        ]));
662
+
663
+        return $calendarId;
664
+    }
665
+
666
+    /**
667
+     * Updates properties for a calendar.
668
+     *
669
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
670
+     * To do the actual updates, you must tell this object which properties
671
+     * you're going to process with the handle() method.
672
+     *
673
+     * Calling the handle method is like telling the PropPatch object "I
674
+     * promise I can handle updating this property".
675
+     *
676
+     * Read the PropPatch documentation for more info and examples.
677
+     *
678
+     * @param PropPatch $propPatch
679
+     * @return void
680
+     */
681
+    function updateCalendar($calendarId, PropPatch $propPatch) {
682
+        $supportedProperties = array_keys($this->propertyMap);
683
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
684
+
685
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
686
+            $newValues = [];
687
+            foreach ($mutations as $propertyName => $propertyValue) {
688
+
689
+                switch ($propertyName) {
690
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
691
+                        $fieldName = 'transparent';
692
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
693
+                        break;
694
+                    default :
695
+                        $fieldName = $this->propertyMap[$propertyName];
696
+                        $newValues[$fieldName] = $propertyValue;
697
+                        break;
698
+                }
699
+
700
+            }
701
+            $query = $this->db->getQueryBuilder();
702
+            $query->update('calendars');
703
+            foreach ($newValues as $fieldName => $value) {
704
+                $query->set($fieldName, $query->createNamedParameter($value));
705
+            }
706
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
707
+            $query->execute();
708
+
709
+            $this->addChange($calendarId, "", 2);
710
+
711
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
712
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
713
+                [
714
+                    'calendarId' => $calendarId,
715
+                    'calendarData' => $this->getCalendarById($calendarId),
716
+                    'shares' => $this->getShares($calendarId),
717
+                    'propertyMutations' => $mutations,
718
+            ]));
719
+
720
+            return true;
721
+        });
722
+    }
723
+
724
+    /**
725
+     * Delete a calendar and all it's objects
726
+     *
727
+     * @param mixed $calendarId
728
+     * @return void
729
+     */
730
+    function deleteCalendar($calendarId) {
731
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
732
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
733
+            [
734
+                'calendarId' => $calendarId,
735
+                'calendarData' => $this->getCalendarById($calendarId),
736
+                'shares' => $this->getShares($calendarId),
737
+        ]));
738
+
739
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
740
+        $stmt->execute([$calendarId]);
741
+
742
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
743
+        $stmt->execute([$calendarId]);
744
+
745
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
746
+        $stmt->execute([$calendarId]);
747
+
748
+        $this->sharingBackend->deleteAllShares($calendarId);
749
+    }
750
+
751
+    /**
752
+     * Delete all of an user's shares
753
+     *
754
+     * @param string $principaluri
755
+     * @return void
756
+     */
757
+    function deleteAllSharesByUser($principaluri) {
758
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
759
+    }
760
+
761
+    /**
762
+     * Returns all calendar objects within a calendar.
763
+     *
764
+     * Every item contains an array with the following keys:
765
+     *   * calendardata - The iCalendar-compatible calendar data
766
+     *   * uri - a unique key which will be used to construct the uri. This can
767
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
768
+     *     good idea. This is only the basename, or filename, not the full
769
+     *     path.
770
+     *   * lastmodified - a timestamp of the last modification time
771
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
772
+     *   '"abcdef"')
773
+     *   * size - The size of the calendar objects, in bytes.
774
+     *   * component - optional, a string containing the type of object, such
775
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
776
+     *     the Content-Type header.
777
+     *
778
+     * Note that the etag is optional, but it's highly encouraged to return for
779
+     * speed reasons.
780
+     *
781
+     * The calendardata is also optional. If it's not returned
782
+     * 'getCalendarObject' will be called later, which *is* expected to return
783
+     * calendardata.
784
+     *
785
+     * If neither etag or size are specified, the calendardata will be
786
+     * used/fetched to determine these numbers. If both are specified the
787
+     * amount of times this is needed is reduced by a great degree.
788
+     *
789
+     * @param mixed $calendarId
790
+     * @return array
791
+     */
792
+    function getCalendarObjects($calendarId) {
793
+        $query = $this->db->getQueryBuilder();
794
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
795
+            ->from('calendarobjects')
796
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
797
+        $stmt = $query->execute();
798
+
799
+        $result = [];
800
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
801
+            $result[] = [
802
+                    'id'           => $row['id'],
803
+                    'uri'          => $row['uri'],
804
+                    'lastmodified' => $row['lastmodified'],
805
+                    'etag'         => '"' . $row['etag'] . '"',
806
+                    'calendarid'   => $row['calendarid'],
807
+                    'size'         => (int)$row['size'],
808
+                    'component'    => strtolower($row['componenttype']),
809
+                    'classification'=> (int)$row['classification']
810
+            ];
811
+        }
812
+
813
+        return $result;
814
+    }
815
+
816
+    /**
817
+     * Returns information from a single calendar object, based on it's object
818
+     * uri.
819
+     *
820
+     * The object uri is only the basename, or filename and not a full path.
821
+     *
822
+     * The returned array must have the same keys as getCalendarObjects. The
823
+     * 'calendardata' object is required here though, while it's not required
824
+     * for getCalendarObjects.
825
+     *
826
+     * This method must return null if the object did not exist.
827
+     *
828
+     * @param mixed $calendarId
829
+     * @param string $objectUri
830
+     * @return array|null
831
+     */
832
+    function getCalendarObject($calendarId, $objectUri) {
833
+
834
+        $query = $this->db->getQueryBuilder();
835
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
836
+                ->from('calendarobjects')
837
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
838
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
839
+        $stmt = $query->execute();
840
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
841
+
842
+        if(!$row) return null;
843
+
844
+        return [
845
+                'id'            => $row['id'],
846
+                'uri'           => $row['uri'],
847
+                'lastmodified'  => $row['lastmodified'],
848
+                'etag'          => '"' . $row['etag'] . '"',
849
+                'calendarid'    => $row['calendarid'],
850
+                'size'          => (int)$row['size'],
851
+                'calendardata'  => $this->readBlob($row['calendardata']),
852
+                'component'     => strtolower($row['componenttype']),
853
+                'classification'=> (int)$row['classification']
854
+        ];
855
+    }
856
+
857
+    /**
858
+     * Returns a list of calendar objects.
859
+     *
860
+     * This method should work identical to getCalendarObject, but instead
861
+     * return all the calendar objects in the list as an array.
862
+     *
863
+     * If the backend supports this, it may allow for some speed-ups.
864
+     *
865
+     * @param mixed $calendarId
866
+     * @param string[] $uris
867
+     * @return array
868
+     */
869
+    function getMultipleCalendarObjects($calendarId, array $uris) {
870
+        if (empty($uris)) {
871
+            return [];
872
+        }
873
+
874
+        $chunks = array_chunk($uris, 100);
875
+        $objects = [];
876
+
877
+        $query = $this->db->getQueryBuilder();
878
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
879
+            ->from('calendarobjects')
880
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
881
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
882
+
883
+        foreach ($chunks as $uris) {
884
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
885
+            $result = $query->execute();
886
+
887
+            while ($row = $result->fetch()) {
888
+                $objects[] = [
889
+                    'id'           => $row['id'],
890
+                    'uri'          => $row['uri'],
891
+                    'lastmodified' => $row['lastmodified'],
892
+                    'etag'         => '"' . $row['etag'] . '"',
893
+                    'calendarid'   => $row['calendarid'],
894
+                    'size'         => (int)$row['size'],
895
+                    'calendardata' => $this->readBlob($row['calendardata']),
896
+                    'component'    => strtolower($row['componenttype']),
897
+                    'classification' => (int)$row['classification']
898
+                ];
899
+            }
900
+            $result->closeCursor();
901
+        }
902
+        return $objects;
903
+    }
904
+
905
+    /**
906
+     * Creates a new calendar object.
907
+     *
908
+     * The object uri is only the basename, or filename and not a full path.
909
+     *
910
+     * It is possible return an etag from this function, which will be used in
911
+     * the response to this PUT request. Note that the ETag must be surrounded
912
+     * by double-quotes.
913
+     *
914
+     * However, you should only really return this ETag if you don't mangle the
915
+     * calendar-data. If the result of a subsequent GET to this object is not
916
+     * the exact same as this request body, you should omit the ETag.
917
+     *
918
+     * @param mixed $calendarId
919
+     * @param string $objectUri
920
+     * @param string $calendarData
921
+     * @return string
922
+     */
923
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
924
+        $extraData = $this->getDenormalizedData($calendarData);
925
+
926
+        $query = $this->db->getQueryBuilder();
927
+        $query->insert('calendarobjects')
928
+            ->values([
929
+                'calendarid' => $query->createNamedParameter($calendarId),
930
+                'uri' => $query->createNamedParameter($objectUri),
931
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
932
+                'lastmodified' => $query->createNamedParameter(time()),
933
+                'etag' => $query->createNamedParameter($extraData['etag']),
934
+                'size' => $query->createNamedParameter($extraData['size']),
935
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
936
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
937
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
938
+                'classification' => $query->createNamedParameter($extraData['classification']),
939
+                'uid' => $query->createNamedParameter($extraData['uid']),
940
+            ])
941
+            ->execute();
942
+
943
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
944
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
945
+            [
946
+                'calendarId' => $calendarId,
947
+                'calendarData' => $this->getCalendarById($calendarId),
948
+                'shares' => $this->getShares($calendarId),
949
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
950
+            ]
951
+        ));
952
+        $this->addChange($calendarId, $objectUri, 1);
953
+
954
+        return '"' . $extraData['etag'] . '"';
955
+    }
956
+
957
+    /**
958
+     * Updates an existing calendarobject, based on it's uri.
959
+     *
960
+     * The object uri is only the basename, or filename and not a full path.
961
+     *
962
+     * It is possible return an etag from this function, which will be used in
963
+     * the response to this PUT request. Note that the ETag must be surrounded
964
+     * by double-quotes.
965
+     *
966
+     * However, you should only really return this ETag if you don't mangle the
967
+     * calendar-data. If the result of a subsequent GET to this object is not
968
+     * the exact same as this request body, you should omit the ETag.
969
+     *
970
+     * @param mixed $calendarId
971
+     * @param string $objectUri
972
+     * @param string $calendarData
973
+     * @return string
974
+     */
975
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
976
+        $extraData = $this->getDenormalizedData($calendarData);
977
+
978
+        $query = $this->db->getQueryBuilder();
979
+        $query->update('calendarobjects')
980
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
981
+                ->set('lastmodified', $query->createNamedParameter(time()))
982
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
983
+                ->set('size', $query->createNamedParameter($extraData['size']))
984
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
985
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
986
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
987
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
988
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
989
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
990
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
991
+            ->execute();
992
+
993
+        $data = $this->getCalendarObject($calendarId, $objectUri);
994
+        if (is_array($data)) {
995
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
996
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
997
+                [
998
+                    'calendarId' => $calendarId,
999
+                    'calendarData' => $this->getCalendarById($calendarId),
1000
+                    'shares' => $this->getShares($calendarId),
1001
+                    'objectData' => $data,
1002
+                ]
1003
+            ));
1004
+        }
1005
+        $this->addChange($calendarId, $objectUri, 2);
1006
+
1007
+        return '"' . $extraData['etag'] . '"';
1008
+    }
1009
+
1010
+    /**
1011
+     * @param int $calendarObjectId
1012
+     * @param int $classification
1013
+     */
1014
+    public function setClassification($calendarObjectId, $classification) {
1015
+        if (!in_array($classification, [
1016
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1017
+        ])) {
1018
+            throw new \InvalidArgumentException();
1019
+        }
1020
+        $query = $this->db->getQueryBuilder();
1021
+        $query->update('calendarobjects')
1022
+            ->set('classification', $query->createNamedParameter($classification))
1023
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1024
+            ->execute();
1025
+    }
1026
+
1027
+    /**
1028
+     * Deletes an existing calendar object.
1029
+     *
1030
+     * The object uri is only the basename, or filename and not a full path.
1031
+     *
1032
+     * @param mixed $calendarId
1033
+     * @param string $objectUri
1034
+     * @return void
1035
+     */
1036
+    function deleteCalendarObject($calendarId, $objectUri) {
1037
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1038
+        if (is_array($data)) {
1039
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1040
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1041
+                [
1042
+                    'calendarId' => $calendarId,
1043
+                    'calendarData' => $this->getCalendarById($calendarId),
1044
+                    'shares' => $this->getShares($calendarId),
1045
+                    'objectData' => $data,
1046
+                ]
1047
+            ));
1048
+        }
1049
+
1050
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1051
+        $stmt->execute([$calendarId, $objectUri]);
1052
+
1053
+        $this->addChange($calendarId, $objectUri, 3);
1054
+    }
1055
+
1056
+    /**
1057
+     * Performs a calendar-query on the contents of this calendar.
1058
+     *
1059
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1060
+     * calendar-query it is possible for a client to request a specific set of
1061
+     * object, based on contents of iCalendar properties, date-ranges and
1062
+     * iCalendar component types (VTODO, VEVENT).
1063
+     *
1064
+     * This method should just return a list of (relative) urls that match this
1065
+     * query.
1066
+     *
1067
+     * The list of filters are specified as an array. The exact array is
1068
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1069
+     *
1070
+     * Note that it is extremely likely that getCalendarObject for every path
1071
+     * returned from this method will be called almost immediately after. You
1072
+     * may want to anticipate this to speed up these requests.
1073
+     *
1074
+     * This method provides a default implementation, which parses *all* the
1075
+     * iCalendar objects in the specified calendar.
1076
+     *
1077
+     * This default may well be good enough for personal use, and calendars
1078
+     * that aren't very large. But if you anticipate high usage, big calendars
1079
+     * or high loads, you are strongly advised to optimize certain paths.
1080
+     *
1081
+     * The best way to do so is override this method and to optimize
1082
+     * specifically for 'common filters'.
1083
+     *
1084
+     * Requests that are extremely common are:
1085
+     *   * requests for just VEVENTS
1086
+     *   * requests for just VTODO
1087
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1088
+     *
1089
+     * ..and combinations of these requests. It may not be worth it to try to
1090
+     * handle every possible situation and just rely on the (relatively
1091
+     * easy to use) CalendarQueryValidator to handle the rest.
1092
+     *
1093
+     * Note that especially time-range-filters may be difficult to parse. A
1094
+     * time-range filter specified on a VEVENT must for instance also handle
1095
+     * recurrence rules correctly.
1096
+     * A good example of how to interprete all these filters can also simply
1097
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1098
+     * as possible, so it gives you a good idea on what type of stuff you need
1099
+     * to think of.
1100
+     *
1101
+     * @param mixed $calendarId
1102
+     * @param array $filters
1103
+     * @return array
1104
+     */
1105
+    function calendarQuery($calendarId, array $filters) {
1106
+        $componentType = null;
1107
+        $requirePostFilter = true;
1108
+        $timeRange = null;
1109
+
1110
+        // if no filters were specified, we don't need to filter after a query
1111
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1112
+            $requirePostFilter = false;
1113
+        }
1114
+
1115
+        // Figuring out if there's a component filter
1116
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1117
+            $componentType = $filters['comp-filters'][0]['name'];
1118
+
1119
+            // Checking if we need post-filters
1120
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1121
+                $requirePostFilter = false;
1122
+            }
1123
+            // There was a time-range filter
1124
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1125
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1126
+
1127
+                // If start time OR the end time is not specified, we can do a
1128
+                // 100% accurate mysql query.
1129
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1130
+                    $requirePostFilter = false;
1131
+                }
1132
+            }
1133
+
1134
+        }
1135
+        $columns = ['uri'];
1136
+        if ($requirePostFilter) {
1137
+            $columns = ['uri', 'calendardata'];
1138
+        }
1139
+        $query = $this->db->getQueryBuilder();
1140
+        $query->select($columns)
1141
+            ->from('calendarobjects')
1142
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1143
+
1144
+        if ($componentType) {
1145
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1146
+        }
1147
+
1148
+        if ($timeRange && $timeRange['start']) {
1149
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1150
+        }
1151
+        if ($timeRange && $timeRange['end']) {
1152
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1153
+        }
1154
+
1155
+        $stmt = $query->execute();
1156
+
1157
+        $result = [];
1158
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1159
+            if ($requirePostFilter) {
1160
+                if (!$this->validateFilterForObject($row, $filters)) {
1161
+                    continue;
1162
+                }
1163
+            }
1164
+            $result[] = $row['uri'];
1165
+        }
1166
+
1167
+        return $result;
1168
+    }
1169
+
1170
+    /**
1171
+     * Searches through all of a users calendars and calendar objects to find
1172
+     * an object with a specific UID.
1173
+     *
1174
+     * This method should return the path to this object, relative to the
1175
+     * calendar home, so this path usually only contains two parts:
1176
+     *
1177
+     * calendarpath/objectpath.ics
1178
+     *
1179
+     * If the uid is not found, return null.
1180
+     *
1181
+     * This method should only consider * objects that the principal owns, so
1182
+     * any calendars owned by other principals that also appear in this
1183
+     * collection should be ignored.
1184
+     *
1185
+     * @param string $principalUri
1186
+     * @param string $uid
1187
+     * @return string|null
1188
+     */
1189
+    function getCalendarObjectByUID($principalUri, $uid) {
1190
+
1191
+        $query = $this->db->getQueryBuilder();
1192
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1193
+            ->from('calendarobjects', 'co')
1194
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1195
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1196
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1197
+
1198
+        $stmt = $query->execute();
1199
+
1200
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1201
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1202
+        }
1203
+
1204
+        return null;
1205
+    }
1206
+
1207
+    /**
1208
+     * The getChanges method returns all the changes that have happened, since
1209
+     * the specified syncToken in the specified calendar.
1210
+     *
1211
+     * This function should return an array, such as the following:
1212
+     *
1213
+     * [
1214
+     *   'syncToken' => 'The current synctoken',
1215
+     *   'added'   => [
1216
+     *      'new.txt',
1217
+     *   ],
1218
+     *   'modified'   => [
1219
+     *      'modified.txt',
1220
+     *   ],
1221
+     *   'deleted' => [
1222
+     *      'foo.php.bak',
1223
+     *      'old.txt'
1224
+     *   ]
1225
+     * );
1226
+     *
1227
+     * The returned syncToken property should reflect the *current* syncToken
1228
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1229
+     * property This is * needed here too, to ensure the operation is atomic.
1230
+     *
1231
+     * If the $syncToken argument is specified as null, this is an initial
1232
+     * sync, and all members should be reported.
1233
+     *
1234
+     * The modified property is an array of nodenames that have changed since
1235
+     * the last token.
1236
+     *
1237
+     * The deleted property is an array with nodenames, that have been deleted
1238
+     * from collection.
1239
+     *
1240
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1241
+     * 1, you only have to report changes that happened only directly in
1242
+     * immediate descendants. If it's 2, it should also include changes from
1243
+     * the nodes below the child collections. (grandchildren)
1244
+     *
1245
+     * The $limit argument allows a client to specify how many results should
1246
+     * be returned at most. If the limit is not specified, it should be treated
1247
+     * as infinite.
1248
+     *
1249
+     * If the limit (infinite or not) is higher than you're willing to return,
1250
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1251
+     *
1252
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1253
+     * return null.
1254
+     *
1255
+     * The limit is 'suggestive'. You are free to ignore it.
1256
+     *
1257
+     * @param string $calendarId
1258
+     * @param string $syncToken
1259
+     * @param int $syncLevel
1260
+     * @param int $limit
1261
+     * @return array
1262
+     */
1263
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1264
+        // Current synctoken
1265
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1266
+        $stmt->execute([ $calendarId ]);
1267
+        $currentToken = $stmt->fetchColumn(0);
1268
+
1269
+        if (is_null($currentToken)) {
1270
+            return null;
1271
+        }
1272
+
1273
+        $result = [
1274
+            'syncToken' => $currentToken,
1275
+            'added'     => [],
1276
+            'modified'  => [],
1277
+            'deleted'   => [],
1278
+        ];
1279
+
1280
+        if ($syncToken) {
1281
+
1282
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1283
+            if ($limit>0) {
1284
+                $query.= " `LIMIT` " . (int)$limit;
1285
+            }
1286
+
1287
+            // Fetching all changes
1288
+            $stmt = $this->db->prepare($query);
1289
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1290
+
1291
+            $changes = [];
1292
+
1293
+            // This loop ensures that any duplicates are overwritten, only the
1294
+            // last change on a node is relevant.
1295
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1296
+
1297
+                $changes[$row['uri']] = $row['operation'];
1298
+
1299
+            }
1300
+
1301
+            foreach($changes as $uri => $operation) {
1302
+
1303
+                switch($operation) {
1304
+                    case 1 :
1305
+                        $result['added'][] = $uri;
1306
+                        break;
1307
+                    case 2 :
1308
+                        $result['modified'][] = $uri;
1309
+                        break;
1310
+                    case 3 :
1311
+                        $result['deleted'][] = $uri;
1312
+                        break;
1313
+                }
1314
+
1315
+            }
1316
+        } else {
1317
+            // No synctoken supplied, this is the initial sync.
1318
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1319
+            $stmt = $this->db->prepare($query);
1320
+            $stmt->execute([$calendarId]);
1321
+
1322
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1323
+        }
1324
+        return $result;
1325
+
1326
+    }
1327
+
1328
+    /**
1329
+     * Returns a list of subscriptions for a principal.
1330
+     *
1331
+     * Every subscription is an array with the following keys:
1332
+     *  * id, a unique id that will be used by other functions to modify the
1333
+     *    subscription. This can be the same as the uri or a database key.
1334
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1335
+     *  * principaluri. The owner of the subscription. Almost always the same as
1336
+     *    principalUri passed to this method.
1337
+     *
1338
+     * Furthermore, all the subscription info must be returned too:
1339
+     *
1340
+     * 1. {DAV:}displayname
1341
+     * 2. {http://apple.com/ns/ical/}refreshrate
1342
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1343
+     *    should not be stripped).
1344
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1345
+     *    should not be stripped).
1346
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1347
+     *    attachments should not be stripped).
1348
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1349
+     *     Sabre\DAV\Property\Href).
1350
+     * 7. {http://apple.com/ns/ical/}calendar-color
1351
+     * 8. {http://apple.com/ns/ical/}calendar-order
1352
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1353
+     *    (should just be an instance of
1354
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1355
+     *    default components).
1356
+     *
1357
+     * @param string $principalUri
1358
+     * @return array
1359
+     */
1360
+    function getSubscriptionsForUser($principalUri) {
1361
+        $fields = array_values($this->subscriptionPropertyMap);
1362
+        $fields[] = 'id';
1363
+        $fields[] = 'uri';
1364
+        $fields[] = 'source';
1365
+        $fields[] = 'principaluri';
1366
+        $fields[] = 'lastmodified';
1367
+
1368
+        $query = $this->db->getQueryBuilder();
1369
+        $query->select($fields)
1370
+            ->from('calendarsubscriptions')
1371
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1372
+            ->orderBy('calendarorder', 'asc');
1373
+        $stmt =$query->execute();
1374
+
1375
+        $subscriptions = [];
1376
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1377
+
1378
+            $subscription = [
1379
+                'id'           => $row['id'],
1380
+                'uri'          => $row['uri'],
1381
+                'principaluri' => $row['principaluri'],
1382
+                'source'       => $row['source'],
1383
+                'lastmodified' => $row['lastmodified'],
1384
+
1385
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1386
+            ];
1387
+
1388
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1389
+                if (!is_null($row[$dbName])) {
1390
+                    $subscription[$xmlName] = $row[$dbName];
1391
+                }
1392
+            }
1393
+
1394
+            $subscriptions[] = $subscription;
1395
+
1396
+        }
1397
+
1398
+        return $subscriptions;
1399
+    }
1400
+
1401
+    /**
1402
+     * Creates a new subscription for a principal.
1403
+     *
1404
+     * If the creation was a success, an id must be returned that can be used to reference
1405
+     * this subscription in other methods, such as updateSubscription.
1406
+     *
1407
+     * @param string $principalUri
1408
+     * @param string $uri
1409
+     * @param array $properties
1410
+     * @return mixed
1411
+     */
1412
+    function createSubscription($principalUri, $uri, array $properties) {
1413
+
1414
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1415
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1416
+        }
1417
+
1418
+        $values = [
1419
+            'principaluri' => $principalUri,
1420
+            'uri'          => $uri,
1421
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1422
+            'lastmodified' => time(),
1423
+        ];
1424
+
1425
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1426
+
1427
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1428
+            if (array_key_exists($xmlName, $properties)) {
1429
+                    $values[$dbName] = $properties[$xmlName];
1430
+                    if (in_array($dbName, $propertiesBoolean)) {
1431
+                        $values[$dbName] = true;
1432
+                }
1433
+            }
1434
+        }
1435
+
1436
+        $valuesToInsert = array();
1437
+
1438
+        $query = $this->db->getQueryBuilder();
1439
+
1440
+        foreach (array_keys($values) as $name) {
1441
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1442
+        }
1443
+
1444
+        $query->insert('calendarsubscriptions')
1445
+            ->values($valuesToInsert)
1446
+            ->execute();
1447
+
1448
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1449
+    }
1450
+
1451
+    /**
1452
+     * Updates a subscription
1453
+     *
1454
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1455
+     * To do the actual updates, you must tell this object which properties
1456
+     * you're going to process with the handle() method.
1457
+     *
1458
+     * Calling the handle method is like telling the PropPatch object "I
1459
+     * promise I can handle updating this property".
1460
+     *
1461
+     * Read the PropPatch documentation for more info and examples.
1462
+     *
1463
+     * @param mixed $subscriptionId
1464
+     * @param PropPatch $propPatch
1465
+     * @return void
1466
+     */
1467
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1468
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1469
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1470
+
1471
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1472
+
1473
+            $newValues = [];
1474
+
1475
+            foreach($mutations as $propertyName=>$propertyValue) {
1476
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1477
+                    $newValues['source'] = $propertyValue->getHref();
1478
+                } else {
1479
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1480
+                    $newValues[$fieldName] = $propertyValue;
1481
+                }
1482
+            }
1483
+
1484
+            $query = $this->db->getQueryBuilder();
1485
+            $query->update('calendarsubscriptions')
1486
+                ->set('lastmodified', $query->createNamedParameter(time()));
1487
+            foreach($newValues as $fieldName=>$value) {
1488
+                $query->set($fieldName, $query->createNamedParameter($value));
1489
+            }
1490
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1491
+                ->execute();
1492
+
1493
+            return true;
1494
+
1495
+        });
1496
+    }
1497
+
1498
+    /**
1499
+     * Deletes a subscription.
1500
+     *
1501
+     * @param mixed $subscriptionId
1502
+     * @return void
1503
+     */
1504
+    function deleteSubscription($subscriptionId) {
1505
+        $query = $this->db->getQueryBuilder();
1506
+        $query->delete('calendarsubscriptions')
1507
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1508
+            ->execute();
1509
+    }
1510
+
1511
+    /**
1512
+     * Returns a single scheduling object for the inbox collection.
1513
+     *
1514
+     * The returned array should contain the following elements:
1515
+     *   * uri - A unique basename for the object. This will be used to
1516
+     *           construct a full uri.
1517
+     *   * calendardata - The iCalendar object
1518
+     *   * lastmodified - The last modification date. Can be an int for a unix
1519
+     *                    timestamp, or a PHP DateTime object.
1520
+     *   * etag - A unique token that must change if the object changed.
1521
+     *   * size - The size of the object, in bytes.
1522
+     *
1523
+     * @param string $principalUri
1524
+     * @param string $objectUri
1525
+     * @return array
1526
+     */
1527
+    function getSchedulingObject($principalUri, $objectUri) {
1528
+        $query = $this->db->getQueryBuilder();
1529
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1530
+            ->from('schedulingobjects')
1531
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1532
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1533
+            ->execute();
1534
+
1535
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1536
+
1537
+        if(!$row) {
1538
+            return null;
1539
+        }
1540
+
1541
+        return [
1542
+                'uri'          => $row['uri'],
1543
+                'calendardata' => $row['calendardata'],
1544
+                'lastmodified' => $row['lastmodified'],
1545
+                'etag'         => '"' . $row['etag'] . '"',
1546
+                'size'         => (int)$row['size'],
1547
+        ];
1548
+    }
1549
+
1550
+    /**
1551
+     * Returns all scheduling objects for the inbox collection.
1552
+     *
1553
+     * These objects should be returned as an array. Every item in the array
1554
+     * should follow the same structure as returned from getSchedulingObject.
1555
+     *
1556
+     * The main difference is that 'calendardata' is optional.
1557
+     *
1558
+     * @param string $principalUri
1559
+     * @return array
1560
+     */
1561
+    function getSchedulingObjects($principalUri) {
1562
+        $query = $this->db->getQueryBuilder();
1563
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1564
+                ->from('schedulingobjects')
1565
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1566
+                ->execute();
1567
+
1568
+        $result = [];
1569
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1570
+            $result[] = [
1571
+                    'calendardata' => $row['calendardata'],
1572
+                    'uri'          => $row['uri'],
1573
+                    'lastmodified' => $row['lastmodified'],
1574
+                    'etag'         => '"' . $row['etag'] . '"',
1575
+                    'size'         => (int)$row['size'],
1576
+            ];
1577
+        }
1578
+
1579
+        return $result;
1580
+    }
1581
+
1582
+    /**
1583
+     * Deletes a scheduling object from the inbox collection.
1584
+     *
1585
+     * @param string $principalUri
1586
+     * @param string $objectUri
1587
+     * @return void
1588
+     */
1589
+    function deleteSchedulingObject($principalUri, $objectUri) {
1590
+        $query = $this->db->getQueryBuilder();
1591
+        $query->delete('schedulingobjects')
1592
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1593
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1594
+                ->execute();
1595
+    }
1596
+
1597
+    /**
1598
+     * Creates a new scheduling object. This should land in a users' inbox.
1599
+     *
1600
+     * @param string $principalUri
1601
+     * @param string $objectUri
1602
+     * @param string $objectData
1603
+     * @return void
1604
+     */
1605
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1606
+        $query = $this->db->getQueryBuilder();
1607
+        $query->insert('schedulingobjects')
1608
+            ->values([
1609
+                'principaluri' => $query->createNamedParameter($principalUri),
1610
+                'calendardata' => $query->createNamedParameter($objectData),
1611
+                'uri' => $query->createNamedParameter($objectUri),
1612
+                'lastmodified' => $query->createNamedParameter(time()),
1613
+                'etag' => $query->createNamedParameter(md5($objectData)),
1614
+                'size' => $query->createNamedParameter(strlen($objectData))
1615
+            ])
1616
+            ->execute();
1617
+    }
1618
+
1619
+    /**
1620
+     * Adds a change record to the calendarchanges table.
1621
+     *
1622
+     * @param mixed $calendarId
1623
+     * @param string $objectUri
1624
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1625
+     * @return void
1626
+     */
1627
+    protected function addChange($calendarId, $objectUri, $operation) {
1628
+
1629
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1630
+        $stmt->execute([
1631
+            $objectUri,
1632
+            $calendarId,
1633
+            $operation,
1634
+            $calendarId
1635
+        ]);
1636
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1637
+        $stmt->execute([
1638
+            $calendarId
1639
+        ]);
1640
+
1641
+    }
1642
+
1643
+    /**
1644
+     * Parses some information from calendar objects, used for optimized
1645
+     * calendar-queries.
1646
+     *
1647
+     * Returns an array with the following keys:
1648
+     *   * etag - An md5 checksum of the object without the quotes.
1649
+     *   * size - Size of the object in bytes
1650
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1651
+     *   * firstOccurence
1652
+     *   * lastOccurence
1653
+     *   * uid - value of the UID property
1654
+     *
1655
+     * @param string $calendarData
1656
+     * @return array
1657
+     */
1658
+    public function getDenormalizedData($calendarData) {
1659
+
1660
+        $vObject = Reader::read($calendarData);
1661
+        $componentType = null;
1662
+        $component = null;
1663
+        $firstOccurrence = null;
1664
+        $lastOccurrence = null;
1665
+        $uid = null;
1666
+        $classification = self::CLASSIFICATION_PUBLIC;
1667
+        foreach($vObject->getComponents() as $component) {
1668
+            if ($component->name!=='VTIMEZONE') {
1669
+                $componentType = $component->name;
1670
+                $uid = (string)$component->UID;
1671
+                break;
1672
+            }
1673
+        }
1674
+        if (!$componentType) {
1675
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1676
+        }
1677
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1678
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1679
+            // Finding the last occurrence is a bit harder
1680
+            if (!isset($component->RRULE)) {
1681
+                if (isset($component->DTEND)) {
1682
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1683
+                } elseif (isset($component->DURATION)) {
1684
+                    $endDate = clone $component->DTSTART->getDateTime();
1685
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1686
+                    $lastOccurrence = $endDate->getTimeStamp();
1687
+                } elseif (!$component->DTSTART->hasTime()) {
1688
+                    $endDate = clone $component->DTSTART->getDateTime();
1689
+                    $endDate->modify('+1 day');
1690
+                    $lastOccurrence = $endDate->getTimeStamp();
1691
+                } else {
1692
+                    $lastOccurrence = $firstOccurrence;
1693
+                }
1694
+            } else {
1695
+                $it = new EventIterator($vObject, (string)$component->UID);
1696
+                $maxDate = new \DateTime(self::MAX_DATE);
1697
+                if ($it->isInfinite()) {
1698
+                    $lastOccurrence = $maxDate->getTimestamp();
1699
+                } else {
1700
+                    $end = $it->getDtEnd();
1701
+                    while($it->valid() && $end < $maxDate) {
1702
+                        $end = $it->getDtEnd();
1703
+                        $it->next();
1704
+
1705
+                    }
1706
+                    $lastOccurrence = $end->getTimestamp();
1707
+                }
1708
+
1709
+            }
1710
+        }
1711
+
1712
+        if ($component->CLASS) {
1713
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1714
+            switch ($component->CLASS->getValue()) {
1715
+                case 'PUBLIC':
1716
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1717
+                    break;
1718
+                case 'CONFIDENTIAL':
1719
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1720
+                    break;
1721
+            }
1722
+        }
1723
+        return [
1724
+            'etag' => md5($calendarData),
1725
+            'size' => strlen($calendarData),
1726
+            'componentType' => $componentType,
1727
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1728
+            'lastOccurence'  => $lastOccurrence,
1729
+            'uid' => $uid,
1730
+            'classification' => $classification
1731
+        ];
1732
+
1733
+    }
1734
+
1735
+    private function readBlob($cardData) {
1736
+        if (is_resource($cardData)) {
1737
+            return stream_get_contents($cardData);
1738
+        }
1739
+
1740
+        return $cardData;
1741
+    }
1742
+
1743
+    /**
1744
+     * @param IShareable $shareable
1745
+     * @param array $add
1746
+     * @param array $remove
1747
+     */
1748
+    public function updateShares($shareable, $add, $remove) {
1749
+        $calendarId = $shareable->getResourceId();
1750
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1751
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1752
+            [
1753
+                'calendarId' => $calendarId,
1754
+                'calendarData' => $this->getCalendarById($calendarId),
1755
+                'shares' => $this->getShares($calendarId),
1756
+                'add' => $add,
1757
+                'remove' => $remove,
1758
+            ]));
1759
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1760
+    }
1761
+
1762
+    /**
1763
+     * @param int $resourceId
1764
+     * @return array
1765
+     */
1766
+    public function getShares($resourceId) {
1767
+        return $this->sharingBackend->getShares($resourceId);
1768
+    }
1769
+
1770
+    /**
1771
+     * @param boolean $value
1772
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1773
+     * @return string|null
1774
+     */
1775
+    public function setPublishStatus($value, $calendar) {
1776
+        $query = $this->db->getQueryBuilder();
1777
+        if ($value) {
1778
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1779
+            $query->insert('dav_shares')
1780
+                ->values([
1781
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1782
+                    'type' => $query->createNamedParameter('calendar'),
1783
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1784
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1785
+                    'publicuri' => $query->createNamedParameter($publicUri)
1786
+                ]);
1787
+            $query->execute();
1788
+            return $publicUri;
1789
+        }
1790
+        $query->delete('dav_shares')
1791
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1792
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1793
+        $query->execute();
1794
+        return null;
1795
+    }
1796
+
1797
+    /**
1798
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1799
+     * @return mixed
1800
+     */
1801
+    public function getPublishStatus($calendar) {
1802
+        $query = $this->db->getQueryBuilder();
1803
+        $result = $query->select('publicuri')
1804
+            ->from('dav_shares')
1805
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1806
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1807
+            ->execute();
1808
+
1809
+        $row = $result->fetch();
1810
+        $result->closeCursor();
1811
+        return $row ? reset($row) : false;
1812
+    }
1813
+
1814
+    /**
1815
+     * @param int $resourceId
1816
+     * @param array $acl
1817
+     * @return array
1818
+     */
1819
+    public function applyShareAcl($resourceId, $acl) {
1820
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1821
+    }
1822
+
1823
+    private function convertPrincipal($principalUri, $toV2) {
1824
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1825
+            list(, $name) = URLUtil::splitPath($principalUri);
1826
+            if ($toV2 === true) {
1827
+                return "principals/users/$name";
1828
+            }
1829
+            return "principals/$name";
1830
+        }
1831
+        return $principalUri;
1832
+    }
1833
+
1834
+    private function addOwnerPrincipal(&$calendarInfo) {
1835
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1836
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1837
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
1838
+            $uri = $calendarInfo[$ownerPrincipalKey];
1839
+        } else {
1840
+            $uri = $calendarInfo['principaluri'];
1841
+        }
1842
+
1843
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1844
+        if (isset($principalInformation['{DAV:}displayname'])) {
1845
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1846
+        }
1847
+    }
1848 1848
 }
Please login to merge, or discard this patch.
Spacing   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180 180
 		}
181 181
 
182
-		return (int)$query->execute()->fetchColumn();
182
+		return (int) $query->execute()->fetchColumn();
183 183
 	}
184 184
 
185 185
 	/**
@@ -226,25 +226,25 @@  discard block
 block discarded – undo
226 226
 		$stmt = $query->execute();
227 227
 
228 228
 		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
229
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230 230
 
231 231
 			$components = [];
232 232
 			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
233
+				$components = explode(',', $row['components']);
234 234
 			}
235 235
 
236 236
 			$calendar = [
237 237
 				'id' => $row['id'],
238 238
 				'uri' => $row['uri'],
239 239
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
240
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
241
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
242
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
244
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245 245
 			];
246 246
 
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
247
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
248 248
 				$calendar[$xmlName] = $row[$dbName];
249 249
 			}
250 250
 
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 
260 260
 		// query for shared calendars
261 261
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
262
-		$principals[]= $principalUri;
262
+		$principals[] = $principalUri;
263 263
 
264 264
 		$fields = array_values($this->propertyMap);
265 265
 		$fields[] = 'a.id';
@@ -279,8 +279,8 @@  discard block
 block discarded – undo
279 279
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
280 280
 			->execute();
281 281
 
282
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
283
-		while($row = $result->fetch()) {
282
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
283
+		while ($row = $result->fetch()) {
284 284
 			if ($row['principaluri'] === $principalUri) {
285 285
 				continue;
286 286
 			}
@@ -299,25 +299,25 @@  discard block
 block discarded – undo
299 299
 			}
300 300
 
301 301
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
302
-			$uri = $row['uri'] . '_shared_by_' . $name;
303
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
302
+			$uri = $row['uri'].'_shared_by_'.$name;
303
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
304 304
 			$components = [];
305 305
 			if ($row['components']) {
306
-				$components = explode(',',$row['components']);
306
+				$components = explode(',', $row['components']);
307 307
 			}
308 308
 			$calendar = [
309 309
 				'id' => $row['id'],
310 310
 				'uri' => $uri,
311 311
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
312
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
313
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
314
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
315
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
316
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
312
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
313
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
314
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
315
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
316
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
317 317
 				$readOnlyPropertyName => $readOnly,
318 318
 			];
319 319
 
320
-			foreach($this->propertyMap as $xmlName=>$dbName) {
320
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
321 321
 				$calendar[$xmlName] = $row[$dbName];
322 322
 			}
323 323
 
@@ -346,21 +346,21 @@  discard block
 block discarded – undo
346 346
 			->orderBy('calendarorder', 'ASC');
347 347
 		$stmt = $query->execute();
348 348
 		$calendars = [];
349
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
349
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
350 350
 			$components = [];
351 351
 			if ($row['components']) {
352
-				$components = explode(',',$row['components']);
352
+				$components = explode(',', $row['components']);
353 353
 			}
354 354
 			$calendar = [
355 355
 				'id' => $row['id'],
356 356
 				'uri' => $row['uri'],
357 357
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
358
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
359
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
360
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
361
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
358
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
359
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
360
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
361
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
362 362
 			];
363
-			foreach($this->propertyMap as $xmlName=>$dbName) {
363
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
364 364
 				$calendar[$xmlName] = $row[$dbName];
365 365
 			}
366 366
 
@@ -411,27 +411,27 @@  discard block
 block discarded – undo
411 411
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
412 412
 			->execute();
413 413
 
414
-		while($row = $result->fetch()) {
414
+		while ($row = $result->fetch()) {
415 415
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
416
-			$row['displayname'] = $row['displayname'] . "($name)";
416
+			$row['displayname'] = $row['displayname']."($name)";
417 417
 			$components = [];
418 418
 			if ($row['components']) {
419
-				$components = explode(',',$row['components']);
419
+				$components = explode(',', $row['components']);
420 420
 			}
421 421
 			$calendar = [
422 422
 				'id' => $row['id'],
423 423
 				'uri' => $row['publicuri'],
424 424
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
425
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
426
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
427
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
428
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
429
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
430
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
431
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
425
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
426
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
427
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
428
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
429
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
430
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
431
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
432 432
 			];
433 433
 
434
-			foreach($this->propertyMap as $xmlName=>$dbName) {
434
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
435 435
 				$calendar[$xmlName] = $row[$dbName];
436 436
 			}
437 437
 
@@ -475,29 +475,29 @@  discard block
 block discarded – undo
475 475
 		$result->closeCursor();
476 476
 
477 477
 		if ($row === false) {
478
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
478
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
479 479
 		}
480 480
 
481 481
 		list(, $name) = URLUtil::splitPath($row['principaluri']);
482
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
482
+		$row['displayname'] = $row['displayname'].' '."($name)";
483 483
 		$components = [];
484 484
 		if ($row['components']) {
485
-			$components = explode(',',$row['components']);
485
+			$components = explode(',', $row['components']);
486 486
 		}
487 487
 		$calendar = [
488 488
 			'id' => $row['id'],
489 489
 			'uri' => $row['publicuri'],
490 490
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
491
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
492
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
493
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
495
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
496
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
497
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
491
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
492
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
493
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
495
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
496
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
497
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
498 498
 		];
499 499
 
500
-		foreach($this->propertyMap as $xmlName=>$dbName) {
500
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
501 501
 			$calendar[$xmlName] = $row[$dbName];
502 502
 		}
503 503
 
@@ -537,20 +537,20 @@  discard block
 block discarded – undo
537 537
 
538 538
 		$components = [];
539 539
 		if ($row['components']) {
540
-			$components = explode(',',$row['components']);
540
+			$components = explode(',', $row['components']);
541 541
 		}
542 542
 
543 543
 		$calendar = [
544 544
 			'id' => $row['id'],
545 545
 			'uri' => $row['uri'],
546 546
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
547
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
548
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
549
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
550
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
547
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
548
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
549
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
550
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
551 551
 		];
552 552
 
553
-		foreach($this->propertyMap as $xmlName=>$dbName) {
553
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
554 554
 			$calendar[$xmlName] = $row[$dbName];
555 555
 		}
556 556
 
@@ -583,20 +583,20 @@  discard block
 block discarded – undo
583 583
 
584 584
 		$components = [];
585 585
 		if ($row['components']) {
586
-			$components = explode(',',$row['components']);
586
+			$components = explode(',', $row['components']);
587 587
 		}
588 588
 
589 589
 		$calendar = [
590 590
 			'id' => $row['id'],
591 591
 			'uri' => $row['uri'],
592 592
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
593
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
594
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
595
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
596
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
593
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
594
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
595
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
596
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
597 597
 		];
598 598
 
599
-		foreach($this->propertyMap as $xmlName=>$dbName) {
599
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
600 600
 			$calendar[$xmlName] = $row[$dbName];
601 601
 		}
602 602
 
@@ -630,16 +630,16 @@  discard block
 block discarded – undo
630 630
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
631 631
 		if (isset($properties[$sccs])) {
632 632
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
633
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
633
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
634 634
 			}
635
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
635
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
636 636
 		}
637
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
637
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
638 638
 		if (isset($properties[$transp])) {
639 639
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
640 640
 		}
641 641
 
642
-		foreach($this->propertyMap as $xmlName=>$dbName) {
642
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
643 643
 			if (isset($properties[$xmlName])) {
644 644
 				$values[$dbName] = $properties[$xmlName];
645 645
 			}
@@ -647,7 +647,7 @@  discard block
 block discarded – undo
647 647
 
648 648
 		$query = $this->db->getQueryBuilder();
649 649
 		$query->insert('calendars');
650
-		foreach($values as $column => $value) {
650
+		foreach ($values as $column => $value) {
651 651
 			$query->setValue($column, $query->createNamedParameter($value));
652 652
 		}
653 653
 		$query->execute();
@@ -680,14 +680,14 @@  discard block
 block discarded – undo
680 680
 	 */
681 681
 	function updateCalendar($calendarId, PropPatch $propPatch) {
682 682
 		$supportedProperties = array_keys($this->propertyMap);
683
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
683
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
684 684
 
685 685
 		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
686 686
 			$newValues = [];
687 687
 			foreach ($mutations as $propertyName => $propertyValue) {
688 688
 
689 689
 				switch ($propertyName) {
690
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
690
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
691 691
 						$fieldName = 'transparent';
692 692
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
693 693
 						break;
@@ -797,16 +797,16 @@  discard block
 block discarded – undo
797 797
 		$stmt = $query->execute();
798 798
 
799 799
 		$result = [];
800
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
800
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
801 801
 			$result[] = [
802 802
 					'id'           => $row['id'],
803 803
 					'uri'          => $row['uri'],
804 804
 					'lastmodified' => $row['lastmodified'],
805
-					'etag'         => '"' . $row['etag'] . '"',
805
+					'etag'         => '"'.$row['etag'].'"',
806 806
 					'calendarid'   => $row['calendarid'],
807
-					'size'         => (int)$row['size'],
807
+					'size'         => (int) $row['size'],
808 808
 					'component'    => strtolower($row['componenttype']),
809
-					'classification'=> (int)$row['classification']
809
+					'classification'=> (int) $row['classification']
810 810
 			];
811 811
 		}
812 812
 
@@ -839,18 +839,18 @@  discard block
 block discarded – undo
839 839
 		$stmt = $query->execute();
840 840
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
841 841
 
842
-		if(!$row) return null;
842
+		if (!$row) return null;
843 843
 
844 844
 		return [
845 845
 				'id'            => $row['id'],
846 846
 				'uri'           => $row['uri'],
847 847
 				'lastmodified'  => $row['lastmodified'],
848
-				'etag'          => '"' . $row['etag'] . '"',
848
+				'etag'          => '"'.$row['etag'].'"',
849 849
 				'calendarid'    => $row['calendarid'],
850
-				'size'          => (int)$row['size'],
850
+				'size'          => (int) $row['size'],
851 851
 				'calendardata'  => $this->readBlob($row['calendardata']),
852 852
 				'component'     => strtolower($row['componenttype']),
853
-				'classification'=> (int)$row['classification']
853
+				'classification'=> (int) $row['classification']
854 854
 		];
855 855
 	}
856 856
 
@@ -889,12 +889,12 @@  discard block
 block discarded – undo
889 889
 					'id'           => $row['id'],
890 890
 					'uri'          => $row['uri'],
891 891
 					'lastmodified' => $row['lastmodified'],
892
-					'etag'         => '"' . $row['etag'] . '"',
892
+					'etag'         => '"'.$row['etag'].'"',
893 893
 					'calendarid'   => $row['calendarid'],
894
-					'size'         => (int)$row['size'],
894
+					'size'         => (int) $row['size'],
895 895
 					'calendardata' => $this->readBlob($row['calendardata']),
896 896
 					'component'    => strtolower($row['componenttype']),
897
-					'classification' => (int)$row['classification']
897
+					'classification' => (int) $row['classification']
898 898
 				];
899 899
 			}
900 900
 			$result->closeCursor();
@@ -951,7 +951,7 @@  discard block
 block discarded – undo
951 951
 		));
952 952
 		$this->addChange($calendarId, $objectUri, 1);
953 953
 
954
-		return '"' . $extraData['etag'] . '"';
954
+		return '"'.$extraData['etag'].'"';
955 955
 	}
956 956
 
957 957
 	/**
@@ -1004,7 +1004,7 @@  discard block
 block discarded – undo
1004 1004
 		}
1005 1005
 		$this->addChange($calendarId, $objectUri, 2);
1006 1006
 
1007
-		return '"' . $extraData['etag'] . '"';
1007
+		return '"'.$extraData['etag'].'"';
1008 1008
 	}
1009 1009
 
1010 1010
 	/**
@@ -1155,7 +1155,7 @@  discard block
 block discarded – undo
1155 1155
 		$stmt = $query->execute();
1156 1156
 
1157 1157
 		$result = [];
1158
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1158
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1159 1159
 			if ($requirePostFilter) {
1160 1160
 				if (!$this->validateFilterForObject($row, $filters)) {
1161 1161
 					continue;
@@ -1198,7 +1198,7 @@  discard block
 block discarded – undo
1198 1198
 		$stmt = $query->execute();
1199 1199
 
1200 1200
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1201
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1201
+			return $row['calendaruri'].'/'.$row['objecturi'];
1202 1202
 		}
1203 1203
 
1204 1204
 		return null;
@@ -1263,7 +1263,7 @@  discard block
 block discarded – undo
1263 1263
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1264 1264
 		// Current synctoken
1265 1265
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1266
-		$stmt->execute([ $calendarId ]);
1266
+		$stmt->execute([$calendarId]);
1267 1267
 		$currentToken = $stmt->fetchColumn(0);
1268 1268
 
1269 1269
 		if (is_null($currentToken)) {
@@ -1280,8 +1280,8 @@  discard block
 block discarded – undo
1280 1280
 		if ($syncToken) {
1281 1281
 
1282 1282
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1283
-			if ($limit>0) {
1284
-				$query.= " `LIMIT` " . (int)$limit;
1283
+			if ($limit > 0) {
1284
+				$query .= " `LIMIT` ".(int) $limit;
1285 1285
 			}
1286 1286
 
1287 1287
 			// Fetching all changes
@@ -1292,15 +1292,15 @@  discard block
 block discarded – undo
1292 1292
 
1293 1293
 			// This loop ensures that any duplicates are overwritten, only the
1294 1294
 			// last change on a node is relevant.
1295
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1295
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1296 1296
 
1297 1297
 				$changes[$row['uri']] = $row['operation'];
1298 1298
 
1299 1299
 			}
1300 1300
 
1301
-			foreach($changes as $uri => $operation) {
1301
+			foreach ($changes as $uri => $operation) {
1302 1302
 
1303
-				switch($operation) {
1303
+				switch ($operation) {
1304 1304
 					case 1 :
1305 1305
 						$result['added'][] = $uri;
1306 1306
 						break;
@@ -1370,10 +1370,10 @@  discard block
 block discarded – undo
1370 1370
 			->from('calendarsubscriptions')
1371 1371
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1372 1372
 			->orderBy('calendarorder', 'asc');
1373
-		$stmt =$query->execute();
1373
+		$stmt = $query->execute();
1374 1374
 
1375 1375
 		$subscriptions = [];
1376
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1376
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1377 1377
 
1378 1378
 			$subscription = [
1379 1379
 				'id'           => $row['id'],
@@ -1382,10 +1382,10 @@  discard block
 block discarded – undo
1382 1382
 				'source'       => $row['source'],
1383 1383
 				'lastmodified' => $row['lastmodified'],
1384 1384
 
1385
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1385
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1386 1386
 			];
1387 1387
 
1388
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1388
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1389 1389
 				if (!is_null($row[$dbName])) {
1390 1390
 					$subscription[$xmlName] = $row[$dbName];
1391 1391
 				}
@@ -1424,7 +1424,7 @@  discard block
 block discarded – undo
1424 1424
 
1425 1425
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1426 1426
 
1427
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1427
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1428 1428
 			if (array_key_exists($xmlName, $properties)) {
1429 1429
 					$values[$dbName] = $properties[$xmlName];
1430 1430
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1472,7 +1472,7 @@  discard block
 block discarded – undo
1472 1472
 
1473 1473
 			$newValues = [];
1474 1474
 
1475
-			foreach($mutations as $propertyName=>$propertyValue) {
1475
+			foreach ($mutations as $propertyName=>$propertyValue) {
1476 1476
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1477 1477
 					$newValues['source'] = $propertyValue->getHref();
1478 1478
 				} else {
@@ -1484,7 +1484,7 @@  discard block
 block discarded – undo
1484 1484
 			$query = $this->db->getQueryBuilder();
1485 1485
 			$query->update('calendarsubscriptions')
1486 1486
 				->set('lastmodified', $query->createNamedParameter(time()));
1487
-			foreach($newValues as $fieldName=>$value) {
1487
+			foreach ($newValues as $fieldName=>$value) {
1488 1488
 				$query->set($fieldName, $query->createNamedParameter($value));
1489 1489
 			}
1490 1490
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1534,7 +1534,7 @@  discard block
 block discarded – undo
1534 1534
 
1535 1535
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1536 1536
 
1537
-		if(!$row) {
1537
+		if (!$row) {
1538 1538
 			return null;
1539 1539
 		}
1540 1540
 
@@ -1542,8 +1542,8 @@  discard block
 block discarded – undo
1542 1542
 				'uri'          => $row['uri'],
1543 1543
 				'calendardata' => $row['calendardata'],
1544 1544
 				'lastmodified' => $row['lastmodified'],
1545
-				'etag'         => '"' . $row['etag'] . '"',
1546
-				'size'         => (int)$row['size'],
1545
+				'etag'         => '"'.$row['etag'].'"',
1546
+				'size'         => (int) $row['size'],
1547 1547
 		];
1548 1548
 	}
1549 1549
 
@@ -1566,13 +1566,13 @@  discard block
 block discarded – undo
1566 1566
 				->execute();
1567 1567
 
1568 1568
 		$result = [];
1569
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1569
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1570 1570
 			$result[] = [
1571 1571
 					'calendardata' => $row['calendardata'],
1572 1572
 					'uri'          => $row['uri'],
1573 1573
 					'lastmodified' => $row['lastmodified'],
1574
-					'etag'         => '"' . $row['etag'] . '"',
1575
-					'size'         => (int)$row['size'],
1574
+					'etag'         => '"'.$row['etag'].'"',
1575
+					'size'         => (int) $row['size'],
1576 1576
 			];
1577 1577
 		}
1578 1578
 
@@ -1664,10 +1664,10 @@  discard block
 block discarded – undo
1664 1664
 		$lastOccurrence = null;
1665 1665
 		$uid = null;
1666 1666
 		$classification = self::CLASSIFICATION_PUBLIC;
1667
-		foreach($vObject->getComponents() as $component) {
1668
-			if ($component->name!=='VTIMEZONE') {
1667
+		foreach ($vObject->getComponents() as $component) {
1668
+			if ($component->name !== 'VTIMEZONE') {
1669 1669
 				$componentType = $component->name;
1670
-				$uid = (string)$component->UID;
1670
+				$uid = (string) $component->UID;
1671 1671
 				break;
1672 1672
 			}
1673 1673
 		}
@@ -1692,13 +1692,13 @@  discard block
 block discarded – undo
1692 1692
 					$lastOccurrence = $firstOccurrence;
1693 1693
 				}
1694 1694
 			} else {
1695
-				$it = new EventIterator($vObject, (string)$component->UID);
1695
+				$it = new EventIterator($vObject, (string) $component->UID);
1696 1696
 				$maxDate = new \DateTime(self::MAX_DATE);
1697 1697
 				if ($it->isInfinite()) {
1698 1698
 					$lastOccurrence = $maxDate->getTimestamp();
1699 1699
 				} else {
1700 1700
 					$end = $it->getDtEnd();
1701
-					while($it->valid() && $end < $maxDate) {
1701
+					while ($it->valid() && $end < $maxDate) {
1702 1702
 						$end = $it->getDtEnd();
1703 1703
 						$it->next();
1704 1704
 
@@ -1832,8 +1832,8 @@  discard block
 block discarded – undo
1832 1832
 	}
1833 1833
 
1834 1834
 	private function addOwnerPrincipal(&$calendarInfo) {
1835
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1836
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1835
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
1836
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
1837 1837
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
1838 1838
 			$uri = $calendarInfo[$ownerPrincipalKey];
1839 1839
 		} else {
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ShareTypeList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
 	 * The deserialize method is called during xml parsing.
62 62
 	 *
63 63
 	 * @param Reader $reader
64
-	 * @return mixed
64
+	 * @return null|ShareTypeList
65 65
 	 */
66 66
 	static function xmlDeserialize(Reader $reader) {
67 67
 		$shareTypes = [];
Please login to merge, or discard this patch.
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -32,61 +32,61 @@
 block discarded – undo
32 32
  * This property contains multiple "share-type" elements, each containing a share type.
33 33
  */
34 34
 class ShareTypeList implements Element {
35
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
35
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
36 36
 
37
-	/**
38
-	 * Share types
39
-	 *
40
-	 * @var int[]
41
-	 */
42
-	private $shareTypes;
37
+    /**
38
+     * Share types
39
+     *
40
+     * @var int[]
41
+     */
42
+    private $shareTypes;
43 43
 
44
-	/**
45
-	 * @param int[] $shareTypes
46
-	 */
47
-	public function __construct($shareTypes) {
48
-		$this->shareTypes = $shareTypes;
49
-	}
44
+    /**
45
+     * @param int[] $shareTypes
46
+     */
47
+    public function __construct($shareTypes) {
48
+        $this->shareTypes = $shareTypes;
49
+    }
50 50
 
51
-	/**
52
-	 * Returns the share types
53
-	 *
54
-	 * @return int[]
55
-	 */
56
-	public function getShareTypes() {
57
-		return $this->shareTypes;
58
-	}
51
+    /**
52
+     * Returns the share types
53
+     *
54
+     * @return int[]
55
+     */
56
+    public function getShareTypes() {
57
+        return $this->shareTypes;
58
+    }
59 59
 
60
-	/**
61
-	 * The deserialize method is called during xml parsing.
62
-	 *
63
-	 * @param Reader $reader
64
-	 * @return mixed
65
-	 */
66
-	static function xmlDeserialize(Reader $reader) {
67
-		$shareTypes = [];
60
+    /**
61
+     * The deserialize method is called during xml parsing.
62
+     *
63
+     * @param Reader $reader
64
+     * @return mixed
65
+     */
66
+    static function xmlDeserialize(Reader $reader) {
67
+        $shareTypes = [];
68 68
 
69
-		$tree = $reader->parseInnerTree();
70
-		if ($tree === null) {
71
-			return null;
72
-		}
73
-		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
76
-			}
77
-		}
78
-		return new self($shareTypes);
79
-	}
69
+        $tree = $reader->parseInnerTree();
70
+        if ($tree === null) {
71
+            return null;
72
+        }
73
+        foreach ($tree as $elem) {
74
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
+                $shareTypes[] = (int)$elem['value'];
76
+            }
77
+        }
78
+        return new self($shareTypes);
79
+    }
80 80
 
81
-	/**
82
-	 * The xmlSerialize metod is called during xml writing.
83
-	 *
84
-	 * @param Writer $writer
85
-	 * @return void
86
-	 */
87
-	function xmlSerialize(Writer $writer) {
88
-		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
-		}
91
-	}
81
+    /**
82
+     * The xmlSerialize metod is called during xml writing.
83
+     *
84
+     * @param Writer $writer
85
+     * @return void
86
+     */
87
+    function xmlSerialize(Writer $writer) {
88
+        foreach ($this->shareTypes as $shareType) {
89
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
+        }
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -71,8 +71,8 @@  discard block
 block discarded – undo
71 71
 			return null;
72 72
 		}
73 73
 		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
74
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}share-type') {
75
+				$shareTypes[] = (int) $elem['value'];
76 76
 			}
77 77
 		}
78 78
 		return new self($shareTypes);
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 */
87 87
 	function xmlSerialize(Writer $writer) {
88 88
 		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
89
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}share-type', $shareType);
90 90
 		}
91 91
 	}
92 92
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/TagList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@
 block discarded – undo
80 80
 	 * the next element.
81 81
 	 *
82 82
 	 * @param Reader $reader
83
-	 * @return mixed
83
+	 * @return null|TagList
84 84
 	 */
85 85
 	static function xmlDeserialize(Reader $reader) {
86 86
 		$tags = [];
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -34,92 +34,92 @@
 block discarded – undo
34 34
  * This property contains multiple "tag" elements, each containing a tag name.
35 35
  */
36 36
 class TagList implements Element {
37
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
37
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
38 38
 
39
-	/**
40
-	 * tags
41
-	 *
42
-	 * @var array
43
-	 */
44
-	private $tags;
39
+    /**
40
+     * tags
41
+     *
42
+     * @var array
43
+     */
44
+    private $tags;
45 45
 
46
-	/**
47
-	 * @param array $tags
48
-	 */
49
-	public function __construct(array $tags) {
50
-		$this->tags = $tags;
51
-	}
46
+    /**
47
+     * @param array $tags
48
+     */
49
+    public function __construct(array $tags) {
50
+        $this->tags = $tags;
51
+    }
52 52
 
53
-	/**
54
-	 * Returns the tags
55
-	 *
56
-	 * @return array
57
-	 */
58
-	public function getTags() {
53
+    /**
54
+     * Returns the tags
55
+     *
56
+     * @return array
57
+     */
58
+    public function getTags() {
59 59
 
60
-		return $this->tags;
60
+        return $this->tags;
61 61
 
62
-	}
62
+    }
63 63
 
64
-	/**
65
-	 * The deserialize method is called during xml parsing.
66
-	 *
67
-	 * This method is called statictly, this is because in theory this method
68
-	 * may be used as a type of constructor, or factory method.
69
-	 *
70
-	 * Often you want to return an instance of the current class, but you are
71
-	 * free to return other data as well.
72
-	 *
73
-	 * You are responsible for advancing the reader to the next element. Not
74
-	 * doing anything will result in a never-ending loop.
75
-	 *
76
-	 * If you just want to skip parsing for this element altogether, you can
77
-	 * just call $reader->next();
78
-	 *
79
-	 * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
-	 * the next element.
81
-	 *
82
-	 * @param Reader $reader
83
-	 * @return mixed
84
-	 */
85
-	static function xmlDeserialize(Reader $reader) {
86
-		$tags = [];
64
+    /**
65
+     * The deserialize method is called during xml parsing.
66
+     *
67
+     * This method is called statictly, this is because in theory this method
68
+     * may be used as a type of constructor, or factory method.
69
+     *
70
+     * Often you want to return an instance of the current class, but you are
71
+     * free to return other data as well.
72
+     *
73
+     * You are responsible for advancing the reader to the next element. Not
74
+     * doing anything will result in a never-ending loop.
75
+     *
76
+     * If you just want to skip parsing for this element altogether, you can
77
+     * just call $reader->next();
78
+     *
79
+     * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
+     * the next element.
81
+     *
82
+     * @param Reader $reader
83
+     * @return mixed
84
+     */
85
+    static function xmlDeserialize(Reader $reader) {
86
+        $tags = [];
87 87
 
88
-		$tree = $reader->parseInnerTree();
89
-		if ($tree === null) {
90
-			return null;
91
-		}
92
-		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
-				$tags[] = $elem['value'];
95
-			}
96
-		}
97
-		return new self($tags);
98
-	}
88
+        $tree = $reader->parseInnerTree();
89
+        if ($tree === null) {
90
+            return null;
91
+        }
92
+        foreach ($tree as $elem) {
93
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
+                $tags[] = $elem['value'];
95
+            }
96
+        }
97
+        return new self($tags);
98
+    }
99 99
 
100
-	/**
101
-	 * The xmlSerialize metod is called during xml writing.
102
-	 *
103
-	 * Use the $writer argument to write its own xml serialization.
104
-	 *
105
-	 * An important note: do _not_ create a parent element. Any element
106
-	 * implementing XmlSerializble should only ever write what's considered
107
-	 * its 'inner xml'.
108
-	 *
109
-	 * The parent of the current element is responsible for writing a
110
-	 * containing element.
111
-	 *
112
-	 * This allows serializers to be re-used for different element names.
113
-	 *
114
-	 * If you are opening new elements, you must also close them again.
115
-	 *
116
-	 * @param Writer $writer
117
-	 * @return void
118
-	 */
119
-	function xmlSerialize(Writer $writer) {
100
+    /**
101
+     * The xmlSerialize metod is called during xml writing.
102
+     *
103
+     * Use the $writer argument to write its own xml serialization.
104
+     *
105
+     * An important note: do _not_ create a parent element. Any element
106
+     * implementing XmlSerializble should only ever write what's considered
107
+     * its 'inner xml'.
108
+     *
109
+     * The parent of the current element is responsible for writing a
110
+     * containing element.
111
+     *
112
+     * This allows serializers to be re-used for different element names.
113
+     *
114
+     * If you are opening new elements, you must also close them again.
115
+     *
116
+     * @param Writer $writer
117
+     * @return void
118
+     */
119
+    function xmlSerialize(Writer $writer) {
120 120
 
121
-		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
-		}
124
-	}
121
+        foreach ($this->tags as $tag) {
122
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
+        }
124
+    }
125 125
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			return null;
91 91
 		}
92 92
 		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
93
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}tag') {
94 94
 				$tags[] = $elem['value'];
95 95
 			}
96 96
 		}
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 	function xmlSerialize(Writer $writer) {
120 120
 
121 121
 		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
122
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}tag', $tag);
123 123
 		}
124 124
 	}
125 125
 }
Please login to merge, or discard this patch.