Completed
Pull Request — master (#6414)
by Joas
22:42 queued 07:13
created
lib/private/Server.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -99,7 +99,6 @@
 block discarded – undo
99 99
 use OC\Tagging\TagMapper;
100 100
 use OC\Template\SCSSCacher;
101 101
 use OCA\Theming\ThemingDefaults;
102
-
103 102
 use OCP\App\IAppManager;
104 103
 use OCP\AppFramework\Utility\ITimeFactory;
105 104
 use OCP\Defaults;
Please login to merge, or discard this patch.
Indentation   +1681 added lines, -1681 removed lines patch added patch discarded remove patch
@@ -127,1690 +127,1690 @@
 block discarded – undo
127 127
  * TODO: hookup all manager classes
128 128
  */
129 129
 class Server extends ServerContainer implements IServerContainer {
130
-	/** @var string */
131
-	private $webRoot;
132
-
133
-	/**
134
-	 * @param string $webRoot
135
-	 * @param \OC\Config $config
136
-	 */
137
-	public function __construct($webRoot, \OC\Config $config) {
138
-		parent::__construct();
139
-		$this->webRoot = $webRoot;
140
-
141
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
142
-			return $c;
143
-		});
144
-
145
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
146
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
147
-
148
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
149
-
150
-
151
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
152
-			return new PreviewManager(
153
-				$c->getConfig(),
154
-				$c->getRootFolder(),
155
-				$c->getAppDataDir('preview'),
156
-				$c->getEventDispatcher(),
157
-				$c->getSession()->get('user_id')
158
-			);
159
-		});
160
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
161
-
162
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
163
-			return new \OC\Preview\Watcher(
164
-				$c->getAppDataDir('preview')
165
-			);
166
-		});
167
-
168
-		$this->registerService('EncryptionManager', function (Server $c) {
169
-			$view = new View();
170
-			$util = new Encryption\Util(
171
-				$view,
172
-				$c->getUserManager(),
173
-				$c->getGroupManager(),
174
-				$c->getConfig()
175
-			);
176
-			return new Encryption\Manager(
177
-				$c->getConfig(),
178
-				$c->getLogger(),
179
-				$c->getL10N('core'),
180
-				new View(),
181
-				$util,
182
-				new ArrayCache()
183
-			);
184
-		});
185
-
186
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
187
-			$util = new Encryption\Util(
188
-				new View(),
189
-				$c->getUserManager(),
190
-				$c->getGroupManager(),
191
-				$c->getConfig()
192
-			);
193
-			return new Encryption\File(
194
-				$util,
195
-				$c->getRootFolder(),
196
-				$c->getShareManager()
197
-			);
198
-		});
199
-
200
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
201
-			$view = new View();
202
-			$util = new Encryption\Util(
203
-				$view,
204
-				$c->getUserManager(),
205
-				$c->getGroupManager(),
206
-				$c->getConfig()
207
-			);
208
-
209
-			return new Encryption\Keys\Storage($view, $util);
210
-		});
211
-		$this->registerService('TagMapper', function (Server $c) {
212
-			return new TagMapper($c->getDatabaseConnection());
213
-		});
214
-
215
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
216
-			$tagMapper = $c->query('TagMapper');
217
-			return new TagManager($tagMapper, $c->getUserSession());
218
-		});
219
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
220
-
221
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
222
-			$config = $c->getConfig();
223
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
224
-			/** @var \OC\SystemTag\ManagerFactory $factory */
225
-			$factory = new $factoryClass($this);
226
-			return $factory;
227
-		});
228
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
229
-			return $c->query('SystemTagManagerFactory')->getManager();
230
-		});
231
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
232
-
233
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
234
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
235
-		});
236
-		$this->registerService('RootFolder', function (Server $c) {
237
-			$manager = \OC\Files\Filesystem::getMountManager(null);
238
-			$view = new View();
239
-			$root = new Root(
240
-				$manager,
241
-				$view,
242
-				null,
243
-				$c->getUserMountCache(),
244
-				$this->getLogger(),
245
-				$this->getUserManager()
246
-			);
247
-			$connector = new HookConnector($root, $view);
248
-			$connector->viewToNode();
249
-
250
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
251
-			$previewConnector->connectWatcher();
252
-
253
-			return $root;
254
-		});
255
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
256
-
257
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
258
-			return new LazyRoot(function () use ($c) {
259
-				return $c->query('RootFolder');
260
-			});
261
-		});
262
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
263
-
264
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
265
-			$config = $c->getConfig();
266
-			return new \OC\User\Manager($config);
267
-		});
268
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
269
-
270
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
271
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
272
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
273
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
274
-			});
275
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
276
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
277
-			});
278
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
279
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
280
-			});
281
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
282
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
283
-			});
284
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
285
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
286
-			});
287
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
288
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
289
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
290
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
291
-			});
292
-			return $groupManager;
293
-		});
294
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
295
-
296
-		$this->registerService(Store::class, function (Server $c) {
297
-			$session = $c->getSession();
298
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
299
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
300
-			} else {
301
-				$tokenProvider = null;
302
-			}
303
-			$logger = $c->getLogger();
304
-			return new Store($session, $logger, $tokenProvider);
305
-		});
306
-		$this->registerAlias(IStore::class, Store::class);
307
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
308
-			$dbConnection = $c->getDatabaseConnection();
309
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
310
-		});
311
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
312
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
313
-			$crypto = $c->getCrypto();
314
-			$config = $c->getConfig();
315
-			$logger = $c->getLogger();
316
-			$timeFactory = new TimeFactory();
317
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
318
-		});
319
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
320
-
321
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
322
-			$manager = $c->getUserManager();
323
-			$session = new \OC\Session\Memory('');
324
-			$timeFactory = new TimeFactory();
325
-			// Token providers might require a working database. This code
326
-			// might however be called when ownCloud is not yet setup.
327
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
328
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
329
-			} else {
330
-				$defaultTokenProvider = null;
331
-			}
332
-
333
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
334
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
335
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
336
-			});
337
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
338
-				/** @var $user \OC\User\User */
339
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
340
-			});
341
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
342
-				/** @var $user \OC\User\User */
343
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
344
-			});
345
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
346
-				/** @var $user \OC\User\User */
347
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
348
-			});
349
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
350
-				/** @var $user \OC\User\User */
351
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
352
-			});
353
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
354
-				/** @var $user \OC\User\User */
355
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
356
-			});
357
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
358
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
359
-			});
360
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
361
-				/** @var $user \OC\User\User */
362
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
363
-			});
364
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
365
-				/** @var $user \OC\User\User */
366
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
367
-			});
368
-			$userSession->listen('\OC\User', 'logout', function () {
369
-				\OC_Hook::emit('OC_User', 'logout', array());
370
-			});
371
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
372
-				/** @var $user \OC\User\User */
373
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
374
-			});
375
-			return $userSession;
376
-		});
377
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
378
-
379
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
380
-			return new \OC\Authentication\TwoFactorAuth\Manager(
381
-				$c->getAppManager(),
382
-				$c->getSession(),
383
-				$c->getConfig(),
384
-				$c->getActivityManager(),
385
-				$c->getLogger(),
386
-				$c->query(\OC\Authentication\Token\IProvider::class),
387
-				$c->query(ITimeFactory::class)
388
-			);
389
-		});
390
-
391
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
392
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
393
-
394
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
395
-			return new \OC\AllConfig(
396
-				$c->getSystemConfig()
397
-			);
398
-		});
399
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
400
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
401
-
402
-		$this->registerService('SystemConfig', function ($c) use ($config) {
403
-			return new \OC\SystemConfig($config);
404
-		});
405
-
406
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
407
-			return new \OC\AppConfig($c->getDatabaseConnection());
408
-		});
409
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
410
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
411
-
412
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
413
-			return new \OC\L10N\Factory(
414
-				$c->getConfig(),
415
-				$c->getRequest(),
416
-				$c->getUserSession(),
417
-				\OC::$SERVERROOT
418
-			);
419
-		});
420
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
421
-
422
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
423
-			$config = $c->getConfig();
424
-			$cacheFactory = $c->getMemCacheFactory();
425
-			$request = $c->getRequest();
426
-			return new \OC\URLGenerator(
427
-				$config,
428
-				$cacheFactory,
429
-				$request
430
-			);
431
-		});
432
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
433
-
434
-		$this->registerService('AppHelper', function ($c) {
435
-			return new \OC\AppHelper();
436
-		});
437
-		$this->registerAlias('AppFetcher', AppFetcher::class);
438
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
439
-
440
-		$this->registerService(\OCP\ICache::class, function ($c) {
441
-			return new Cache\File();
442
-		});
443
-		$this->registerAlias('UserCache', \OCP\ICache::class);
444
-
445
-		$this->registerService(Factory::class, function (Server $c) {
446
-
447
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
448
-				'\\OC\\Memcache\\ArrayCache',
449
-				'\\OC\\Memcache\\ArrayCache',
450
-				'\\OC\\Memcache\\ArrayCache'
451
-			);
452
-			$config = $c->getConfig();
453
-			$request = $c->getRequest();
454
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
455
-
456
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
457
-				$v = \OC_App::getAppVersions();
458
-				$v['core'] = implode(',', \OC_Util::getVersion());
459
-				$version = implode(',', $v);
460
-				$instanceId = \OC_Util::getInstanceId();
461
-				$path = \OC::$SERVERROOT;
462
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
463
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
464
-					$config->getSystemValue('memcache.local', null),
465
-					$config->getSystemValue('memcache.distributed', null),
466
-					$config->getSystemValue('memcache.locking', null)
467
-				);
468
-			}
469
-			return $arrayCacheFactory;
470
-
471
-		});
472
-		$this->registerAlias('MemCacheFactory', Factory::class);
473
-		$this->registerAlias(ICacheFactory::class, Factory::class);
474
-
475
-		$this->registerService('RedisFactory', function (Server $c) {
476
-			$systemConfig = $c->getSystemConfig();
477
-			return new RedisFactory($systemConfig);
478
-		});
479
-
480
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
481
-			return new \OC\Activity\Manager(
482
-				$c->getRequest(),
483
-				$c->getUserSession(),
484
-				$c->getConfig(),
485
-				$c->query(IValidator::class)
486
-			);
487
-		});
488
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
489
-
490
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
491
-			return new \OC\Activity\EventMerger(
492
-				$c->getL10N('lib')
493
-			);
494
-		});
495
-		$this->registerAlias(IValidator::class, Validator::class);
496
-
497
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
498
-			return new AvatarManager(
499
-				$c->getUserManager(),
500
-				$c->getAppDataDir('avatar'),
501
-				$c->getL10N('lib'),
502
-				$c->getLogger(),
503
-				$c->getConfig()
504
-			);
505
-		});
506
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
507
-
508
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
509
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
510
-			$logger = Log::getLogClass($logType);
511
-			call_user_func(array($logger, 'init'));
512
-
513
-			return new Log($logger);
514
-		});
515
-		$this->registerAlias('Logger', \OCP\ILogger::class);
516
-
517
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
518
-			$config = $c->getConfig();
519
-			return new \OC\BackgroundJob\JobList(
520
-				$c->getDatabaseConnection(),
521
-				$config,
522
-				new TimeFactory()
523
-			);
524
-		});
525
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
526
-
527
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
528
-			$cacheFactory = $c->getMemCacheFactory();
529
-			$logger = $c->getLogger();
530
-			if ($cacheFactory->isAvailable()) {
531
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
532
-			} else {
533
-				$router = new \OC\Route\Router($logger);
534
-			}
535
-			return $router;
536
-		});
537
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
538
-
539
-		$this->registerService(\OCP\ISearch::class, function ($c) {
540
-			return new Search();
541
-		});
542
-		$this->registerAlias('Search', \OCP\ISearch::class);
543
-
544
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
545
-			return new \OC\Security\RateLimiting\Limiter(
546
-				$this->getUserSession(),
547
-				$this->getRequest(),
548
-				new \OC\AppFramework\Utility\TimeFactory(),
549
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
550
-			);
551
-		});
552
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
553
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
554
-				$this->getMemCacheFactory(),
555
-				new \OC\AppFramework\Utility\TimeFactory()
556
-			);
557
-		});
558
-
559
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
560
-			return new SecureRandom();
561
-		});
562
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
563
-
564
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
565
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
566
-		});
567
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
568
-
569
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
570
-			return new Hasher($c->getConfig());
571
-		});
572
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
573
-
574
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
575
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
576
-		});
577
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
578
-
579
-		$this->registerService(IDBConnection::class, function (Server $c) {
580
-			$systemConfig = $c->getSystemConfig();
581
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
582
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
583
-			if (!$factory->isValidType($type)) {
584
-				throw new \OC\DatabaseException('Invalid database type');
585
-			}
586
-			$connectionParams = $factory->createConnectionParams();
587
-			$connection = $factory->getConnection($type, $connectionParams);
588
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
589
-			return $connection;
590
-		});
591
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
592
-
593
-		$this->registerService('HTTPHelper', function (Server $c) {
594
-			$config = $c->getConfig();
595
-			return new HTTPHelper(
596
-				$config,
597
-				$c->getHTTPClientService()
598
-			);
599
-		});
600
-
601
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
602
-			$user = \OC_User::getUser();
603
-			$uid = $user ? $user : null;
604
-			return new ClientService(
605
-				$c->getConfig(),
606
-				new \OC\Security\CertificateManager(
607
-					$uid,
608
-					new View(),
609
-					$c->getConfig(),
610
-					$c->getLogger(),
611
-					$c->getSecureRandom()
612
-				)
613
-			);
614
-		});
615
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
616
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
617
-			$eventLogger = new EventLogger();
618
-			if ($c->getSystemConfig()->getValue('debug', false)) {
619
-				// In debug mode, module is being activated by default
620
-				$eventLogger->activate();
621
-			}
622
-			return $eventLogger;
623
-		});
624
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
625
-
626
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
627
-			$queryLogger = new QueryLogger();
628
-			if ($c->getSystemConfig()->getValue('debug', false)) {
629
-				// In debug mode, module is being activated by default
630
-				$queryLogger->activate();
631
-			}
632
-			return $queryLogger;
633
-		});
634
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
635
-
636
-		$this->registerService(TempManager::class, function (Server $c) {
637
-			return new TempManager(
638
-				$c->getLogger(),
639
-				$c->getConfig()
640
-			);
641
-		});
642
-		$this->registerAlias('TempManager', TempManager::class);
643
-		$this->registerAlias(ITempManager::class, TempManager::class);
644
-
645
-		$this->registerService(AppManager::class, function (Server $c) {
646
-			return new \OC\App\AppManager(
647
-				$c->getUserSession(),
648
-				$c->getAppConfig(),
649
-				$c->getGroupManager(),
650
-				$c->getMemCacheFactory(),
651
-				$c->getEventDispatcher()
652
-			);
653
-		});
654
-		$this->registerAlias('AppManager', AppManager::class);
655
-		$this->registerAlias(IAppManager::class, AppManager::class);
656
-
657
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
658
-			return new DateTimeZone(
659
-				$c->getConfig(),
660
-				$c->getSession()
661
-			);
662
-		});
663
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
664
-
665
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
666
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
667
-
668
-			return new DateTimeFormatter(
669
-				$c->getDateTimeZone()->getTimeZone(),
670
-				$c->getL10N('lib', $language)
671
-			);
672
-		});
673
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
674
-
675
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
676
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
677
-			$listener = new UserMountCacheListener($mountCache);
678
-			$listener->listen($c->getUserManager());
679
-			return $mountCache;
680
-		});
681
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
682
-
683
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
684
-			$loader = \OC\Files\Filesystem::getLoader();
685
-			$mountCache = $c->query('UserMountCache');
686
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
687
-
688
-			// builtin providers
689
-
690
-			$config = $c->getConfig();
691
-			$manager->registerProvider(new CacheMountProvider($config));
692
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
693
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
694
-
695
-			return $manager;
696
-		});
697
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
698
-
699
-		$this->registerService('IniWrapper', function ($c) {
700
-			return new IniGetWrapper();
701
-		});
702
-		$this->registerService('AsyncCommandBus', function (Server $c) {
703
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
704
-			if ($busClass) {
705
-				list($app, $class) = explode('::', $busClass, 2);
706
-				if ($c->getAppManager()->isInstalled($app)) {
707
-					\OC_App::loadApp($app);
708
-					return $c->query($class);
709
-				} else {
710
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
711
-				}
712
-			} else {
713
-				$jobList = $c->getJobList();
714
-				return new CronBus($jobList);
715
-			}
716
-		});
717
-		$this->registerService('TrustedDomainHelper', function ($c) {
718
-			return new TrustedDomainHelper($this->getConfig());
719
-		});
720
-		$this->registerService('Throttler', function (Server $c) {
721
-			return new Throttler(
722
-				$c->getDatabaseConnection(),
723
-				new TimeFactory(),
724
-				$c->getLogger(),
725
-				$c->getConfig()
726
-			);
727
-		});
728
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
729
-			// IConfig and IAppManager requires a working database. This code
730
-			// might however be called when ownCloud is not yet setup.
731
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
732
-				$config = $c->getConfig();
733
-				$appManager = $c->getAppManager();
734
-			} else {
735
-				$config = null;
736
-				$appManager = null;
737
-			}
738
-
739
-			return new Checker(
740
-				new EnvironmentHelper(),
741
-				new FileAccessHelper(),
742
-				new AppLocator(),
743
-				$config,
744
-				$c->getMemCacheFactory(),
745
-				$appManager,
746
-				$c->getTempManager()
747
-			);
748
-		});
749
-		$this->registerService(\OCP\IRequest::class, function ($c) {
750
-			if (isset($this['urlParams'])) {
751
-				$urlParams = $this['urlParams'];
752
-			} else {
753
-				$urlParams = [];
754
-			}
755
-
756
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
757
-				&& in_array('fakeinput', stream_get_wrappers())
758
-			) {
759
-				$stream = 'fakeinput://data';
760
-			} else {
761
-				$stream = 'php://input';
762
-			}
763
-
764
-			return new Request(
765
-				[
766
-					'get' => $_GET,
767
-					'post' => $_POST,
768
-					'files' => $_FILES,
769
-					'server' => $_SERVER,
770
-					'env' => $_ENV,
771
-					'cookies' => $_COOKIE,
772
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
773
-						? $_SERVER['REQUEST_METHOD']
774
-						: null,
775
-					'urlParams' => $urlParams,
776
-				],
777
-				$this->getSecureRandom(),
778
-				$this->getConfig(),
779
-				$this->getCsrfTokenManager(),
780
-				$stream
781
-			);
782
-		});
783
-		$this->registerAlias('Request', \OCP\IRequest::class);
784
-
785
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
786
-			return new Mailer(
787
-				$c->getConfig(),
788
-				$c->getLogger(),
789
-				$c->query(Defaults::class),
790
-				$c->getURLGenerator(),
791
-				$c->getL10N('lib')
792
-			);
793
-		});
794
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
795
-
796
-		$this->registerService('LDAPProvider', function (Server $c) {
797
-			$config = $c->getConfig();
798
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
799
-			if (is_null($factoryClass)) {
800
-				throw new \Exception('ldapProviderFactory not set');
801
-			}
802
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
803
-			$factory = new $factoryClass($this);
804
-			return $factory->getLDAPProvider();
805
-		});
806
-		$this->registerService(ILockingProvider::class, function (Server $c) {
807
-			$ini = $c->getIniWrapper();
808
-			$config = $c->getConfig();
809
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
810
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
811
-				/** @var \OC\Memcache\Factory $memcacheFactory */
812
-				$memcacheFactory = $c->getMemCacheFactory();
813
-				$memcache = $memcacheFactory->createLocking('lock');
814
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
815
-					return new MemcacheLockingProvider($memcache, $ttl);
816
-				}
817
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
818
-			}
819
-			return new NoopLockingProvider();
820
-		});
821
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
822
-
823
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
824
-			return new \OC\Files\Mount\Manager();
825
-		});
826
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
827
-
828
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
829
-			return new \OC\Files\Type\Detection(
830
-				$c->getURLGenerator(),
831
-				\OC::$configDir,
832
-				\OC::$SERVERROOT . '/resources/config/'
833
-			);
834
-		});
835
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
836
-
837
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
838
-			return new \OC\Files\Type\Loader(
839
-				$c->getDatabaseConnection()
840
-			);
841
-		});
842
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
843
-		$this->registerService(BundleFetcher::class, function () {
844
-			return new BundleFetcher($this->getL10N('lib'));
845
-		});
846
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
847
-			return new Manager(
848
-				$c->query(IValidator::class)
849
-			);
850
-		});
851
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
852
-
853
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
854
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
855
-			$manager->registerCapability(function () use ($c) {
856
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
857
-			});
858
-			$manager->registerCapability(function () use ($c) {
859
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
860
-			});
861
-			return $manager;
862
-		});
863
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
864
-
865
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
866
-			$config = $c->getConfig();
867
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
868
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
869
-			$factory = new $factoryClass($this);
870
-			return $factory->getManager();
871
-		});
872
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
873
-
874
-		$this->registerService('ThemingDefaults', function (Server $c) {
875
-			/*
130
+    /** @var string */
131
+    private $webRoot;
132
+
133
+    /**
134
+     * @param string $webRoot
135
+     * @param \OC\Config $config
136
+     */
137
+    public function __construct($webRoot, \OC\Config $config) {
138
+        parent::__construct();
139
+        $this->webRoot = $webRoot;
140
+
141
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
142
+            return $c;
143
+        });
144
+
145
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
146
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
147
+
148
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
149
+
150
+
151
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
152
+            return new PreviewManager(
153
+                $c->getConfig(),
154
+                $c->getRootFolder(),
155
+                $c->getAppDataDir('preview'),
156
+                $c->getEventDispatcher(),
157
+                $c->getSession()->get('user_id')
158
+            );
159
+        });
160
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
161
+
162
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
163
+            return new \OC\Preview\Watcher(
164
+                $c->getAppDataDir('preview')
165
+            );
166
+        });
167
+
168
+        $this->registerService('EncryptionManager', function (Server $c) {
169
+            $view = new View();
170
+            $util = new Encryption\Util(
171
+                $view,
172
+                $c->getUserManager(),
173
+                $c->getGroupManager(),
174
+                $c->getConfig()
175
+            );
176
+            return new Encryption\Manager(
177
+                $c->getConfig(),
178
+                $c->getLogger(),
179
+                $c->getL10N('core'),
180
+                new View(),
181
+                $util,
182
+                new ArrayCache()
183
+            );
184
+        });
185
+
186
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
187
+            $util = new Encryption\Util(
188
+                new View(),
189
+                $c->getUserManager(),
190
+                $c->getGroupManager(),
191
+                $c->getConfig()
192
+            );
193
+            return new Encryption\File(
194
+                $util,
195
+                $c->getRootFolder(),
196
+                $c->getShareManager()
197
+            );
198
+        });
199
+
200
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
201
+            $view = new View();
202
+            $util = new Encryption\Util(
203
+                $view,
204
+                $c->getUserManager(),
205
+                $c->getGroupManager(),
206
+                $c->getConfig()
207
+            );
208
+
209
+            return new Encryption\Keys\Storage($view, $util);
210
+        });
211
+        $this->registerService('TagMapper', function (Server $c) {
212
+            return new TagMapper($c->getDatabaseConnection());
213
+        });
214
+
215
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
216
+            $tagMapper = $c->query('TagMapper');
217
+            return new TagManager($tagMapper, $c->getUserSession());
218
+        });
219
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
220
+
221
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
222
+            $config = $c->getConfig();
223
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
224
+            /** @var \OC\SystemTag\ManagerFactory $factory */
225
+            $factory = new $factoryClass($this);
226
+            return $factory;
227
+        });
228
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
229
+            return $c->query('SystemTagManagerFactory')->getManager();
230
+        });
231
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
232
+
233
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
234
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
235
+        });
236
+        $this->registerService('RootFolder', function (Server $c) {
237
+            $manager = \OC\Files\Filesystem::getMountManager(null);
238
+            $view = new View();
239
+            $root = new Root(
240
+                $manager,
241
+                $view,
242
+                null,
243
+                $c->getUserMountCache(),
244
+                $this->getLogger(),
245
+                $this->getUserManager()
246
+            );
247
+            $connector = new HookConnector($root, $view);
248
+            $connector->viewToNode();
249
+
250
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
251
+            $previewConnector->connectWatcher();
252
+
253
+            return $root;
254
+        });
255
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
256
+
257
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
258
+            return new LazyRoot(function () use ($c) {
259
+                return $c->query('RootFolder');
260
+            });
261
+        });
262
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
263
+
264
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
265
+            $config = $c->getConfig();
266
+            return new \OC\User\Manager($config);
267
+        });
268
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
269
+
270
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
271
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
272
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
273
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
274
+            });
275
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
276
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
277
+            });
278
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
279
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
280
+            });
281
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
282
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
283
+            });
284
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
285
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
286
+            });
287
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
288
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
289
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
290
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
291
+            });
292
+            return $groupManager;
293
+        });
294
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
295
+
296
+        $this->registerService(Store::class, function (Server $c) {
297
+            $session = $c->getSession();
298
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
299
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
300
+            } else {
301
+                $tokenProvider = null;
302
+            }
303
+            $logger = $c->getLogger();
304
+            return new Store($session, $logger, $tokenProvider);
305
+        });
306
+        $this->registerAlias(IStore::class, Store::class);
307
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
308
+            $dbConnection = $c->getDatabaseConnection();
309
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
310
+        });
311
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
312
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
313
+            $crypto = $c->getCrypto();
314
+            $config = $c->getConfig();
315
+            $logger = $c->getLogger();
316
+            $timeFactory = new TimeFactory();
317
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
318
+        });
319
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
320
+
321
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
322
+            $manager = $c->getUserManager();
323
+            $session = new \OC\Session\Memory('');
324
+            $timeFactory = new TimeFactory();
325
+            // Token providers might require a working database. This code
326
+            // might however be called when ownCloud is not yet setup.
327
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
328
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
329
+            } else {
330
+                $defaultTokenProvider = null;
331
+            }
332
+
333
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
334
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
335
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
336
+            });
337
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
338
+                /** @var $user \OC\User\User */
339
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
340
+            });
341
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
342
+                /** @var $user \OC\User\User */
343
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
344
+            });
345
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
346
+                /** @var $user \OC\User\User */
347
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
348
+            });
349
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
350
+                /** @var $user \OC\User\User */
351
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
352
+            });
353
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
354
+                /** @var $user \OC\User\User */
355
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
356
+            });
357
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
358
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
359
+            });
360
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
361
+                /** @var $user \OC\User\User */
362
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
363
+            });
364
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
365
+                /** @var $user \OC\User\User */
366
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
367
+            });
368
+            $userSession->listen('\OC\User', 'logout', function () {
369
+                \OC_Hook::emit('OC_User', 'logout', array());
370
+            });
371
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
372
+                /** @var $user \OC\User\User */
373
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
374
+            });
375
+            return $userSession;
376
+        });
377
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
378
+
379
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
380
+            return new \OC\Authentication\TwoFactorAuth\Manager(
381
+                $c->getAppManager(),
382
+                $c->getSession(),
383
+                $c->getConfig(),
384
+                $c->getActivityManager(),
385
+                $c->getLogger(),
386
+                $c->query(\OC\Authentication\Token\IProvider::class),
387
+                $c->query(ITimeFactory::class)
388
+            );
389
+        });
390
+
391
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
392
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
393
+
394
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
395
+            return new \OC\AllConfig(
396
+                $c->getSystemConfig()
397
+            );
398
+        });
399
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
400
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
401
+
402
+        $this->registerService('SystemConfig', function ($c) use ($config) {
403
+            return new \OC\SystemConfig($config);
404
+        });
405
+
406
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
407
+            return new \OC\AppConfig($c->getDatabaseConnection());
408
+        });
409
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
410
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
411
+
412
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
413
+            return new \OC\L10N\Factory(
414
+                $c->getConfig(),
415
+                $c->getRequest(),
416
+                $c->getUserSession(),
417
+                \OC::$SERVERROOT
418
+            );
419
+        });
420
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
421
+
422
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
423
+            $config = $c->getConfig();
424
+            $cacheFactory = $c->getMemCacheFactory();
425
+            $request = $c->getRequest();
426
+            return new \OC\URLGenerator(
427
+                $config,
428
+                $cacheFactory,
429
+                $request
430
+            );
431
+        });
432
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
433
+
434
+        $this->registerService('AppHelper', function ($c) {
435
+            return new \OC\AppHelper();
436
+        });
437
+        $this->registerAlias('AppFetcher', AppFetcher::class);
438
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
439
+
440
+        $this->registerService(\OCP\ICache::class, function ($c) {
441
+            return new Cache\File();
442
+        });
443
+        $this->registerAlias('UserCache', \OCP\ICache::class);
444
+
445
+        $this->registerService(Factory::class, function (Server $c) {
446
+
447
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
448
+                '\\OC\\Memcache\\ArrayCache',
449
+                '\\OC\\Memcache\\ArrayCache',
450
+                '\\OC\\Memcache\\ArrayCache'
451
+            );
452
+            $config = $c->getConfig();
453
+            $request = $c->getRequest();
454
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
455
+
456
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
457
+                $v = \OC_App::getAppVersions();
458
+                $v['core'] = implode(',', \OC_Util::getVersion());
459
+                $version = implode(',', $v);
460
+                $instanceId = \OC_Util::getInstanceId();
461
+                $path = \OC::$SERVERROOT;
462
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
463
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
464
+                    $config->getSystemValue('memcache.local', null),
465
+                    $config->getSystemValue('memcache.distributed', null),
466
+                    $config->getSystemValue('memcache.locking', null)
467
+                );
468
+            }
469
+            return $arrayCacheFactory;
470
+
471
+        });
472
+        $this->registerAlias('MemCacheFactory', Factory::class);
473
+        $this->registerAlias(ICacheFactory::class, Factory::class);
474
+
475
+        $this->registerService('RedisFactory', function (Server $c) {
476
+            $systemConfig = $c->getSystemConfig();
477
+            return new RedisFactory($systemConfig);
478
+        });
479
+
480
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
481
+            return new \OC\Activity\Manager(
482
+                $c->getRequest(),
483
+                $c->getUserSession(),
484
+                $c->getConfig(),
485
+                $c->query(IValidator::class)
486
+            );
487
+        });
488
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
489
+
490
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
491
+            return new \OC\Activity\EventMerger(
492
+                $c->getL10N('lib')
493
+            );
494
+        });
495
+        $this->registerAlias(IValidator::class, Validator::class);
496
+
497
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
498
+            return new AvatarManager(
499
+                $c->getUserManager(),
500
+                $c->getAppDataDir('avatar'),
501
+                $c->getL10N('lib'),
502
+                $c->getLogger(),
503
+                $c->getConfig()
504
+            );
505
+        });
506
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
507
+
508
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
509
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
510
+            $logger = Log::getLogClass($logType);
511
+            call_user_func(array($logger, 'init'));
512
+
513
+            return new Log($logger);
514
+        });
515
+        $this->registerAlias('Logger', \OCP\ILogger::class);
516
+
517
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
518
+            $config = $c->getConfig();
519
+            return new \OC\BackgroundJob\JobList(
520
+                $c->getDatabaseConnection(),
521
+                $config,
522
+                new TimeFactory()
523
+            );
524
+        });
525
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
526
+
527
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
528
+            $cacheFactory = $c->getMemCacheFactory();
529
+            $logger = $c->getLogger();
530
+            if ($cacheFactory->isAvailable()) {
531
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
532
+            } else {
533
+                $router = new \OC\Route\Router($logger);
534
+            }
535
+            return $router;
536
+        });
537
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
538
+
539
+        $this->registerService(\OCP\ISearch::class, function ($c) {
540
+            return new Search();
541
+        });
542
+        $this->registerAlias('Search', \OCP\ISearch::class);
543
+
544
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
545
+            return new \OC\Security\RateLimiting\Limiter(
546
+                $this->getUserSession(),
547
+                $this->getRequest(),
548
+                new \OC\AppFramework\Utility\TimeFactory(),
549
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
550
+            );
551
+        });
552
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
553
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
554
+                $this->getMemCacheFactory(),
555
+                new \OC\AppFramework\Utility\TimeFactory()
556
+            );
557
+        });
558
+
559
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
560
+            return new SecureRandom();
561
+        });
562
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
563
+
564
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
565
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
566
+        });
567
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
568
+
569
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
570
+            return new Hasher($c->getConfig());
571
+        });
572
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
573
+
574
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
575
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
576
+        });
577
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
578
+
579
+        $this->registerService(IDBConnection::class, function (Server $c) {
580
+            $systemConfig = $c->getSystemConfig();
581
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
582
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
583
+            if (!$factory->isValidType($type)) {
584
+                throw new \OC\DatabaseException('Invalid database type');
585
+            }
586
+            $connectionParams = $factory->createConnectionParams();
587
+            $connection = $factory->getConnection($type, $connectionParams);
588
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
589
+            return $connection;
590
+        });
591
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
592
+
593
+        $this->registerService('HTTPHelper', function (Server $c) {
594
+            $config = $c->getConfig();
595
+            return new HTTPHelper(
596
+                $config,
597
+                $c->getHTTPClientService()
598
+            );
599
+        });
600
+
601
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
602
+            $user = \OC_User::getUser();
603
+            $uid = $user ? $user : null;
604
+            return new ClientService(
605
+                $c->getConfig(),
606
+                new \OC\Security\CertificateManager(
607
+                    $uid,
608
+                    new View(),
609
+                    $c->getConfig(),
610
+                    $c->getLogger(),
611
+                    $c->getSecureRandom()
612
+                )
613
+            );
614
+        });
615
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
616
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
617
+            $eventLogger = new EventLogger();
618
+            if ($c->getSystemConfig()->getValue('debug', false)) {
619
+                // In debug mode, module is being activated by default
620
+                $eventLogger->activate();
621
+            }
622
+            return $eventLogger;
623
+        });
624
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
625
+
626
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
627
+            $queryLogger = new QueryLogger();
628
+            if ($c->getSystemConfig()->getValue('debug', false)) {
629
+                // In debug mode, module is being activated by default
630
+                $queryLogger->activate();
631
+            }
632
+            return $queryLogger;
633
+        });
634
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
635
+
636
+        $this->registerService(TempManager::class, function (Server $c) {
637
+            return new TempManager(
638
+                $c->getLogger(),
639
+                $c->getConfig()
640
+            );
641
+        });
642
+        $this->registerAlias('TempManager', TempManager::class);
643
+        $this->registerAlias(ITempManager::class, TempManager::class);
644
+
645
+        $this->registerService(AppManager::class, function (Server $c) {
646
+            return new \OC\App\AppManager(
647
+                $c->getUserSession(),
648
+                $c->getAppConfig(),
649
+                $c->getGroupManager(),
650
+                $c->getMemCacheFactory(),
651
+                $c->getEventDispatcher()
652
+            );
653
+        });
654
+        $this->registerAlias('AppManager', AppManager::class);
655
+        $this->registerAlias(IAppManager::class, AppManager::class);
656
+
657
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
658
+            return new DateTimeZone(
659
+                $c->getConfig(),
660
+                $c->getSession()
661
+            );
662
+        });
663
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
664
+
665
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
666
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
667
+
668
+            return new DateTimeFormatter(
669
+                $c->getDateTimeZone()->getTimeZone(),
670
+                $c->getL10N('lib', $language)
671
+            );
672
+        });
673
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
674
+
675
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
676
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
677
+            $listener = new UserMountCacheListener($mountCache);
678
+            $listener->listen($c->getUserManager());
679
+            return $mountCache;
680
+        });
681
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
682
+
683
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
684
+            $loader = \OC\Files\Filesystem::getLoader();
685
+            $mountCache = $c->query('UserMountCache');
686
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
687
+
688
+            // builtin providers
689
+
690
+            $config = $c->getConfig();
691
+            $manager->registerProvider(new CacheMountProvider($config));
692
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
693
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
694
+
695
+            return $manager;
696
+        });
697
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
698
+
699
+        $this->registerService('IniWrapper', function ($c) {
700
+            return new IniGetWrapper();
701
+        });
702
+        $this->registerService('AsyncCommandBus', function (Server $c) {
703
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
704
+            if ($busClass) {
705
+                list($app, $class) = explode('::', $busClass, 2);
706
+                if ($c->getAppManager()->isInstalled($app)) {
707
+                    \OC_App::loadApp($app);
708
+                    return $c->query($class);
709
+                } else {
710
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
711
+                }
712
+            } else {
713
+                $jobList = $c->getJobList();
714
+                return new CronBus($jobList);
715
+            }
716
+        });
717
+        $this->registerService('TrustedDomainHelper', function ($c) {
718
+            return new TrustedDomainHelper($this->getConfig());
719
+        });
720
+        $this->registerService('Throttler', function (Server $c) {
721
+            return new Throttler(
722
+                $c->getDatabaseConnection(),
723
+                new TimeFactory(),
724
+                $c->getLogger(),
725
+                $c->getConfig()
726
+            );
727
+        });
728
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
729
+            // IConfig and IAppManager requires a working database. This code
730
+            // might however be called when ownCloud is not yet setup.
731
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
732
+                $config = $c->getConfig();
733
+                $appManager = $c->getAppManager();
734
+            } else {
735
+                $config = null;
736
+                $appManager = null;
737
+            }
738
+
739
+            return new Checker(
740
+                new EnvironmentHelper(),
741
+                new FileAccessHelper(),
742
+                new AppLocator(),
743
+                $config,
744
+                $c->getMemCacheFactory(),
745
+                $appManager,
746
+                $c->getTempManager()
747
+            );
748
+        });
749
+        $this->registerService(\OCP\IRequest::class, function ($c) {
750
+            if (isset($this['urlParams'])) {
751
+                $urlParams = $this['urlParams'];
752
+            } else {
753
+                $urlParams = [];
754
+            }
755
+
756
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
757
+                && in_array('fakeinput', stream_get_wrappers())
758
+            ) {
759
+                $stream = 'fakeinput://data';
760
+            } else {
761
+                $stream = 'php://input';
762
+            }
763
+
764
+            return new Request(
765
+                [
766
+                    'get' => $_GET,
767
+                    'post' => $_POST,
768
+                    'files' => $_FILES,
769
+                    'server' => $_SERVER,
770
+                    'env' => $_ENV,
771
+                    'cookies' => $_COOKIE,
772
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
773
+                        ? $_SERVER['REQUEST_METHOD']
774
+                        : null,
775
+                    'urlParams' => $urlParams,
776
+                ],
777
+                $this->getSecureRandom(),
778
+                $this->getConfig(),
779
+                $this->getCsrfTokenManager(),
780
+                $stream
781
+            );
782
+        });
783
+        $this->registerAlias('Request', \OCP\IRequest::class);
784
+
785
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
786
+            return new Mailer(
787
+                $c->getConfig(),
788
+                $c->getLogger(),
789
+                $c->query(Defaults::class),
790
+                $c->getURLGenerator(),
791
+                $c->getL10N('lib')
792
+            );
793
+        });
794
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
795
+
796
+        $this->registerService('LDAPProvider', function (Server $c) {
797
+            $config = $c->getConfig();
798
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
799
+            if (is_null($factoryClass)) {
800
+                throw new \Exception('ldapProviderFactory not set');
801
+            }
802
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
803
+            $factory = new $factoryClass($this);
804
+            return $factory->getLDAPProvider();
805
+        });
806
+        $this->registerService(ILockingProvider::class, function (Server $c) {
807
+            $ini = $c->getIniWrapper();
808
+            $config = $c->getConfig();
809
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
810
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
811
+                /** @var \OC\Memcache\Factory $memcacheFactory */
812
+                $memcacheFactory = $c->getMemCacheFactory();
813
+                $memcache = $memcacheFactory->createLocking('lock');
814
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
815
+                    return new MemcacheLockingProvider($memcache, $ttl);
816
+                }
817
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
818
+            }
819
+            return new NoopLockingProvider();
820
+        });
821
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
822
+
823
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
824
+            return new \OC\Files\Mount\Manager();
825
+        });
826
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
827
+
828
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
829
+            return new \OC\Files\Type\Detection(
830
+                $c->getURLGenerator(),
831
+                \OC::$configDir,
832
+                \OC::$SERVERROOT . '/resources/config/'
833
+            );
834
+        });
835
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
836
+
837
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
838
+            return new \OC\Files\Type\Loader(
839
+                $c->getDatabaseConnection()
840
+            );
841
+        });
842
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
843
+        $this->registerService(BundleFetcher::class, function () {
844
+            return new BundleFetcher($this->getL10N('lib'));
845
+        });
846
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
847
+            return new Manager(
848
+                $c->query(IValidator::class)
849
+            );
850
+        });
851
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
852
+
853
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
854
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
855
+            $manager->registerCapability(function () use ($c) {
856
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
857
+            });
858
+            $manager->registerCapability(function () use ($c) {
859
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
860
+            });
861
+            return $manager;
862
+        });
863
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
864
+
865
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
866
+            $config = $c->getConfig();
867
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
868
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
869
+            $factory = new $factoryClass($this);
870
+            return $factory->getManager();
871
+        });
872
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
873
+
874
+        $this->registerService('ThemingDefaults', function (Server $c) {
875
+            /*
876 876
 			 * Dark magic for autoloader.
877 877
 			 * If we do a class_exists it will try to load the class which will
878 878
 			 * make composer cache the result. Resulting in errors when enabling
879 879
 			 * the theming app.
880 880
 			 */
881
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
882
-			if (isset($prefixes['OCA\\Theming\\'])) {
883
-				$classExists = true;
884
-			} else {
885
-				$classExists = false;
886
-			}
887
-
888
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
889
-				return new ThemingDefaults(
890
-					$c->getConfig(),
891
-					$c->getL10N('theming'),
892
-					$c->getURLGenerator(),
893
-					$c->getAppDataDir('theming'),
894
-					$c->getMemCacheFactory(),
895
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming'))
896
-				);
897
-			}
898
-			return new \OC_Defaults();
899
-		});
900
-		$this->registerService(SCSSCacher::class, function (Server $c) {
901
-			/** @var Factory $cacheFactory */
902
-			$cacheFactory = $c->query(Factory::class);
903
-			return new SCSSCacher(
904
-				$c->getLogger(),
905
-				$c->query(\OC\Files\AppData\Factory::class),
906
-				$c->getURLGenerator(),
907
-				$c->getConfig(),
908
-				$c->getThemingDefaults(),
909
-				\OC::$SERVERROOT,
910
-				$cacheFactory->create('SCSS')
911
-			);
912
-		});
913
-		$this->registerService(EventDispatcher::class, function () {
914
-			return new EventDispatcher();
915
-		});
916
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
917
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
918
-
919
-		$this->registerService('CryptoWrapper', function (Server $c) {
920
-			// FIXME: Instantiiated here due to cyclic dependency
921
-			$request = new Request(
922
-				[
923
-					'get' => $_GET,
924
-					'post' => $_POST,
925
-					'files' => $_FILES,
926
-					'server' => $_SERVER,
927
-					'env' => $_ENV,
928
-					'cookies' => $_COOKIE,
929
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
930
-						? $_SERVER['REQUEST_METHOD']
931
-						: null,
932
-				],
933
-				$c->getSecureRandom(),
934
-				$c->getConfig()
935
-			);
936
-
937
-			return new CryptoWrapper(
938
-				$c->getConfig(),
939
-				$c->getCrypto(),
940
-				$c->getSecureRandom(),
941
-				$request
942
-			);
943
-		});
944
-		$this->registerService('CsrfTokenManager', function (Server $c) {
945
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
946
-
947
-			return new CsrfTokenManager(
948
-				$tokenGenerator,
949
-				$c->query(SessionStorage::class)
950
-			);
951
-		});
952
-		$this->registerService(SessionStorage::class, function (Server $c) {
953
-			return new SessionStorage($c->getSession());
954
-		});
955
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
956
-			return new ContentSecurityPolicyManager();
957
-		});
958
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
959
-
960
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
961
-			return new ContentSecurityPolicyNonceManager(
962
-				$c->getCsrfTokenManager(),
963
-				$c->getRequest()
964
-			);
965
-		});
966
-
967
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
968
-			$config = $c->getConfig();
969
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
970
-			/** @var \OCP\Share\IProviderFactory $factory */
971
-			$factory = new $factoryClass($this);
972
-
973
-			$manager = new \OC\Share20\Manager(
974
-				$c->getLogger(),
975
-				$c->getConfig(),
976
-				$c->getSecureRandom(),
977
-				$c->getHasher(),
978
-				$c->getMountManager(),
979
-				$c->getGroupManager(),
980
-				$c->getL10N('lib'),
981
-				$c->getL10NFactory(),
982
-				$factory,
983
-				$c->getUserManager(),
984
-				$c->getLazyRootFolder(),
985
-				$c->getEventDispatcher(),
986
-				$c->getMailer(),
987
-				$c->getURLGenerator(),
988
-				$c->getThemingDefaults()
989
-			);
990
-
991
-			return $manager;
992
-		});
993
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
994
-
995
-		$this->registerService('SettingsManager', function (Server $c) {
996
-			$manager = new \OC\Settings\Manager(
997
-				$c->getLogger(),
998
-				$c->getDatabaseConnection(),
999
-				$c->getL10N('lib'),
1000
-				$c->getConfig(),
1001
-				$c->getEncryptionManager(),
1002
-				$c->getUserManager(),
1003
-				$c->getLockingProvider(),
1004
-				$c->getRequest(),
1005
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1006
-				$c->getURLGenerator(),
1007
-				$c->query(AccountManager::class),
1008
-				$c->getGroupManager(),
1009
-				$c->getL10NFactory(),
1010
-				$c->getThemingDefaults(),
1011
-				$c->getAppManager()
1012
-			);
1013
-			return $manager;
1014
-		});
1015
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1016
-			return new \OC\Files\AppData\Factory(
1017
-				$c->getRootFolder(),
1018
-				$c->getSystemConfig()
1019
-			);
1020
-		});
1021
-
1022
-		$this->registerService('LockdownManager', function (Server $c) {
1023
-			return new LockdownManager(function () use ($c) {
1024
-				return $c->getSession();
1025
-			});
1026
-		});
1027
-
1028
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1029
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1030
-		});
1031
-
1032
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1033
-			return new CloudIdManager();
1034
-		});
1035
-
1036
-		/* To trick DI since we don't extend the DIContainer here */
1037
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1038
-			return new CleanPreviewsBackgroundJob(
1039
-				$c->getRootFolder(),
1040
-				$c->getLogger(),
1041
-				$c->getJobList(),
1042
-				new TimeFactory()
1043
-			);
1044
-		});
1045
-
1046
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1047
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1048
-
1049
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1050
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1051
-
1052
-		$this->registerService(Defaults::class, function (Server $c) {
1053
-			return new Defaults(
1054
-				$c->getThemingDefaults()
1055
-			);
1056
-		});
1057
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1058
-
1059
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1060
-			return $c->query(\OCP\IUserSession::class)->getSession();
1061
-		});
1062
-
1063
-		$this->registerService(IShareHelper::class, function (Server $c) {
1064
-			return new ShareHelper(
1065
-				$c->query(\OCP\Share\IManager::class)
1066
-			);
1067
-		});
1068
-	}
1069
-
1070
-	/**
1071
-	 * @return \OCP\Contacts\IManager
1072
-	 */
1073
-	public function getContactsManager() {
1074
-		return $this->query('ContactsManager');
1075
-	}
1076
-
1077
-	/**
1078
-	 * @return \OC\Encryption\Manager
1079
-	 */
1080
-	public function getEncryptionManager() {
1081
-		return $this->query('EncryptionManager');
1082
-	}
1083
-
1084
-	/**
1085
-	 * @return \OC\Encryption\File
1086
-	 */
1087
-	public function getEncryptionFilesHelper() {
1088
-		return $this->query('EncryptionFileHelper');
1089
-	}
1090
-
1091
-	/**
1092
-	 * @return \OCP\Encryption\Keys\IStorage
1093
-	 */
1094
-	public function getEncryptionKeyStorage() {
1095
-		return $this->query('EncryptionKeyStorage');
1096
-	}
1097
-
1098
-	/**
1099
-	 * The current request object holding all information about the request
1100
-	 * currently being processed is returned from this method.
1101
-	 * In case the current execution was not initiated by a web request null is returned
1102
-	 *
1103
-	 * @return \OCP\IRequest
1104
-	 */
1105
-	public function getRequest() {
1106
-		return $this->query('Request');
1107
-	}
1108
-
1109
-	/**
1110
-	 * Returns the preview manager which can create preview images for a given file
1111
-	 *
1112
-	 * @return \OCP\IPreview
1113
-	 */
1114
-	public function getPreviewManager() {
1115
-		return $this->query('PreviewManager');
1116
-	}
1117
-
1118
-	/**
1119
-	 * Returns the tag manager which can get and set tags for different object types
1120
-	 *
1121
-	 * @see \OCP\ITagManager::load()
1122
-	 * @return \OCP\ITagManager
1123
-	 */
1124
-	public function getTagManager() {
1125
-		return $this->query('TagManager');
1126
-	}
1127
-
1128
-	/**
1129
-	 * Returns the system-tag manager
1130
-	 *
1131
-	 * @return \OCP\SystemTag\ISystemTagManager
1132
-	 *
1133
-	 * @since 9.0.0
1134
-	 */
1135
-	public function getSystemTagManager() {
1136
-		return $this->query('SystemTagManager');
1137
-	}
1138
-
1139
-	/**
1140
-	 * Returns the system-tag object mapper
1141
-	 *
1142
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1143
-	 *
1144
-	 * @since 9.0.0
1145
-	 */
1146
-	public function getSystemTagObjectMapper() {
1147
-		return $this->query('SystemTagObjectMapper');
1148
-	}
1149
-
1150
-	/**
1151
-	 * Returns the avatar manager, used for avatar functionality
1152
-	 *
1153
-	 * @return \OCP\IAvatarManager
1154
-	 */
1155
-	public function getAvatarManager() {
1156
-		return $this->query('AvatarManager');
1157
-	}
1158
-
1159
-	/**
1160
-	 * Returns the root folder of ownCloud's data directory
1161
-	 *
1162
-	 * @return \OCP\Files\IRootFolder
1163
-	 */
1164
-	public function getRootFolder() {
1165
-		return $this->query('LazyRootFolder');
1166
-	}
1167
-
1168
-	/**
1169
-	 * Returns the root folder of ownCloud's data directory
1170
-	 * This is the lazy variant so this gets only initialized once it
1171
-	 * is actually used.
1172
-	 *
1173
-	 * @return \OCP\Files\IRootFolder
1174
-	 */
1175
-	public function getLazyRootFolder() {
1176
-		return $this->query('LazyRootFolder');
1177
-	}
1178
-
1179
-	/**
1180
-	 * Returns a view to ownCloud's files folder
1181
-	 *
1182
-	 * @param string $userId user ID
1183
-	 * @return \OCP\Files\Folder|null
1184
-	 */
1185
-	public function getUserFolder($userId = null) {
1186
-		if ($userId === null) {
1187
-			$user = $this->getUserSession()->getUser();
1188
-			if (!$user) {
1189
-				return null;
1190
-			}
1191
-			$userId = $user->getUID();
1192
-		}
1193
-		$root = $this->getRootFolder();
1194
-		return $root->getUserFolder($userId);
1195
-	}
1196
-
1197
-	/**
1198
-	 * Returns an app-specific view in ownClouds data directory
1199
-	 *
1200
-	 * @return \OCP\Files\Folder
1201
-	 * @deprecated since 9.2.0 use IAppData
1202
-	 */
1203
-	public function getAppFolder() {
1204
-		$dir = '/' . \OC_App::getCurrentApp();
1205
-		$root = $this->getRootFolder();
1206
-		if (!$root->nodeExists($dir)) {
1207
-			$folder = $root->newFolder($dir);
1208
-		} else {
1209
-			$folder = $root->get($dir);
1210
-		}
1211
-		return $folder;
1212
-	}
1213
-
1214
-	/**
1215
-	 * @return \OC\User\Manager
1216
-	 */
1217
-	public function getUserManager() {
1218
-		return $this->query('UserManager');
1219
-	}
1220
-
1221
-	/**
1222
-	 * @return \OC\Group\Manager
1223
-	 */
1224
-	public function getGroupManager() {
1225
-		return $this->query('GroupManager');
1226
-	}
1227
-
1228
-	/**
1229
-	 * @return \OC\User\Session
1230
-	 */
1231
-	public function getUserSession() {
1232
-		return $this->query('UserSession');
1233
-	}
1234
-
1235
-	/**
1236
-	 * @return \OCP\ISession
1237
-	 */
1238
-	public function getSession() {
1239
-		return $this->query('UserSession')->getSession();
1240
-	}
1241
-
1242
-	/**
1243
-	 * @param \OCP\ISession $session
1244
-	 */
1245
-	public function setSession(\OCP\ISession $session) {
1246
-		$this->query(SessionStorage::class)->setSession($session);
1247
-		$this->query('UserSession')->setSession($session);
1248
-		$this->query(Store::class)->setSession($session);
1249
-	}
1250
-
1251
-	/**
1252
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1253
-	 */
1254
-	public function getTwoFactorAuthManager() {
1255
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1256
-	}
1257
-
1258
-	/**
1259
-	 * @return \OC\NavigationManager
1260
-	 */
1261
-	public function getNavigationManager() {
1262
-		return $this->query('NavigationManager');
1263
-	}
1264
-
1265
-	/**
1266
-	 * @return \OCP\IConfig
1267
-	 */
1268
-	public function getConfig() {
1269
-		return $this->query('AllConfig');
1270
-	}
1271
-
1272
-	/**
1273
-	 * @return \OC\SystemConfig
1274
-	 */
1275
-	public function getSystemConfig() {
1276
-		return $this->query('SystemConfig');
1277
-	}
1278
-
1279
-	/**
1280
-	 * Returns the app config manager
1281
-	 *
1282
-	 * @return \OCP\IAppConfig
1283
-	 */
1284
-	public function getAppConfig() {
1285
-		return $this->query('AppConfig');
1286
-	}
1287
-
1288
-	/**
1289
-	 * @return \OCP\L10N\IFactory
1290
-	 */
1291
-	public function getL10NFactory() {
1292
-		return $this->query('L10NFactory');
1293
-	}
1294
-
1295
-	/**
1296
-	 * get an L10N instance
1297
-	 *
1298
-	 * @param string $app appid
1299
-	 * @param string $lang
1300
-	 * @return IL10N
1301
-	 */
1302
-	public function getL10N($app, $lang = null) {
1303
-		return $this->getL10NFactory()->get($app, $lang);
1304
-	}
1305
-
1306
-	/**
1307
-	 * @return \OCP\IURLGenerator
1308
-	 */
1309
-	public function getURLGenerator() {
1310
-		return $this->query('URLGenerator');
1311
-	}
1312
-
1313
-	/**
1314
-	 * @return \OCP\IHelper
1315
-	 */
1316
-	public function getHelper() {
1317
-		return $this->query('AppHelper');
1318
-	}
1319
-
1320
-	/**
1321
-	 * @return AppFetcher
1322
-	 */
1323
-	public function getAppFetcher() {
1324
-		return $this->query(AppFetcher::class);
1325
-	}
1326
-
1327
-	/**
1328
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1329
-	 * getMemCacheFactory() instead.
1330
-	 *
1331
-	 * @return \OCP\ICache
1332
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1333
-	 */
1334
-	public function getCache() {
1335
-		return $this->query('UserCache');
1336
-	}
1337
-
1338
-	/**
1339
-	 * Returns an \OCP\CacheFactory instance
1340
-	 *
1341
-	 * @return \OCP\ICacheFactory
1342
-	 */
1343
-	public function getMemCacheFactory() {
1344
-		return $this->query('MemCacheFactory');
1345
-	}
1346
-
1347
-	/**
1348
-	 * Returns an \OC\RedisFactory instance
1349
-	 *
1350
-	 * @return \OC\RedisFactory
1351
-	 */
1352
-	public function getGetRedisFactory() {
1353
-		return $this->query('RedisFactory');
1354
-	}
1355
-
1356
-
1357
-	/**
1358
-	 * Returns the current session
1359
-	 *
1360
-	 * @return \OCP\IDBConnection
1361
-	 */
1362
-	public function getDatabaseConnection() {
1363
-		return $this->query('DatabaseConnection');
1364
-	}
1365
-
1366
-	/**
1367
-	 * Returns the activity manager
1368
-	 *
1369
-	 * @return \OCP\Activity\IManager
1370
-	 */
1371
-	public function getActivityManager() {
1372
-		return $this->query('ActivityManager');
1373
-	}
1374
-
1375
-	/**
1376
-	 * Returns an job list for controlling background jobs
1377
-	 *
1378
-	 * @return \OCP\BackgroundJob\IJobList
1379
-	 */
1380
-	public function getJobList() {
1381
-		return $this->query('JobList');
1382
-	}
1383
-
1384
-	/**
1385
-	 * Returns a logger instance
1386
-	 *
1387
-	 * @return \OCP\ILogger
1388
-	 */
1389
-	public function getLogger() {
1390
-		return $this->query('Logger');
1391
-	}
1392
-
1393
-	/**
1394
-	 * Returns a router for generating and matching urls
1395
-	 *
1396
-	 * @return \OCP\Route\IRouter
1397
-	 */
1398
-	public function getRouter() {
1399
-		return $this->query('Router');
1400
-	}
1401
-
1402
-	/**
1403
-	 * Returns a search instance
1404
-	 *
1405
-	 * @return \OCP\ISearch
1406
-	 */
1407
-	public function getSearch() {
1408
-		return $this->query('Search');
1409
-	}
1410
-
1411
-	/**
1412
-	 * Returns a SecureRandom instance
1413
-	 *
1414
-	 * @return \OCP\Security\ISecureRandom
1415
-	 */
1416
-	public function getSecureRandom() {
1417
-		return $this->query('SecureRandom');
1418
-	}
1419
-
1420
-	/**
1421
-	 * Returns a Crypto instance
1422
-	 *
1423
-	 * @return \OCP\Security\ICrypto
1424
-	 */
1425
-	public function getCrypto() {
1426
-		return $this->query('Crypto');
1427
-	}
1428
-
1429
-	/**
1430
-	 * Returns a Hasher instance
1431
-	 *
1432
-	 * @return \OCP\Security\IHasher
1433
-	 */
1434
-	public function getHasher() {
1435
-		return $this->query('Hasher');
1436
-	}
1437
-
1438
-	/**
1439
-	 * Returns a CredentialsManager instance
1440
-	 *
1441
-	 * @return \OCP\Security\ICredentialsManager
1442
-	 */
1443
-	public function getCredentialsManager() {
1444
-		return $this->query('CredentialsManager');
1445
-	}
1446
-
1447
-	/**
1448
-	 * Returns an instance of the HTTP helper class
1449
-	 *
1450
-	 * @deprecated Use getHTTPClientService()
1451
-	 * @return \OC\HTTPHelper
1452
-	 */
1453
-	public function getHTTPHelper() {
1454
-		return $this->query('HTTPHelper');
1455
-	}
1456
-
1457
-	/**
1458
-	 * Get the certificate manager for the user
1459
-	 *
1460
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1461
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1462
-	 */
1463
-	public function getCertificateManager($userId = '') {
1464
-		if ($userId === '') {
1465
-			$userSession = $this->getUserSession();
1466
-			$user = $userSession->getUser();
1467
-			if (is_null($user)) {
1468
-				return null;
1469
-			}
1470
-			$userId = $user->getUID();
1471
-		}
1472
-		return new CertificateManager(
1473
-			$userId,
1474
-			new View(),
1475
-			$this->getConfig(),
1476
-			$this->getLogger(),
1477
-			$this->getSecureRandom()
1478
-		);
1479
-	}
1480
-
1481
-	/**
1482
-	 * Returns an instance of the HTTP client service
1483
-	 *
1484
-	 * @return \OCP\Http\Client\IClientService
1485
-	 */
1486
-	public function getHTTPClientService() {
1487
-		return $this->query('HttpClientService');
1488
-	}
1489
-
1490
-	/**
1491
-	 * Create a new event source
1492
-	 *
1493
-	 * @return \OCP\IEventSource
1494
-	 */
1495
-	public function createEventSource() {
1496
-		return new \OC_EventSource();
1497
-	}
1498
-
1499
-	/**
1500
-	 * Get the active event logger
1501
-	 *
1502
-	 * The returned logger only logs data when debug mode is enabled
1503
-	 *
1504
-	 * @return \OCP\Diagnostics\IEventLogger
1505
-	 */
1506
-	public function getEventLogger() {
1507
-		return $this->query('EventLogger');
1508
-	}
1509
-
1510
-	/**
1511
-	 * Get the active query logger
1512
-	 *
1513
-	 * The returned logger only logs data when debug mode is enabled
1514
-	 *
1515
-	 * @return \OCP\Diagnostics\IQueryLogger
1516
-	 */
1517
-	public function getQueryLogger() {
1518
-		return $this->query('QueryLogger');
1519
-	}
1520
-
1521
-	/**
1522
-	 * Get the manager for temporary files and folders
1523
-	 *
1524
-	 * @return \OCP\ITempManager
1525
-	 */
1526
-	public function getTempManager() {
1527
-		return $this->query('TempManager');
1528
-	}
1529
-
1530
-	/**
1531
-	 * Get the app manager
1532
-	 *
1533
-	 * @return \OCP\App\IAppManager
1534
-	 */
1535
-	public function getAppManager() {
1536
-		return $this->query('AppManager');
1537
-	}
1538
-
1539
-	/**
1540
-	 * Creates a new mailer
1541
-	 *
1542
-	 * @return \OCP\Mail\IMailer
1543
-	 */
1544
-	public function getMailer() {
1545
-		return $this->query('Mailer');
1546
-	}
1547
-
1548
-	/**
1549
-	 * Get the webroot
1550
-	 *
1551
-	 * @return string
1552
-	 */
1553
-	public function getWebRoot() {
1554
-		return $this->webRoot;
1555
-	}
1556
-
1557
-	/**
1558
-	 * @return \OC\OCSClient
1559
-	 */
1560
-	public function getOcsClient() {
1561
-		return $this->query('OcsClient');
1562
-	}
1563
-
1564
-	/**
1565
-	 * @return \OCP\IDateTimeZone
1566
-	 */
1567
-	public function getDateTimeZone() {
1568
-		return $this->query('DateTimeZone');
1569
-	}
1570
-
1571
-	/**
1572
-	 * @return \OCP\IDateTimeFormatter
1573
-	 */
1574
-	public function getDateTimeFormatter() {
1575
-		return $this->query('DateTimeFormatter');
1576
-	}
1577
-
1578
-	/**
1579
-	 * @return \OCP\Files\Config\IMountProviderCollection
1580
-	 */
1581
-	public function getMountProviderCollection() {
1582
-		return $this->query('MountConfigManager');
1583
-	}
1584
-
1585
-	/**
1586
-	 * Get the IniWrapper
1587
-	 *
1588
-	 * @return IniGetWrapper
1589
-	 */
1590
-	public function getIniWrapper() {
1591
-		return $this->query('IniWrapper');
1592
-	}
1593
-
1594
-	/**
1595
-	 * @return \OCP\Command\IBus
1596
-	 */
1597
-	public function getCommandBus() {
1598
-		return $this->query('AsyncCommandBus');
1599
-	}
1600
-
1601
-	/**
1602
-	 * Get the trusted domain helper
1603
-	 *
1604
-	 * @return TrustedDomainHelper
1605
-	 */
1606
-	public function getTrustedDomainHelper() {
1607
-		return $this->query('TrustedDomainHelper');
1608
-	}
1609
-
1610
-	/**
1611
-	 * Get the locking provider
1612
-	 *
1613
-	 * @return \OCP\Lock\ILockingProvider
1614
-	 * @since 8.1.0
1615
-	 */
1616
-	public function getLockingProvider() {
1617
-		return $this->query('LockingProvider');
1618
-	}
1619
-
1620
-	/**
1621
-	 * @return \OCP\Files\Mount\IMountManager
1622
-	 **/
1623
-	function getMountManager() {
1624
-		return $this->query('MountManager');
1625
-	}
1626
-
1627
-	/** @return \OCP\Files\Config\IUserMountCache */
1628
-	function getUserMountCache() {
1629
-		return $this->query('UserMountCache');
1630
-	}
1631
-
1632
-	/**
1633
-	 * Get the MimeTypeDetector
1634
-	 *
1635
-	 * @return \OCP\Files\IMimeTypeDetector
1636
-	 */
1637
-	public function getMimeTypeDetector() {
1638
-		return $this->query('MimeTypeDetector');
1639
-	}
1640
-
1641
-	/**
1642
-	 * Get the MimeTypeLoader
1643
-	 *
1644
-	 * @return \OCP\Files\IMimeTypeLoader
1645
-	 */
1646
-	public function getMimeTypeLoader() {
1647
-		return $this->query('MimeTypeLoader');
1648
-	}
1649
-
1650
-	/**
1651
-	 * Get the manager of all the capabilities
1652
-	 *
1653
-	 * @return \OC\CapabilitiesManager
1654
-	 */
1655
-	public function getCapabilitiesManager() {
1656
-		return $this->query('CapabilitiesManager');
1657
-	}
1658
-
1659
-	/**
1660
-	 * Get the EventDispatcher
1661
-	 *
1662
-	 * @return EventDispatcherInterface
1663
-	 * @since 8.2.0
1664
-	 */
1665
-	public function getEventDispatcher() {
1666
-		return $this->query('EventDispatcher');
1667
-	}
1668
-
1669
-	/**
1670
-	 * Get the Notification Manager
1671
-	 *
1672
-	 * @return \OCP\Notification\IManager
1673
-	 * @since 8.2.0
1674
-	 */
1675
-	public function getNotificationManager() {
1676
-		return $this->query('NotificationManager');
1677
-	}
1678
-
1679
-	/**
1680
-	 * @return \OCP\Comments\ICommentsManager
1681
-	 */
1682
-	public function getCommentsManager() {
1683
-		return $this->query('CommentsManager');
1684
-	}
1685
-
1686
-	/**
1687
-	 * @return \OCA\Theming\ThemingDefaults
1688
-	 */
1689
-	public function getThemingDefaults() {
1690
-		return $this->query('ThemingDefaults');
1691
-	}
1692
-
1693
-	/**
1694
-	 * @return \OC\IntegrityCheck\Checker
1695
-	 */
1696
-	public function getIntegrityCodeChecker() {
1697
-		return $this->query('IntegrityCodeChecker');
1698
-	}
1699
-
1700
-	/**
1701
-	 * @return \OC\Session\CryptoWrapper
1702
-	 */
1703
-	public function getSessionCryptoWrapper() {
1704
-		return $this->query('CryptoWrapper');
1705
-	}
1706
-
1707
-	/**
1708
-	 * @return CsrfTokenManager
1709
-	 */
1710
-	public function getCsrfTokenManager() {
1711
-		return $this->query('CsrfTokenManager');
1712
-	}
1713
-
1714
-	/**
1715
-	 * @return Throttler
1716
-	 */
1717
-	public function getBruteForceThrottler() {
1718
-		return $this->query('Throttler');
1719
-	}
1720
-
1721
-	/**
1722
-	 * @return IContentSecurityPolicyManager
1723
-	 */
1724
-	public function getContentSecurityPolicyManager() {
1725
-		return $this->query('ContentSecurityPolicyManager');
1726
-	}
1727
-
1728
-	/**
1729
-	 * @return ContentSecurityPolicyNonceManager
1730
-	 */
1731
-	public function getContentSecurityPolicyNonceManager() {
1732
-		return $this->query('ContentSecurityPolicyNonceManager');
1733
-	}
1734
-
1735
-	/**
1736
-	 * Not a public API as of 8.2, wait for 9.0
1737
-	 *
1738
-	 * @return \OCA\Files_External\Service\BackendService
1739
-	 */
1740
-	public function getStoragesBackendService() {
1741
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1742
-	}
1743
-
1744
-	/**
1745
-	 * Not a public API as of 8.2, wait for 9.0
1746
-	 *
1747
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1748
-	 */
1749
-	public function getGlobalStoragesService() {
1750
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1751
-	}
1752
-
1753
-	/**
1754
-	 * Not a public API as of 8.2, wait for 9.0
1755
-	 *
1756
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1757
-	 */
1758
-	public function getUserGlobalStoragesService() {
1759
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1760
-	}
1761
-
1762
-	/**
1763
-	 * Not a public API as of 8.2, wait for 9.0
1764
-	 *
1765
-	 * @return \OCA\Files_External\Service\UserStoragesService
1766
-	 */
1767
-	public function getUserStoragesService() {
1768
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1769
-	}
1770
-
1771
-	/**
1772
-	 * @return \OCP\Share\IManager
1773
-	 */
1774
-	public function getShareManager() {
1775
-		return $this->query('ShareManager');
1776
-	}
1777
-
1778
-	/**
1779
-	 * Returns the LDAP Provider
1780
-	 *
1781
-	 * @return \OCP\LDAP\ILDAPProvider
1782
-	 */
1783
-	public function getLDAPProvider() {
1784
-		return $this->query('LDAPProvider');
1785
-	}
1786
-
1787
-	/**
1788
-	 * @return \OCP\Settings\IManager
1789
-	 */
1790
-	public function getSettingsManager() {
1791
-		return $this->query('SettingsManager');
1792
-	}
1793
-
1794
-	/**
1795
-	 * @return \OCP\Files\IAppData
1796
-	 */
1797
-	public function getAppDataDir($app) {
1798
-		/** @var \OC\Files\AppData\Factory $factory */
1799
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1800
-		return $factory->get($app);
1801
-	}
1802
-
1803
-	/**
1804
-	 * @return \OCP\Lockdown\ILockdownManager
1805
-	 */
1806
-	public function getLockdownManager() {
1807
-		return $this->query('LockdownManager');
1808
-	}
1809
-
1810
-	/**
1811
-	 * @return \OCP\Federation\ICloudIdManager
1812
-	 */
1813
-	public function getCloudIdManager() {
1814
-		return $this->query(ICloudIdManager::class);
1815
-	}
881
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
882
+            if (isset($prefixes['OCA\\Theming\\'])) {
883
+                $classExists = true;
884
+            } else {
885
+                $classExists = false;
886
+            }
887
+
888
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
889
+                return new ThemingDefaults(
890
+                    $c->getConfig(),
891
+                    $c->getL10N('theming'),
892
+                    $c->getURLGenerator(),
893
+                    $c->getAppDataDir('theming'),
894
+                    $c->getMemCacheFactory(),
895
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming'))
896
+                );
897
+            }
898
+            return new \OC_Defaults();
899
+        });
900
+        $this->registerService(SCSSCacher::class, function (Server $c) {
901
+            /** @var Factory $cacheFactory */
902
+            $cacheFactory = $c->query(Factory::class);
903
+            return new SCSSCacher(
904
+                $c->getLogger(),
905
+                $c->query(\OC\Files\AppData\Factory::class),
906
+                $c->getURLGenerator(),
907
+                $c->getConfig(),
908
+                $c->getThemingDefaults(),
909
+                \OC::$SERVERROOT,
910
+                $cacheFactory->create('SCSS')
911
+            );
912
+        });
913
+        $this->registerService(EventDispatcher::class, function () {
914
+            return new EventDispatcher();
915
+        });
916
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
917
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
918
+
919
+        $this->registerService('CryptoWrapper', function (Server $c) {
920
+            // FIXME: Instantiiated here due to cyclic dependency
921
+            $request = new Request(
922
+                [
923
+                    'get' => $_GET,
924
+                    'post' => $_POST,
925
+                    'files' => $_FILES,
926
+                    'server' => $_SERVER,
927
+                    'env' => $_ENV,
928
+                    'cookies' => $_COOKIE,
929
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
930
+                        ? $_SERVER['REQUEST_METHOD']
931
+                        : null,
932
+                ],
933
+                $c->getSecureRandom(),
934
+                $c->getConfig()
935
+            );
936
+
937
+            return new CryptoWrapper(
938
+                $c->getConfig(),
939
+                $c->getCrypto(),
940
+                $c->getSecureRandom(),
941
+                $request
942
+            );
943
+        });
944
+        $this->registerService('CsrfTokenManager', function (Server $c) {
945
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
946
+
947
+            return new CsrfTokenManager(
948
+                $tokenGenerator,
949
+                $c->query(SessionStorage::class)
950
+            );
951
+        });
952
+        $this->registerService(SessionStorage::class, function (Server $c) {
953
+            return new SessionStorage($c->getSession());
954
+        });
955
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
956
+            return new ContentSecurityPolicyManager();
957
+        });
958
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
959
+
960
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
961
+            return new ContentSecurityPolicyNonceManager(
962
+                $c->getCsrfTokenManager(),
963
+                $c->getRequest()
964
+            );
965
+        });
966
+
967
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
968
+            $config = $c->getConfig();
969
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
970
+            /** @var \OCP\Share\IProviderFactory $factory */
971
+            $factory = new $factoryClass($this);
972
+
973
+            $manager = new \OC\Share20\Manager(
974
+                $c->getLogger(),
975
+                $c->getConfig(),
976
+                $c->getSecureRandom(),
977
+                $c->getHasher(),
978
+                $c->getMountManager(),
979
+                $c->getGroupManager(),
980
+                $c->getL10N('lib'),
981
+                $c->getL10NFactory(),
982
+                $factory,
983
+                $c->getUserManager(),
984
+                $c->getLazyRootFolder(),
985
+                $c->getEventDispatcher(),
986
+                $c->getMailer(),
987
+                $c->getURLGenerator(),
988
+                $c->getThemingDefaults()
989
+            );
990
+
991
+            return $manager;
992
+        });
993
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
994
+
995
+        $this->registerService('SettingsManager', function (Server $c) {
996
+            $manager = new \OC\Settings\Manager(
997
+                $c->getLogger(),
998
+                $c->getDatabaseConnection(),
999
+                $c->getL10N('lib'),
1000
+                $c->getConfig(),
1001
+                $c->getEncryptionManager(),
1002
+                $c->getUserManager(),
1003
+                $c->getLockingProvider(),
1004
+                $c->getRequest(),
1005
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1006
+                $c->getURLGenerator(),
1007
+                $c->query(AccountManager::class),
1008
+                $c->getGroupManager(),
1009
+                $c->getL10NFactory(),
1010
+                $c->getThemingDefaults(),
1011
+                $c->getAppManager()
1012
+            );
1013
+            return $manager;
1014
+        });
1015
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1016
+            return new \OC\Files\AppData\Factory(
1017
+                $c->getRootFolder(),
1018
+                $c->getSystemConfig()
1019
+            );
1020
+        });
1021
+
1022
+        $this->registerService('LockdownManager', function (Server $c) {
1023
+            return new LockdownManager(function () use ($c) {
1024
+                return $c->getSession();
1025
+            });
1026
+        });
1027
+
1028
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1029
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1030
+        });
1031
+
1032
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1033
+            return new CloudIdManager();
1034
+        });
1035
+
1036
+        /* To trick DI since we don't extend the DIContainer here */
1037
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1038
+            return new CleanPreviewsBackgroundJob(
1039
+                $c->getRootFolder(),
1040
+                $c->getLogger(),
1041
+                $c->getJobList(),
1042
+                new TimeFactory()
1043
+            );
1044
+        });
1045
+
1046
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1047
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1048
+
1049
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1050
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1051
+
1052
+        $this->registerService(Defaults::class, function (Server $c) {
1053
+            return new Defaults(
1054
+                $c->getThemingDefaults()
1055
+            );
1056
+        });
1057
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1058
+
1059
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1060
+            return $c->query(\OCP\IUserSession::class)->getSession();
1061
+        });
1062
+
1063
+        $this->registerService(IShareHelper::class, function (Server $c) {
1064
+            return new ShareHelper(
1065
+                $c->query(\OCP\Share\IManager::class)
1066
+            );
1067
+        });
1068
+    }
1069
+
1070
+    /**
1071
+     * @return \OCP\Contacts\IManager
1072
+     */
1073
+    public function getContactsManager() {
1074
+        return $this->query('ContactsManager');
1075
+    }
1076
+
1077
+    /**
1078
+     * @return \OC\Encryption\Manager
1079
+     */
1080
+    public function getEncryptionManager() {
1081
+        return $this->query('EncryptionManager');
1082
+    }
1083
+
1084
+    /**
1085
+     * @return \OC\Encryption\File
1086
+     */
1087
+    public function getEncryptionFilesHelper() {
1088
+        return $this->query('EncryptionFileHelper');
1089
+    }
1090
+
1091
+    /**
1092
+     * @return \OCP\Encryption\Keys\IStorage
1093
+     */
1094
+    public function getEncryptionKeyStorage() {
1095
+        return $this->query('EncryptionKeyStorage');
1096
+    }
1097
+
1098
+    /**
1099
+     * The current request object holding all information about the request
1100
+     * currently being processed is returned from this method.
1101
+     * In case the current execution was not initiated by a web request null is returned
1102
+     *
1103
+     * @return \OCP\IRequest
1104
+     */
1105
+    public function getRequest() {
1106
+        return $this->query('Request');
1107
+    }
1108
+
1109
+    /**
1110
+     * Returns the preview manager which can create preview images for a given file
1111
+     *
1112
+     * @return \OCP\IPreview
1113
+     */
1114
+    public function getPreviewManager() {
1115
+        return $this->query('PreviewManager');
1116
+    }
1117
+
1118
+    /**
1119
+     * Returns the tag manager which can get and set tags for different object types
1120
+     *
1121
+     * @see \OCP\ITagManager::load()
1122
+     * @return \OCP\ITagManager
1123
+     */
1124
+    public function getTagManager() {
1125
+        return $this->query('TagManager');
1126
+    }
1127
+
1128
+    /**
1129
+     * Returns the system-tag manager
1130
+     *
1131
+     * @return \OCP\SystemTag\ISystemTagManager
1132
+     *
1133
+     * @since 9.0.0
1134
+     */
1135
+    public function getSystemTagManager() {
1136
+        return $this->query('SystemTagManager');
1137
+    }
1138
+
1139
+    /**
1140
+     * Returns the system-tag object mapper
1141
+     *
1142
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1143
+     *
1144
+     * @since 9.0.0
1145
+     */
1146
+    public function getSystemTagObjectMapper() {
1147
+        return $this->query('SystemTagObjectMapper');
1148
+    }
1149
+
1150
+    /**
1151
+     * Returns the avatar manager, used for avatar functionality
1152
+     *
1153
+     * @return \OCP\IAvatarManager
1154
+     */
1155
+    public function getAvatarManager() {
1156
+        return $this->query('AvatarManager');
1157
+    }
1158
+
1159
+    /**
1160
+     * Returns the root folder of ownCloud's data directory
1161
+     *
1162
+     * @return \OCP\Files\IRootFolder
1163
+     */
1164
+    public function getRootFolder() {
1165
+        return $this->query('LazyRootFolder');
1166
+    }
1167
+
1168
+    /**
1169
+     * Returns the root folder of ownCloud's data directory
1170
+     * This is the lazy variant so this gets only initialized once it
1171
+     * is actually used.
1172
+     *
1173
+     * @return \OCP\Files\IRootFolder
1174
+     */
1175
+    public function getLazyRootFolder() {
1176
+        return $this->query('LazyRootFolder');
1177
+    }
1178
+
1179
+    /**
1180
+     * Returns a view to ownCloud's files folder
1181
+     *
1182
+     * @param string $userId user ID
1183
+     * @return \OCP\Files\Folder|null
1184
+     */
1185
+    public function getUserFolder($userId = null) {
1186
+        if ($userId === null) {
1187
+            $user = $this->getUserSession()->getUser();
1188
+            if (!$user) {
1189
+                return null;
1190
+            }
1191
+            $userId = $user->getUID();
1192
+        }
1193
+        $root = $this->getRootFolder();
1194
+        return $root->getUserFolder($userId);
1195
+    }
1196
+
1197
+    /**
1198
+     * Returns an app-specific view in ownClouds data directory
1199
+     *
1200
+     * @return \OCP\Files\Folder
1201
+     * @deprecated since 9.2.0 use IAppData
1202
+     */
1203
+    public function getAppFolder() {
1204
+        $dir = '/' . \OC_App::getCurrentApp();
1205
+        $root = $this->getRootFolder();
1206
+        if (!$root->nodeExists($dir)) {
1207
+            $folder = $root->newFolder($dir);
1208
+        } else {
1209
+            $folder = $root->get($dir);
1210
+        }
1211
+        return $folder;
1212
+    }
1213
+
1214
+    /**
1215
+     * @return \OC\User\Manager
1216
+     */
1217
+    public function getUserManager() {
1218
+        return $this->query('UserManager');
1219
+    }
1220
+
1221
+    /**
1222
+     * @return \OC\Group\Manager
1223
+     */
1224
+    public function getGroupManager() {
1225
+        return $this->query('GroupManager');
1226
+    }
1227
+
1228
+    /**
1229
+     * @return \OC\User\Session
1230
+     */
1231
+    public function getUserSession() {
1232
+        return $this->query('UserSession');
1233
+    }
1234
+
1235
+    /**
1236
+     * @return \OCP\ISession
1237
+     */
1238
+    public function getSession() {
1239
+        return $this->query('UserSession')->getSession();
1240
+    }
1241
+
1242
+    /**
1243
+     * @param \OCP\ISession $session
1244
+     */
1245
+    public function setSession(\OCP\ISession $session) {
1246
+        $this->query(SessionStorage::class)->setSession($session);
1247
+        $this->query('UserSession')->setSession($session);
1248
+        $this->query(Store::class)->setSession($session);
1249
+    }
1250
+
1251
+    /**
1252
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1253
+     */
1254
+    public function getTwoFactorAuthManager() {
1255
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1256
+    }
1257
+
1258
+    /**
1259
+     * @return \OC\NavigationManager
1260
+     */
1261
+    public function getNavigationManager() {
1262
+        return $this->query('NavigationManager');
1263
+    }
1264
+
1265
+    /**
1266
+     * @return \OCP\IConfig
1267
+     */
1268
+    public function getConfig() {
1269
+        return $this->query('AllConfig');
1270
+    }
1271
+
1272
+    /**
1273
+     * @return \OC\SystemConfig
1274
+     */
1275
+    public function getSystemConfig() {
1276
+        return $this->query('SystemConfig');
1277
+    }
1278
+
1279
+    /**
1280
+     * Returns the app config manager
1281
+     *
1282
+     * @return \OCP\IAppConfig
1283
+     */
1284
+    public function getAppConfig() {
1285
+        return $this->query('AppConfig');
1286
+    }
1287
+
1288
+    /**
1289
+     * @return \OCP\L10N\IFactory
1290
+     */
1291
+    public function getL10NFactory() {
1292
+        return $this->query('L10NFactory');
1293
+    }
1294
+
1295
+    /**
1296
+     * get an L10N instance
1297
+     *
1298
+     * @param string $app appid
1299
+     * @param string $lang
1300
+     * @return IL10N
1301
+     */
1302
+    public function getL10N($app, $lang = null) {
1303
+        return $this->getL10NFactory()->get($app, $lang);
1304
+    }
1305
+
1306
+    /**
1307
+     * @return \OCP\IURLGenerator
1308
+     */
1309
+    public function getURLGenerator() {
1310
+        return $this->query('URLGenerator');
1311
+    }
1312
+
1313
+    /**
1314
+     * @return \OCP\IHelper
1315
+     */
1316
+    public function getHelper() {
1317
+        return $this->query('AppHelper');
1318
+    }
1319
+
1320
+    /**
1321
+     * @return AppFetcher
1322
+     */
1323
+    public function getAppFetcher() {
1324
+        return $this->query(AppFetcher::class);
1325
+    }
1326
+
1327
+    /**
1328
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1329
+     * getMemCacheFactory() instead.
1330
+     *
1331
+     * @return \OCP\ICache
1332
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1333
+     */
1334
+    public function getCache() {
1335
+        return $this->query('UserCache');
1336
+    }
1337
+
1338
+    /**
1339
+     * Returns an \OCP\CacheFactory instance
1340
+     *
1341
+     * @return \OCP\ICacheFactory
1342
+     */
1343
+    public function getMemCacheFactory() {
1344
+        return $this->query('MemCacheFactory');
1345
+    }
1346
+
1347
+    /**
1348
+     * Returns an \OC\RedisFactory instance
1349
+     *
1350
+     * @return \OC\RedisFactory
1351
+     */
1352
+    public function getGetRedisFactory() {
1353
+        return $this->query('RedisFactory');
1354
+    }
1355
+
1356
+
1357
+    /**
1358
+     * Returns the current session
1359
+     *
1360
+     * @return \OCP\IDBConnection
1361
+     */
1362
+    public function getDatabaseConnection() {
1363
+        return $this->query('DatabaseConnection');
1364
+    }
1365
+
1366
+    /**
1367
+     * Returns the activity manager
1368
+     *
1369
+     * @return \OCP\Activity\IManager
1370
+     */
1371
+    public function getActivityManager() {
1372
+        return $this->query('ActivityManager');
1373
+    }
1374
+
1375
+    /**
1376
+     * Returns an job list for controlling background jobs
1377
+     *
1378
+     * @return \OCP\BackgroundJob\IJobList
1379
+     */
1380
+    public function getJobList() {
1381
+        return $this->query('JobList');
1382
+    }
1383
+
1384
+    /**
1385
+     * Returns a logger instance
1386
+     *
1387
+     * @return \OCP\ILogger
1388
+     */
1389
+    public function getLogger() {
1390
+        return $this->query('Logger');
1391
+    }
1392
+
1393
+    /**
1394
+     * Returns a router for generating and matching urls
1395
+     *
1396
+     * @return \OCP\Route\IRouter
1397
+     */
1398
+    public function getRouter() {
1399
+        return $this->query('Router');
1400
+    }
1401
+
1402
+    /**
1403
+     * Returns a search instance
1404
+     *
1405
+     * @return \OCP\ISearch
1406
+     */
1407
+    public function getSearch() {
1408
+        return $this->query('Search');
1409
+    }
1410
+
1411
+    /**
1412
+     * Returns a SecureRandom instance
1413
+     *
1414
+     * @return \OCP\Security\ISecureRandom
1415
+     */
1416
+    public function getSecureRandom() {
1417
+        return $this->query('SecureRandom');
1418
+    }
1419
+
1420
+    /**
1421
+     * Returns a Crypto instance
1422
+     *
1423
+     * @return \OCP\Security\ICrypto
1424
+     */
1425
+    public function getCrypto() {
1426
+        return $this->query('Crypto');
1427
+    }
1428
+
1429
+    /**
1430
+     * Returns a Hasher instance
1431
+     *
1432
+     * @return \OCP\Security\IHasher
1433
+     */
1434
+    public function getHasher() {
1435
+        return $this->query('Hasher');
1436
+    }
1437
+
1438
+    /**
1439
+     * Returns a CredentialsManager instance
1440
+     *
1441
+     * @return \OCP\Security\ICredentialsManager
1442
+     */
1443
+    public function getCredentialsManager() {
1444
+        return $this->query('CredentialsManager');
1445
+    }
1446
+
1447
+    /**
1448
+     * Returns an instance of the HTTP helper class
1449
+     *
1450
+     * @deprecated Use getHTTPClientService()
1451
+     * @return \OC\HTTPHelper
1452
+     */
1453
+    public function getHTTPHelper() {
1454
+        return $this->query('HTTPHelper');
1455
+    }
1456
+
1457
+    /**
1458
+     * Get the certificate manager for the user
1459
+     *
1460
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1461
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1462
+     */
1463
+    public function getCertificateManager($userId = '') {
1464
+        if ($userId === '') {
1465
+            $userSession = $this->getUserSession();
1466
+            $user = $userSession->getUser();
1467
+            if (is_null($user)) {
1468
+                return null;
1469
+            }
1470
+            $userId = $user->getUID();
1471
+        }
1472
+        return new CertificateManager(
1473
+            $userId,
1474
+            new View(),
1475
+            $this->getConfig(),
1476
+            $this->getLogger(),
1477
+            $this->getSecureRandom()
1478
+        );
1479
+    }
1480
+
1481
+    /**
1482
+     * Returns an instance of the HTTP client service
1483
+     *
1484
+     * @return \OCP\Http\Client\IClientService
1485
+     */
1486
+    public function getHTTPClientService() {
1487
+        return $this->query('HttpClientService');
1488
+    }
1489
+
1490
+    /**
1491
+     * Create a new event source
1492
+     *
1493
+     * @return \OCP\IEventSource
1494
+     */
1495
+    public function createEventSource() {
1496
+        return new \OC_EventSource();
1497
+    }
1498
+
1499
+    /**
1500
+     * Get the active event logger
1501
+     *
1502
+     * The returned logger only logs data when debug mode is enabled
1503
+     *
1504
+     * @return \OCP\Diagnostics\IEventLogger
1505
+     */
1506
+    public function getEventLogger() {
1507
+        return $this->query('EventLogger');
1508
+    }
1509
+
1510
+    /**
1511
+     * Get the active query logger
1512
+     *
1513
+     * The returned logger only logs data when debug mode is enabled
1514
+     *
1515
+     * @return \OCP\Diagnostics\IQueryLogger
1516
+     */
1517
+    public function getQueryLogger() {
1518
+        return $this->query('QueryLogger');
1519
+    }
1520
+
1521
+    /**
1522
+     * Get the manager for temporary files and folders
1523
+     *
1524
+     * @return \OCP\ITempManager
1525
+     */
1526
+    public function getTempManager() {
1527
+        return $this->query('TempManager');
1528
+    }
1529
+
1530
+    /**
1531
+     * Get the app manager
1532
+     *
1533
+     * @return \OCP\App\IAppManager
1534
+     */
1535
+    public function getAppManager() {
1536
+        return $this->query('AppManager');
1537
+    }
1538
+
1539
+    /**
1540
+     * Creates a new mailer
1541
+     *
1542
+     * @return \OCP\Mail\IMailer
1543
+     */
1544
+    public function getMailer() {
1545
+        return $this->query('Mailer');
1546
+    }
1547
+
1548
+    /**
1549
+     * Get the webroot
1550
+     *
1551
+     * @return string
1552
+     */
1553
+    public function getWebRoot() {
1554
+        return $this->webRoot;
1555
+    }
1556
+
1557
+    /**
1558
+     * @return \OC\OCSClient
1559
+     */
1560
+    public function getOcsClient() {
1561
+        return $this->query('OcsClient');
1562
+    }
1563
+
1564
+    /**
1565
+     * @return \OCP\IDateTimeZone
1566
+     */
1567
+    public function getDateTimeZone() {
1568
+        return $this->query('DateTimeZone');
1569
+    }
1570
+
1571
+    /**
1572
+     * @return \OCP\IDateTimeFormatter
1573
+     */
1574
+    public function getDateTimeFormatter() {
1575
+        return $this->query('DateTimeFormatter');
1576
+    }
1577
+
1578
+    /**
1579
+     * @return \OCP\Files\Config\IMountProviderCollection
1580
+     */
1581
+    public function getMountProviderCollection() {
1582
+        return $this->query('MountConfigManager');
1583
+    }
1584
+
1585
+    /**
1586
+     * Get the IniWrapper
1587
+     *
1588
+     * @return IniGetWrapper
1589
+     */
1590
+    public function getIniWrapper() {
1591
+        return $this->query('IniWrapper');
1592
+    }
1593
+
1594
+    /**
1595
+     * @return \OCP\Command\IBus
1596
+     */
1597
+    public function getCommandBus() {
1598
+        return $this->query('AsyncCommandBus');
1599
+    }
1600
+
1601
+    /**
1602
+     * Get the trusted domain helper
1603
+     *
1604
+     * @return TrustedDomainHelper
1605
+     */
1606
+    public function getTrustedDomainHelper() {
1607
+        return $this->query('TrustedDomainHelper');
1608
+    }
1609
+
1610
+    /**
1611
+     * Get the locking provider
1612
+     *
1613
+     * @return \OCP\Lock\ILockingProvider
1614
+     * @since 8.1.0
1615
+     */
1616
+    public function getLockingProvider() {
1617
+        return $this->query('LockingProvider');
1618
+    }
1619
+
1620
+    /**
1621
+     * @return \OCP\Files\Mount\IMountManager
1622
+     **/
1623
+    function getMountManager() {
1624
+        return $this->query('MountManager');
1625
+    }
1626
+
1627
+    /** @return \OCP\Files\Config\IUserMountCache */
1628
+    function getUserMountCache() {
1629
+        return $this->query('UserMountCache');
1630
+    }
1631
+
1632
+    /**
1633
+     * Get the MimeTypeDetector
1634
+     *
1635
+     * @return \OCP\Files\IMimeTypeDetector
1636
+     */
1637
+    public function getMimeTypeDetector() {
1638
+        return $this->query('MimeTypeDetector');
1639
+    }
1640
+
1641
+    /**
1642
+     * Get the MimeTypeLoader
1643
+     *
1644
+     * @return \OCP\Files\IMimeTypeLoader
1645
+     */
1646
+    public function getMimeTypeLoader() {
1647
+        return $this->query('MimeTypeLoader');
1648
+    }
1649
+
1650
+    /**
1651
+     * Get the manager of all the capabilities
1652
+     *
1653
+     * @return \OC\CapabilitiesManager
1654
+     */
1655
+    public function getCapabilitiesManager() {
1656
+        return $this->query('CapabilitiesManager');
1657
+    }
1658
+
1659
+    /**
1660
+     * Get the EventDispatcher
1661
+     *
1662
+     * @return EventDispatcherInterface
1663
+     * @since 8.2.0
1664
+     */
1665
+    public function getEventDispatcher() {
1666
+        return $this->query('EventDispatcher');
1667
+    }
1668
+
1669
+    /**
1670
+     * Get the Notification Manager
1671
+     *
1672
+     * @return \OCP\Notification\IManager
1673
+     * @since 8.2.0
1674
+     */
1675
+    public function getNotificationManager() {
1676
+        return $this->query('NotificationManager');
1677
+    }
1678
+
1679
+    /**
1680
+     * @return \OCP\Comments\ICommentsManager
1681
+     */
1682
+    public function getCommentsManager() {
1683
+        return $this->query('CommentsManager');
1684
+    }
1685
+
1686
+    /**
1687
+     * @return \OCA\Theming\ThemingDefaults
1688
+     */
1689
+    public function getThemingDefaults() {
1690
+        return $this->query('ThemingDefaults');
1691
+    }
1692
+
1693
+    /**
1694
+     * @return \OC\IntegrityCheck\Checker
1695
+     */
1696
+    public function getIntegrityCodeChecker() {
1697
+        return $this->query('IntegrityCodeChecker');
1698
+    }
1699
+
1700
+    /**
1701
+     * @return \OC\Session\CryptoWrapper
1702
+     */
1703
+    public function getSessionCryptoWrapper() {
1704
+        return $this->query('CryptoWrapper');
1705
+    }
1706
+
1707
+    /**
1708
+     * @return CsrfTokenManager
1709
+     */
1710
+    public function getCsrfTokenManager() {
1711
+        return $this->query('CsrfTokenManager');
1712
+    }
1713
+
1714
+    /**
1715
+     * @return Throttler
1716
+     */
1717
+    public function getBruteForceThrottler() {
1718
+        return $this->query('Throttler');
1719
+    }
1720
+
1721
+    /**
1722
+     * @return IContentSecurityPolicyManager
1723
+     */
1724
+    public function getContentSecurityPolicyManager() {
1725
+        return $this->query('ContentSecurityPolicyManager');
1726
+    }
1727
+
1728
+    /**
1729
+     * @return ContentSecurityPolicyNonceManager
1730
+     */
1731
+    public function getContentSecurityPolicyNonceManager() {
1732
+        return $this->query('ContentSecurityPolicyNonceManager');
1733
+    }
1734
+
1735
+    /**
1736
+     * Not a public API as of 8.2, wait for 9.0
1737
+     *
1738
+     * @return \OCA\Files_External\Service\BackendService
1739
+     */
1740
+    public function getStoragesBackendService() {
1741
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1742
+    }
1743
+
1744
+    /**
1745
+     * Not a public API as of 8.2, wait for 9.0
1746
+     *
1747
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1748
+     */
1749
+    public function getGlobalStoragesService() {
1750
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1751
+    }
1752
+
1753
+    /**
1754
+     * Not a public API as of 8.2, wait for 9.0
1755
+     *
1756
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1757
+     */
1758
+    public function getUserGlobalStoragesService() {
1759
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1760
+    }
1761
+
1762
+    /**
1763
+     * Not a public API as of 8.2, wait for 9.0
1764
+     *
1765
+     * @return \OCA\Files_External\Service\UserStoragesService
1766
+     */
1767
+    public function getUserStoragesService() {
1768
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1769
+    }
1770
+
1771
+    /**
1772
+     * @return \OCP\Share\IManager
1773
+     */
1774
+    public function getShareManager() {
1775
+        return $this->query('ShareManager');
1776
+    }
1777
+
1778
+    /**
1779
+     * Returns the LDAP Provider
1780
+     *
1781
+     * @return \OCP\LDAP\ILDAPProvider
1782
+     */
1783
+    public function getLDAPProvider() {
1784
+        return $this->query('LDAPProvider');
1785
+    }
1786
+
1787
+    /**
1788
+     * @return \OCP\Settings\IManager
1789
+     */
1790
+    public function getSettingsManager() {
1791
+        return $this->query('SettingsManager');
1792
+    }
1793
+
1794
+    /**
1795
+     * @return \OCP\Files\IAppData
1796
+     */
1797
+    public function getAppDataDir($app) {
1798
+        /** @var \OC\Files\AppData\Factory $factory */
1799
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1800
+        return $factory->get($app);
1801
+    }
1802
+
1803
+    /**
1804
+     * @return \OCP\Lockdown\ILockdownManager
1805
+     */
1806
+    public function getLockdownManager() {
1807
+        return $this->query('LockdownManager');
1808
+    }
1809
+
1810
+    /**
1811
+     * @return \OCP\Federation\ICloudIdManager
1812
+     */
1813
+    public function getCloudIdManager() {
1814
+        return $this->query(ICloudIdManager::class);
1815
+    }
1816 1816
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 2 patches
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 
346 346
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347 347
 			$expirationDate = new \DateTime();
348
-			$expirationDate->setTime(0,0,0);
348
+			$expirationDate->setTime(0, 0, 0);
349 349
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350 350
 		}
351 351
 
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 
358 358
 			$date = new \DateTime();
359 359
 			$date->setTime(0, 0, 0);
360
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
360
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
361 361
 			if ($date < $expirationDate) {
362 362
 				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363 363
 				throw new GenericShareException($message, $message, 404);
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 		 */
411 411
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412 412
 		$existingShares = $provider->getSharesByPath($share->getNode());
413
-		foreach($existingShares as $existingShare) {
413
+		foreach ($existingShares as $existingShare) {
414 414
 			// Ignore if it is the same share
415 415
 			try {
416 416
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
 		 */
468 468
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469 469
 		$existingShares = $provider->getSharesByPath($share->getNode());
470
-		foreach($existingShares as $existingShare) {
470
+		foreach ($existingShares as $existingShare) {
471 471
 			try {
472 472
 				if ($existingShare->getFullId() === $share->getFullId()) {
473 473
 					continue;
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
 		// Make sure that we do not share a path that contains a shared mountpoint
537 537
 		if ($path instanceof \OCP\Files\Folder) {
538 538
 			$mounts = $this->mountManager->findIn($path->getPath());
539
-			foreach($mounts as $mount) {
539
+			foreach ($mounts as $mount) {
540 540
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541 541
 					throw new \InvalidArgumentException('Path contains files shared with you');
542 542
 				}
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
 		$storage = $share->getNode()->getStorage();
585 585
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586 586
 			$parent = $share->getNode()->getParent();
587
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
587
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588 588
 				$parent = $parent->getParent();
589 589
 			}
590 590
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
 		}
638 638
 
639 639
 		// Generate the target
640
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
640
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
641 641
 		$target = \OC\Files\Filesystem::normalizePath($target);
642 642
 		$share->setTarget($target);
643 643
 
@@ -668,17 +668,17 @@  discard block
 block discarded – undo
668 668
 					$this->sendMailNotification(
669 669
 						$l,
670 670
 						$share->getNode()->getName(),
671
-						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
671
+						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
672 672
 						$share->getSharedBy(),
673 673
 						$emailAddress,
674 674
 						$share->getExpirationDate()
675 675
 					);
676
-					$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
676
+					$this->logger->debug('Send share notification to '.$emailAddress.' for share with ID '.$share->getId(), ['app' => 'share']);
677 677
 				} else {
678
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
678
+					$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because email address is not set.', ['app' => 'share']);
679 679
 				}
680 680
 			} else {
681
-				$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
681
+				$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because user could not be found.', ['app' => 'share']);
682 682
 			}
683 683
 		}
684 684
 
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
 		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
720 720
 
721 721
 		$emailTemplate->addBodyText(
722
-			$text . ' ' . $l->t('Click the button below to open it.'),
722
+			$text.' '.$l->t('Click the button below to open it.'),
723 723
 			$text
724 724
 		);
725 725
 		$emailTemplate->addBodyButton(
@@ -743,9 +743,9 @@  discard block
 block discarded – undo
743 743
 		// The "Reply-To" is set to the sharer if an mail address is configured
744 744
 		// also the default footer contains a "Do not reply" which needs to be adjusted.
745 745
 		$initiatorEmail = $initiatorUser->getEMailAddress();
746
-		if($initiatorEmail !== null) {
746
+		if ($initiatorEmail !== null) {
747 747
 			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
748
-			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
748
+			$emailTemplate->addFooter($instanceName.' - '.$this->defaults->getSlogan());
749 749
 		} else {
750 750
 			$emailTemplate->addFooter();
751 751
 		}
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
 	 * @param string $recipientId
957 957
 	 */
958 958
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
959
-		list($providerId, ) = $this->splitFullId($share->getFullId());
959
+		list($providerId,) = $this->splitFullId($share->getFullId());
960 960
 		$provider = $this->factory->getProvider($providerId);
961 961
 
962 962
 		$provider->deleteFromSelf($share, $recipientId);
@@ -979,7 +979,7 @@  discard block
 block discarded – undo
979 979
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
980 980
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
981 981
 			if (is_null($sharedWith)) {
982
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
982
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
983 983
 			}
984 984
 			$recipient = $this->userManager->get($recipientId);
985 985
 			if (!$sharedWith->inGroup($recipient)) {
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
 			}
988 988
 		}
989 989
 
990
-		list($providerId, ) = $this->splitFullId($share->getFullId());
990
+		list($providerId,) = $this->splitFullId($share->getFullId());
991 991
 		$provider = $this->factory->getProvider($providerId);
992 992
 
993 993
 		$provider->move($share, $recipientId);
@@ -1034,7 +1034,7 @@  discard block
 block discarded – undo
1034 1034
 
1035 1035
 		$shares2 = [];
1036 1036
 
1037
-		while(true) {
1037
+		while (true) {
1038 1038
 			$added = 0;
1039 1039
 			foreach ($shares as $share) {
1040 1040
 
@@ -1134,7 +1134,7 @@  discard block
 block discarded – undo
1134 1134
 	 *
1135 1135
 	 * @return Share[]
1136 1136
 	 */
1137
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1137
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1138 1138
 		return [];
1139 1139
 	}
1140 1140
 
@@ -1149,7 +1149,7 @@  discard block
 block discarded – undo
1149 1149
 	public function getShareByToken($token) {
1150 1150
 		$share = null;
1151 1151
 		try {
1152
-			if($this->shareApiAllowLinks()) {
1152
+			if ($this->shareApiAllowLinks()) {
1153 1153
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1154 1154
 				$share = $provider->getShareByToken($token);
1155 1155
 			}
@@ -1356,7 +1356,7 @@  discard block
 block discarded – undo
1356 1356
 			}
1357 1357
 			$al['users'][$owner] = [
1358 1358
 				'node_id' => $path->getId(),
1359
-				'node_path' => '/' . $ownerPath,
1359
+				'node_path' => '/'.$ownerPath,
1360 1360
 			];
1361 1361
 		} else {
1362 1362
 			$al['users'][] = $owner;
@@ -1450,7 +1450,7 @@  discard block
 block discarded – undo
1450 1450
 	 * @return int
1451 1451
 	 */
1452 1452
 	public function shareApiLinkDefaultExpireDays() {
1453
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1453
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1454 1454
 	}
1455 1455
 
1456 1456
 	/**
Please login to merge, or discard this patch.
Indentation   +1456 added lines, -1456 removed lines patch added patch discarded remove patch
@@ -60,1484 +60,1484 @@
 block discarded – undo
60 60
  */
61 61
 class Manager implements IManager {
62 62
 
63
-	/** @var IProviderFactory */
64
-	private $factory;
65
-	/** @var ILogger */
66
-	private $logger;
67
-	/** @var IConfig */
68
-	private $config;
69
-	/** @var ISecureRandom */
70
-	private $secureRandom;
71
-	/** @var IHasher */
72
-	private $hasher;
73
-	/** @var IMountManager */
74
-	private $mountManager;
75
-	/** @var IGroupManager */
76
-	private $groupManager;
77
-	/** @var IL10N */
78
-	private $l;
79
-	/** @var IFactory */
80
-	private $l10nFactory;
81
-	/** @var IUserManager */
82
-	private $userManager;
83
-	/** @var IRootFolder */
84
-	private $rootFolder;
85
-	/** @var CappedMemoryCache */
86
-	private $sharingDisabledForUsersCache;
87
-	/** @var EventDispatcher */
88
-	private $eventDispatcher;
89
-	/** @var LegacyHooks */
90
-	private $legacyHooks;
91
-	/** @var IMailer */
92
-	private $mailer;
93
-	/** @var IURLGenerator */
94
-	private $urlGenerator;
95
-	/** @var \OC_Defaults */
96
-	private $defaults;
97
-
98
-
99
-	/**
100
-	 * Manager constructor.
101
-	 *
102
-	 * @param ILogger $logger
103
-	 * @param IConfig $config
104
-	 * @param ISecureRandom $secureRandom
105
-	 * @param IHasher $hasher
106
-	 * @param IMountManager $mountManager
107
-	 * @param IGroupManager $groupManager
108
-	 * @param IL10N $l
109
-	 * @param IFactory $l10nFactory
110
-	 * @param IProviderFactory $factory
111
-	 * @param IUserManager $userManager
112
-	 * @param IRootFolder $rootFolder
113
-	 * @param EventDispatcher $eventDispatcher
114
-	 * @param IMailer $mailer
115
-	 * @param IURLGenerator $urlGenerator
116
-	 * @param \OC_Defaults $defaults
117
-	 */
118
-	public function __construct(
119
-			ILogger $logger,
120
-			IConfig $config,
121
-			ISecureRandom $secureRandom,
122
-			IHasher $hasher,
123
-			IMountManager $mountManager,
124
-			IGroupManager $groupManager,
125
-			IL10N $l,
126
-			IFactory $l10nFactory,
127
-			IProviderFactory $factory,
128
-			IUserManager $userManager,
129
-			IRootFolder $rootFolder,
130
-			EventDispatcher $eventDispatcher,
131
-			IMailer $mailer,
132
-			IURLGenerator $urlGenerator,
133
-			\OC_Defaults $defaults
134
-	) {
135
-		$this->logger = $logger;
136
-		$this->config = $config;
137
-		$this->secureRandom = $secureRandom;
138
-		$this->hasher = $hasher;
139
-		$this->mountManager = $mountManager;
140
-		$this->groupManager = $groupManager;
141
-		$this->l = $l;
142
-		$this->l10nFactory = $l10nFactory;
143
-		$this->factory = $factory;
144
-		$this->userManager = $userManager;
145
-		$this->rootFolder = $rootFolder;
146
-		$this->eventDispatcher = $eventDispatcher;
147
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
148
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
149
-		$this->mailer = $mailer;
150
-		$this->urlGenerator = $urlGenerator;
151
-		$this->defaults = $defaults;
152
-	}
153
-
154
-	/**
155
-	 * Convert from a full share id to a tuple (providerId, shareId)
156
-	 *
157
-	 * @param string $id
158
-	 * @return string[]
159
-	 */
160
-	private function splitFullId($id) {
161
-		return explode(':', $id, 2);
162
-	}
163
-
164
-	/**
165
-	 * Verify if a password meets all requirements
166
-	 *
167
-	 * @param string $password
168
-	 * @throws \Exception
169
-	 */
170
-	protected function verifyPassword($password) {
171
-		if ($password === null) {
172
-			// No password is set, check if this is allowed.
173
-			if ($this->shareApiLinkEnforcePassword()) {
174
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
175
-			}
176
-
177
-			return;
178
-		}
179
-
180
-		// Let others verify the password
181
-		try {
182
-			$event = new GenericEvent($password);
183
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
184
-		} catch (HintException $e) {
185
-			throw new \Exception($e->getHint());
186
-		}
187
-	}
188
-
189
-	/**
190
-	 * Check for generic requirements before creating a share
191
-	 *
192
-	 * @param \OCP\Share\IShare $share
193
-	 * @throws \InvalidArgumentException
194
-	 * @throws GenericShareException
195
-	 *
196
-	 * @suppress PhanUndeclaredClassMethod
197
-	 */
198
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
199
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
200
-			// We expect a valid user as sharedWith for user shares
201
-			if (!$this->userManager->userExists($share->getSharedWith())) {
202
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
203
-			}
204
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
205
-			// We expect a valid group as sharedWith for group shares
206
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
207
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
208
-			}
209
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
210
-			if ($share->getSharedWith() !== null) {
211
-				throw new \InvalidArgumentException('SharedWith should be empty');
212
-			}
213
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
214
-			if ($share->getSharedWith() === null) {
215
-				throw new \InvalidArgumentException('SharedWith should not be empty');
216
-			}
217
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
218
-			if ($share->getSharedWith() === null) {
219
-				throw new \InvalidArgumentException('SharedWith should not be empty');
220
-			}
221
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
222
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
223
-			if ($circle === null) {
224
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
225
-			}
226
-		} else {
227
-			// We can't handle other types yet
228
-			throw new \InvalidArgumentException('unknown share type');
229
-		}
230
-
231
-		// Verify the initiator of the share is set
232
-		if ($share->getSharedBy() === null) {
233
-			throw new \InvalidArgumentException('SharedBy should be set');
234
-		}
235
-
236
-		// Cannot share with yourself
237
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
238
-			$share->getSharedWith() === $share->getSharedBy()) {
239
-			throw new \InvalidArgumentException('Can’t share with yourself');
240
-		}
241
-
242
-		// The path should be set
243
-		if ($share->getNode() === null) {
244
-			throw new \InvalidArgumentException('Path should be set');
245
-		}
246
-
247
-		// And it should be a file or a folder
248
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
249
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
250
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
251
-		}
252
-
253
-		// And you can't share your rootfolder
254
-		if ($this->userManager->userExists($share->getSharedBy())) {
255
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
256
-		} else {
257
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
258
-		}
259
-		if ($sharedPath === $share->getNode()->getPath()) {
260
-			throw new \InvalidArgumentException('You can’t share your root folder');
261
-		}
262
-
263
-		// Check if we actually have share permissions
264
-		if (!$share->getNode()->isShareable()) {
265
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
266
-			throw new GenericShareException($message_t, $message_t, 404);
267
-		}
268
-
269
-		// Permissions should be set
270
-		if ($share->getPermissions() === null) {
271
-			throw new \InvalidArgumentException('A share requires permissions');
272
-		}
273
-
274
-		/*
63
+    /** @var IProviderFactory */
64
+    private $factory;
65
+    /** @var ILogger */
66
+    private $logger;
67
+    /** @var IConfig */
68
+    private $config;
69
+    /** @var ISecureRandom */
70
+    private $secureRandom;
71
+    /** @var IHasher */
72
+    private $hasher;
73
+    /** @var IMountManager */
74
+    private $mountManager;
75
+    /** @var IGroupManager */
76
+    private $groupManager;
77
+    /** @var IL10N */
78
+    private $l;
79
+    /** @var IFactory */
80
+    private $l10nFactory;
81
+    /** @var IUserManager */
82
+    private $userManager;
83
+    /** @var IRootFolder */
84
+    private $rootFolder;
85
+    /** @var CappedMemoryCache */
86
+    private $sharingDisabledForUsersCache;
87
+    /** @var EventDispatcher */
88
+    private $eventDispatcher;
89
+    /** @var LegacyHooks */
90
+    private $legacyHooks;
91
+    /** @var IMailer */
92
+    private $mailer;
93
+    /** @var IURLGenerator */
94
+    private $urlGenerator;
95
+    /** @var \OC_Defaults */
96
+    private $defaults;
97
+
98
+
99
+    /**
100
+     * Manager constructor.
101
+     *
102
+     * @param ILogger $logger
103
+     * @param IConfig $config
104
+     * @param ISecureRandom $secureRandom
105
+     * @param IHasher $hasher
106
+     * @param IMountManager $mountManager
107
+     * @param IGroupManager $groupManager
108
+     * @param IL10N $l
109
+     * @param IFactory $l10nFactory
110
+     * @param IProviderFactory $factory
111
+     * @param IUserManager $userManager
112
+     * @param IRootFolder $rootFolder
113
+     * @param EventDispatcher $eventDispatcher
114
+     * @param IMailer $mailer
115
+     * @param IURLGenerator $urlGenerator
116
+     * @param \OC_Defaults $defaults
117
+     */
118
+    public function __construct(
119
+            ILogger $logger,
120
+            IConfig $config,
121
+            ISecureRandom $secureRandom,
122
+            IHasher $hasher,
123
+            IMountManager $mountManager,
124
+            IGroupManager $groupManager,
125
+            IL10N $l,
126
+            IFactory $l10nFactory,
127
+            IProviderFactory $factory,
128
+            IUserManager $userManager,
129
+            IRootFolder $rootFolder,
130
+            EventDispatcher $eventDispatcher,
131
+            IMailer $mailer,
132
+            IURLGenerator $urlGenerator,
133
+            \OC_Defaults $defaults
134
+    ) {
135
+        $this->logger = $logger;
136
+        $this->config = $config;
137
+        $this->secureRandom = $secureRandom;
138
+        $this->hasher = $hasher;
139
+        $this->mountManager = $mountManager;
140
+        $this->groupManager = $groupManager;
141
+        $this->l = $l;
142
+        $this->l10nFactory = $l10nFactory;
143
+        $this->factory = $factory;
144
+        $this->userManager = $userManager;
145
+        $this->rootFolder = $rootFolder;
146
+        $this->eventDispatcher = $eventDispatcher;
147
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
148
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
149
+        $this->mailer = $mailer;
150
+        $this->urlGenerator = $urlGenerator;
151
+        $this->defaults = $defaults;
152
+    }
153
+
154
+    /**
155
+     * Convert from a full share id to a tuple (providerId, shareId)
156
+     *
157
+     * @param string $id
158
+     * @return string[]
159
+     */
160
+    private function splitFullId($id) {
161
+        return explode(':', $id, 2);
162
+    }
163
+
164
+    /**
165
+     * Verify if a password meets all requirements
166
+     *
167
+     * @param string $password
168
+     * @throws \Exception
169
+     */
170
+    protected function verifyPassword($password) {
171
+        if ($password === null) {
172
+            // No password is set, check if this is allowed.
173
+            if ($this->shareApiLinkEnforcePassword()) {
174
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
175
+            }
176
+
177
+            return;
178
+        }
179
+
180
+        // Let others verify the password
181
+        try {
182
+            $event = new GenericEvent($password);
183
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
184
+        } catch (HintException $e) {
185
+            throw new \Exception($e->getHint());
186
+        }
187
+    }
188
+
189
+    /**
190
+     * Check for generic requirements before creating a share
191
+     *
192
+     * @param \OCP\Share\IShare $share
193
+     * @throws \InvalidArgumentException
194
+     * @throws GenericShareException
195
+     *
196
+     * @suppress PhanUndeclaredClassMethod
197
+     */
198
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
199
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
200
+            // We expect a valid user as sharedWith for user shares
201
+            if (!$this->userManager->userExists($share->getSharedWith())) {
202
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
203
+            }
204
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
205
+            // We expect a valid group as sharedWith for group shares
206
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
207
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
208
+            }
209
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
210
+            if ($share->getSharedWith() !== null) {
211
+                throw new \InvalidArgumentException('SharedWith should be empty');
212
+            }
213
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
214
+            if ($share->getSharedWith() === null) {
215
+                throw new \InvalidArgumentException('SharedWith should not be empty');
216
+            }
217
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
218
+            if ($share->getSharedWith() === null) {
219
+                throw new \InvalidArgumentException('SharedWith should not be empty');
220
+            }
221
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
222
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
223
+            if ($circle === null) {
224
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
225
+            }
226
+        } else {
227
+            // We can't handle other types yet
228
+            throw new \InvalidArgumentException('unknown share type');
229
+        }
230
+
231
+        // Verify the initiator of the share is set
232
+        if ($share->getSharedBy() === null) {
233
+            throw new \InvalidArgumentException('SharedBy should be set');
234
+        }
235
+
236
+        // Cannot share with yourself
237
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
238
+            $share->getSharedWith() === $share->getSharedBy()) {
239
+            throw new \InvalidArgumentException('Can’t share with yourself');
240
+        }
241
+
242
+        // The path should be set
243
+        if ($share->getNode() === null) {
244
+            throw new \InvalidArgumentException('Path should be set');
245
+        }
246
+
247
+        // And it should be a file or a folder
248
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
249
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
250
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
251
+        }
252
+
253
+        // And you can't share your rootfolder
254
+        if ($this->userManager->userExists($share->getSharedBy())) {
255
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
256
+        } else {
257
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
258
+        }
259
+        if ($sharedPath === $share->getNode()->getPath()) {
260
+            throw new \InvalidArgumentException('You can’t share your root folder');
261
+        }
262
+
263
+        // Check if we actually have share permissions
264
+        if (!$share->getNode()->isShareable()) {
265
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
266
+            throw new GenericShareException($message_t, $message_t, 404);
267
+        }
268
+
269
+        // Permissions should be set
270
+        if ($share->getPermissions() === null) {
271
+            throw new \InvalidArgumentException('A share requires permissions');
272
+        }
273
+
274
+        /*
275 275
 		 * Quick fix for #23536
276 276
 		 * Non moveable mount points do not have update and delete permissions
277 277
 		 * while we 'most likely' do have that on the storage.
278 278
 		 */
279
-		$permissions = $share->getNode()->getPermissions();
280
-		$mount = $share->getNode()->getMountPoint();
281
-		if (!($mount instanceof MoveableMount)) {
282
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
283
-		}
284
-
285
-		// Check that we do not share with more permissions than we have
286
-		if ($share->getPermissions() & ~$permissions) {
287
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
288
-			throw new GenericShareException($message_t, $message_t, 404);
289
-		}
290
-
291
-
292
-		// Check that read permissions are always set
293
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
294
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
295
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
296
-		if (!$noReadPermissionRequired &&
297
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
298
-			throw new \InvalidArgumentException('Shares need at least read permissions');
299
-		}
300
-
301
-		if ($share->getNode() instanceof \OCP\Files\File) {
302
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
303
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
304
-				throw new GenericShareException($message_t);
305
-			}
306
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
307
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
308
-				throw new GenericShareException($message_t);
309
-			}
310
-		}
311
-	}
312
-
313
-	/**
314
-	 * Validate if the expiration date fits the system settings
315
-	 *
316
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
317
-	 * @return \OCP\Share\IShare The modified share object
318
-	 * @throws GenericShareException
319
-	 * @throws \InvalidArgumentException
320
-	 * @throws \Exception
321
-	 */
322
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
323
-
324
-		$expirationDate = $share->getExpirationDate();
325
-
326
-		if ($expirationDate !== null) {
327
-			//Make sure the expiration date is a date
328
-			$expirationDate->setTime(0, 0, 0);
329
-
330
-			$date = new \DateTime();
331
-			$date->setTime(0, 0, 0);
332
-			if ($date >= $expirationDate) {
333
-				$message = $this->l->t('Expiration date is in the past');
334
-				throw new GenericShareException($message, $message, 404);
335
-			}
336
-		}
337
-
338
-		// If expiredate is empty set a default one if there is a default
339
-		$fullId = null;
340
-		try {
341
-			$fullId = $share->getFullId();
342
-		} catch (\UnexpectedValueException $e) {
343
-			// This is a new share
344
-		}
345
-
346
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347
-			$expirationDate = new \DateTime();
348
-			$expirationDate->setTime(0,0,0);
349
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350
-		}
351
-
352
-		// If we enforce the expiration date check that is does not exceed
353
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
354
-			if ($expirationDate === null) {
355
-				throw new \InvalidArgumentException('Expiration date is enforced');
356
-			}
357
-
358
-			$date = new \DateTime();
359
-			$date->setTime(0, 0, 0);
360
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
361
-			if ($date < $expirationDate) {
362
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363
-				throw new GenericShareException($message, $message, 404);
364
-			}
365
-		}
366
-
367
-		$accepted = true;
368
-		$message = '';
369
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
370
-			'expirationDate' => &$expirationDate,
371
-			'accepted' => &$accepted,
372
-			'message' => &$message,
373
-			'passwordSet' => $share->getPassword() !== null,
374
-		]);
375
-
376
-		if (!$accepted) {
377
-			throw new \Exception($message);
378
-		}
379
-
380
-		$share->setExpirationDate($expirationDate);
381
-
382
-		return $share;
383
-	}
384
-
385
-	/**
386
-	 * Check for pre share requirements for user shares
387
-	 *
388
-	 * @param \OCP\Share\IShare $share
389
-	 * @throws \Exception
390
-	 */
391
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
392
-		// Check if we can share with group members only
393
-		if ($this->shareWithGroupMembersOnly()) {
394
-			$sharedBy = $this->userManager->get($share->getSharedBy());
395
-			$sharedWith = $this->userManager->get($share->getSharedWith());
396
-			// Verify we can share with this user
397
-			$groups = array_intersect(
398
-					$this->groupManager->getUserGroupIds($sharedBy),
399
-					$this->groupManager->getUserGroupIds($sharedWith)
400
-			);
401
-			if (empty($groups)) {
402
-				throw new \Exception('Sharing is only allowed with group members');
403
-			}
404
-		}
405
-
406
-		/*
279
+        $permissions = $share->getNode()->getPermissions();
280
+        $mount = $share->getNode()->getMountPoint();
281
+        if (!($mount instanceof MoveableMount)) {
282
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
283
+        }
284
+
285
+        // Check that we do not share with more permissions than we have
286
+        if ($share->getPermissions() & ~$permissions) {
287
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
288
+            throw new GenericShareException($message_t, $message_t, 404);
289
+        }
290
+
291
+
292
+        // Check that read permissions are always set
293
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
294
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
295
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
296
+        if (!$noReadPermissionRequired &&
297
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
298
+            throw new \InvalidArgumentException('Shares need at least read permissions');
299
+        }
300
+
301
+        if ($share->getNode() instanceof \OCP\Files\File) {
302
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
303
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
304
+                throw new GenericShareException($message_t);
305
+            }
306
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
307
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
308
+                throw new GenericShareException($message_t);
309
+            }
310
+        }
311
+    }
312
+
313
+    /**
314
+     * Validate if the expiration date fits the system settings
315
+     *
316
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
317
+     * @return \OCP\Share\IShare The modified share object
318
+     * @throws GenericShareException
319
+     * @throws \InvalidArgumentException
320
+     * @throws \Exception
321
+     */
322
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
323
+
324
+        $expirationDate = $share->getExpirationDate();
325
+
326
+        if ($expirationDate !== null) {
327
+            //Make sure the expiration date is a date
328
+            $expirationDate->setTime(0, 0, 0);
329
+
330
+            $date = new \DateTime();
331
+            $date->setTime(0, 0, 0);
332
+            if ($date >= $expirationDate) {
333
+                $message = $this->l->t('Expiration date is in the past');
334
+                throw new GenericShareException($message, $message, 404);
335
+            }
336
+        }
337
+
338
+        // If expiredate is empty set a default one if there is a default
339
+        $fullId = null;
340
+        try {
341
+            $fullId = $share->getFullId();
342
+        } catch (\UnexpectedValueException $e) {
343
+            // This is a new share
344
+        }
345
+
346
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347
+            $expirationDate = new \DateTime();
348
+            $expirationDate->setTime(0,0,0);
349
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350
+        }
351
+
352
+        // If we enforce the expiration date check that is does not exceed
353
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
354
+            if ($expirationDate === null) {
355
+                throw new \InvalidArgumentException('Expiration date is enforced');
356
+            }
357
+
358
+            $date = new \DateTime();
359
+            $date->setTime(0, 0, 0);
360
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
361
+            if ($date < $expirationDate) {
362
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363
+                throw new GenericShareException($message, $message, 404);
364
+            }
365
+        }
366
+
367
+        $accepted = true;
368
+        $message = '';
369
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
370
+            'expirationDate' => &$expirationDate,
371
+            'accepted' => &$accepted,
372
+            'message' => &$message,
373
+            'passwordSet' => $share->getPassword() !== null,
374
+        ]);
375
+
376
+        if (!$accepted) {
377
+            throw new \Exception($message);
378
+        }
379
+
380
+        $share->setExpirationDate($expirationDate);
381
+
382
+        return $share;
383
+    }
384
+
385
+    /**
386
+     * Check for pre share requirements for user shares
387
+     *
388
+     * @param \OCP\Share\IShare $share
389
+     * @throws \Exception
390
+     */
391
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
392
+        // Check if we can share with group members only
393
+        if ($this->shareWithGroupMembersOnly()) {
394
+            $sharedBy = $this->userManager->get($share->getSharedBy());
395
+            $sharedWith = $this->userManager->get($share->getSharedWith());
396
+            // Verify we can share with this user
397
+            $groups = array_intersect(
398
+                    $this->groupManager->getUserGroupIds($sharedBy),
399
+                    $this->groupManager->getUserGroupIds($sharedWith)
400
+            );
401
+            if (empty($groups)) {
402
+                throw new \Exception('Sharing is only allowed with group members');
403
+            }
404
+        }
405
+
406
+        /*
407 407
 		 * TODO: Could be costly, fix
408 408
 		 *
409 409
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
410 410
 		 */
411
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412
-		$existingShares = $provider->getSharesByPath($share->getNode());
413
-		foreach($existingShares as $existingShare) {
414
-			// Ignore if it is the same share
415
-			try {
416
-				if ($existingShare->getFullId() === $share->getFullId()) {
417
-					continue;
418
-				}
419
-			} catch (\UnexpectedValueException $e) {
420
-				//Shares are not identical
421
-			}
422
-
423
-			// Identical share already existst
424
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
425
-				throw new \Exception('Path is already shared with this user');
426
-			}
427
-
428
-			// The share is already shared with this user via a group share
429
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
430
-				$group = $this->groupManager->get($existingShare->getSharedWith());
431
-				if (!is_null($group)) {
432
-					$user = $this->userManager->get($share->getSharedWith());
433
-
434
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
435
-						throw new \Exception('Path is already shared with this user');
436
-					}
437
-				}
438
-			}
439
-		}
440
-	}
441
-
442
-	/**
443
-	 * Check for pre share requirements for group shares
444
-	 *
445
-	 * @param \OCP\Share\IShare $share
446
-	 * @throws \Exception
447
-	 */
448
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
449
-		// Verify group shares are allowed
450
-		if (!$this->allowGroupSharing()) {
451
-			throw new \Exception('Group sharing is now allowed');
452
-		}
453
-
454
-		// Verify if the user can share with this group
455
-		if ($this->shareWithGroupMembersOnly()) {
456
-			$sharedBy = $this->userManager->get($share->getSharedBy());
457
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
458
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
459
-				throw new \Exception('Sharing is only allowed within your own groups');
460
-			}
461
-		}
462
-
463
-		/*
411
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412
+        $existingShares = $provider->getSharesByPath($share->getNode());
413
+        foreach($existingShares as $existingShare) {
414
+            // Ignore if it is the same share
415
+            try {
416
+                if ($existingShare->getFullId() === $share->getFullId()) {
417
+                    continue;
418
+                }
419
+            } catch (\UnexpectedValueException $e) {
420
+                //Shares are not identical
421
+            }
422
+
423
+            // Identical share already existst
424
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
425
+                throw new \Exception('Path is already shared with this user');
426
+            }
427
+
428
+            // The share is already shared with this user via a group share
429
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
430
+                $group = $this->groupManager->get($existingShare->getSharedWith());
431
+                if (!is_null($group)) {
432
+                    $user = $this->userManager->get($share->getSharedWith());
433
+
434
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
435
+                        throw new \Exception('Path is already shared with this user');
436
+                    }
437
+                }
438
+            }
439
+        }
440
+    }
441
+
442
+    /**
443
+     * Check for pre share requirements for group shares
444
+     *
445
+     * @param \OCP\Share\IShare $share
446
+     * @throws \Exception
447
+     */
448
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
449
+        // Verify group shares are allowed
450
+        if (!$this->allowGroupSharing()) {
451
+            throw new \Exception('Group sharing is now allowed');
452
+        }
453
+
454
+        // Verify if the user can share with this group
455
+        if ($this->shareWithGroupMembersOnly()) {
456
+            $sharedBy = $this->userManager->get($share->getSharedBy());
457
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
458
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
459
+                throw new \Exception('Sharing is only allowed within your own groups');
460
+            }
461
+        }
462
+
463
+        /*
464 464
 		 * TODO: Could be costly, fix
465 465
 		 *
466 466
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
467 467
 		 */
468
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469
-		$existingShares = $provider->getSharesByPath($share->getNode());
470
-		foreach($existingShares as $existingShare) {
471
-			try {
472
-				if ($existingShare->getFullId() === $share->getFullId()) {
473
-					continue;
474
-				}
475
-			} catch (\UnexpectedValueException $e) {
476
-				//It is a new share so just continue
477
-			}
478
-
479
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
480
-				throw new \Exception('Path is already shared with this group');
481
-			}
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * Check for pre share requirements for link shares
487
-	 *
488
-	 * @param \OCP\Share\IShare $share
489
-	 * @throws \Exception
490
-	 */
491
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
492
-		// Are link shares allowed?
493
-		if (!$this->shareApiAllowLinks()) {
494
-			throw new \Exception('Link sharing is not allowed');
495
-		}
496
-
497
-		// Link shares by definition can't have share permissions
498
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
499
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
500
-		}
501
-
502
-		// Check if public upload is allowed
503
-		if (!$this->shareApiLinkAllowPublicUpload() &&
504
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
505
-			throw new \InvalidArgumentException('Public upload is not allowed');
506
-		}
507
-	}
508
-
509
-	/**
510
-	 * To make sure we don't get invisible link shares we set the parent
511
-	 * of a link if it is a reshare. This is a quick word around
512
-	 * until we can properly display multiple link shares in the UI
513
-	 *
514
-	 * See: https://github.com/owncloud/core/issues/22295
515
-	 *
516
-	 * FIXME: Remove once multiple link shares can be properly displayed
517
-	 *
518
-	 * @param \OCP\Share\IShare $share
519
-	 */
520
-	protected function setLinkParent(\OCP\Share\IShare $share) {
521
-
522
-		// No sense in checking if the method is not there.
523
-		if (method_exists($share, 'setParent')) {
524
-			$storage = $share->getNode()->getStorage();
525
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
526
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
527
-				$share->setParent($storage->getShareId());
528
-			}
529
-		};
530
-	}
531
-
532
-	/**
533
-	 * @param File|Folder $path
534
-	 */
535
-	protected function pathCreateChecks($path) {
536
-		// Make sure that we do not share a path that contains a shared mountpoint
537
-		if ($path instanceof \OCP\Files\Folder) {
538
-			$mounts = $this->mountManager->findIn($path->getPath());
539
-			foreach($mounts as $mount) {
540
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541
-					throw new \InvalidArgumentException('Path contains files shared with you');
542
-				}
543
-			}
544
-		}
545
-	}
546
-
547
-	/**
548
-	 * Check if the user that is sharing can actually share
549
-	 *
550
-	 * @param \OCP\Share\IShare $share
551
-	 * @throws \Exception
552
-	 */
553
-	protected function canShare(\OCP\Share\IShare $share) {
554
-		if (!$this->shareApiEnabled()) {
555
-			throw new \Exception('Sharing is disabled');
556
-		}
557
-
558
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
559
-			throw new \Exception('Sharing is disabled for you');
560
-		}
561
-	}
562
-
563
-	/**
564
-	 * Share a path
565
-	 *
566
-	 * @param \OCP\Share\IShare $share
567
-	 * @return Share The share object
568
-	 * @throws \Exception
569
-	 *
570
-	 * TODO: handle link share permissions or check them
571
-	 */
572
-	public function createShare(\OCP\Share\IShare $share) {
573
-		$this->canShare($share);
574
-
575
-		$this->generalCreateChecks($share);
576
-
577
-		// Verify if there are any issues with the path
578
-		$this->pathCreateChecks($share->getNode());
579
-
580
-		/*
468
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469
+        $existingShares = $provider->getSharesByPath($share->getNode());
470
+        foreach($existingShares as $existingShare) {
471
+            try {
472
+                if ($existingShare->getFullId() === $share->getFullId()) {
473
+                    continue;
474
+                }
475
+            } catch (\UnexpectedValueException $e) {
476
+                //It is a new share so just continue
477
+            }
478
+
479
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
480
+                throw new \Exception('Path is already shared with this group');
481
+            }
482
+        }
483
+    }
484
+
485
+    /**
486
+     * Check for pre share requirements for link shares
487
+     *
488
+     * @param \OCP\Share\IShare $share
489
+     * @throws \Exception
490
+     */
491
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
492
+        // Are link shares allowed?
493
+        if (!$this->shareApiAllowLinks()) {
494
+            throw new \Exception('Link sharing is not allowed');
495
+        }
496
+
497
+        // Link shares by definition can't have share permissions
498
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
499
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
500
+        }
501
+
502
+        // Check if public upload is allowed
503
+        if (!$this->shareApiLinkAllowPublicUpload() &&
504
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
505
+            throw new \InvalidArgumentException('Public upload is not allowed');
506
+        }
507
+    }
508
+
509
+    /**
510
+     * To make sure we don't get invisible link shares we set the parent
511
+     * of a link if it is a reshare. This is a quick word around
512
+     * until we can properly display multiple link shares in the UI
513
+     *
514
+     * See: https://github.com/owncloud/core/issues/22295
515
+     *
516
+     * FIXME: Remove once multiple link shares can be properly displayed
517
+     *
518
+     * @param \OCP\Share\IShare $share
519
+     */
520
+    protected function setLinkParent(\OCP\Share\IShare $share) {
521
+
522
+        // No sense in checking if the method is not there.
523
+        if (method_exists($share, 'setParent')) {
524
+            $storage = $share->getNode()->getStorage();
525
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
526
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
527
+                $share->setParent($storage->getShareId());
528
+            }
529
+        };
530
+    }
531
+
532
+    /**
533
+     * @param File|Folder $path
534
+     */
535
+    protected function pathCreateChecks($path) {
536
+        // Make sure that we do not share a path that contains a shared mountpoint
537
+        if ($path instanceof \OCP\Files\Folder) {
538
+            $mounts = $this->mountManager->findIn($path->getPath());
539
+            foreach($mounts as $mount) {
540
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541
+                    throw new \InvalidArgumentException('Path contains files shared with you');
542
+                }
543
+            }
544
+        }
545
+    }
546
+
547
+    /**
548
+     * Check if the user that is sharing can actually share
549
+     *
550
+     * @param \OCP\Share\IShare $share
551
+     * @throws \Exception
552
+     */
553
+    protected function canShare(\OCP\Share\IShare $share) {
554
+        if (!$this->shareApiEnabled()) {
555
+            throw new \Exception('Sharing is disabled');
556
+        }
557
+
558
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
559
+            throw new \Exception('Sharing is disabled for you');
560
+        }
561
+    }
562
+
563
+    /**
564
+     * Share a path
565
+     *
566
+     * @param \OCP\Share\IShare $share
567
+     * @return Share The share object
568
+     * @throws \Exception
569
+     *
570
+     * TODO: handle link share permissions or check them
571
+     */
572
+    public function createShare(\OCP\Share\IShare $share) {
573
+        $this->canShare($share);
574
+
575
+        $this->generalCreateChecks($share);
576
+
577
+        // Verify if there are any issues with the path
578
+        $this->pathCreateChecks($share->getNode());
579
+
580
+        /*
581 581
 		 * On creation of a share the owner is always the owner of the path
582 582
 		 * Except for mounted federated shares.
583 583
 		 */
584
-		$storage = $share->getNode()->getStorage();
585
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586
-			$parent = $share->getNode()->getParent();
587
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588
-				$parent = $parent->getParent();
589
-			}
590
-			$share->setShareOwner($parent->getOwner()->getUID());
591
-		} else {
592
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
593
-		}
594
-
595
-		//Verify share type
596
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
-			$this->userCreateChecks($share);
598
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
-			$this->groupCreateChecks($share);
600
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
601
-			$this->linkCreateChecks($share);
602
-			$this->setLinkParent($share);
603
-
604
-			/*
584
+        $storage = $share->getNode()->getStorage();
585
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586
+            $parent = $share->getNode()->getParent();
587
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588
+                $parent = $parent->getParent();
589
+            }
590
+            $share->setShareOwner($parent->getOwner()->getUID());
591
+        } else {
592
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
593
+        }
594
+
595
+        //Verify share type
596
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
+            $this->userCreateChecks($share);
598
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
+            $this->groupCreateChecks($share);
600
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
601
+            $this->linkCreateChecks($share);
602
+            $this->setLinkParent($share);
603
+
604
+            /*
605 605
 			 * For now ignore a set token.
606 606
 			 */
607
-			$share->setToken(
608
-				$this->secureRandom->generate(
609
-					\OC\Share\Constants::TOKEN_LENGTH,
610
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
611
-				)
612
-			);
613
-
614
-			//Verify the expiration date
615
-			$this->validateExpirationDate($share);
616
-
617
-			//Verify the password
618
-			$this->verifyPassword($share->getPassword());
619
-
620
-			// If a password is set. Hash it!
621
-			if ($share->getPassword() !== null) {
622
-				$share->setPassword($this->hasher->hash($share->getPassword()));
623
-			}
624
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
-			$share->setToken(
626
-				$this->secureRandom->generate(
627
-					\OC\Share\Constants::TOKEN_LENGTH,
628
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
629
-				)
630
-			);
631
-		}
632
-
633
-		// Cannot share with the owner
634
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
635
-			$share->getSharedWith() === $share->getShareOwner()) {
636
-			throw new \InvalidArgumentException('Can’t share with the share owner');
637
-		}
638
-
639
-		// Generate the target
640
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
641
-		$target = \OC\Files\Filesystem::normalizePath($target);
642
-		$share->setTarget($target);
643
-
644
-		// Pre share event
645
-		$event = new GenericEvent($share);
646
-		$a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
647
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
648
-			throw new \Exception($event->getArgument('error'));
649
-		}
650
-
651
-		$oldShare = $share;
652
-		$provider = $this->factory->getProviderForType($share->getShareType());
653
-		$share = $provider->create($share);
654
-		//reuse the node we already have
655
-		$share->setNode($oldShare->getNode());
656
-
657
-		// Post share event
658
-		$event = new GenericEvent($share);
659
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
660
-
661
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662
-			$user = $this->userManager->get($share->getSharedWith());
663
-			if ($user !== null) {
664
-				$emailAddress = $user->getEMailAddress();
665
-				if ($emailAddress !== null && $emailAddress !== '') {
666
-					$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
667
-					$l = $this->l10nFactory->get('lib', $userLang);
668
-					$this->sendMailNotification(
669
-						$l,
670
-						$share->getNode()->getName(),
671
-						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
672
-						$share->getSharedBy(),
673
-						$emailAddress,
674
-						$share->getExpirationDate()
675
-					);
676
-					$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
677
-				} else {
678
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
679
-				}
680
-			} else {
681
-				$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
682
-			}
683
-		}
684
-
685
-		return $share;
686
-	}
687
-
688
-	/**
689
-	 * @param IL10N $l Language of the recipient
690
-	 * @param string $filename file/folder name
691
-	 * @param string $link link to the file/folder
692
-	 * @param string $initiator user ID of share sender
693
-	 * @param string $shareWith email address of share receiver
694
-	 * @param \DateTime|null $expiration
695
-	 * @throws \Exception If mail couldn't be sent
696
-	 */
697
-	protected function sendMailNotification(IL10N $l,
698
-											$filename,
699
-											$link,
700
-											$initiator,
701
-											$shareWith,
702
-											\DateTime $expiration = null) {
703
-		$initiatorUser = $this->userManager->get($initiator);
704
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
705
-		$subject = $l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename));
706
-
707
-		$message = $this->mailer->createMessage();
708
-
709
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
710
-			'filename' => $filename,
711
-			'link' => $link,
712
-			'initiator' => $initiatorDisplayName,
713
-			'expiration' => $expiration,
714
-			'shareWith' => $shareWith,
715
-		]);
716
-
717
-		$emailTemplate->addHeader();
718
-		$emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
719
-		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
720
-
721
-		$emailTemplate->addBodyText(
722
-			$text . ' ' . $l->t('Click the button below to open it.'),
723
-			$text
724
-		);
725
-		$emailTemplate->addBodyButton(
726
-			$l->t('Open »%s«', [$filename]),
727
-			$link
728
-		);
729
-
730
-		$message->setTo([$shareWith]);
731
-
732
-		// The "From" contains the sharers name
733
-		$instanceName = $this->defaults->getName();
734
-		$senderName = $l->t(
735
-			'%s via %s',
736
-			[
737
-				$initiatorDisplayName,
738
-				$instanceName
739
-			]
740
-		);
741
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
742
-
743
-		// The "Reply-To" is set to the sharer if an mail address is configured
744
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
745
-		$initiatorEmail = $initiatorUser->getEMailAddress();
746
-		if($initiatorEmail !== null) {
747
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
748
-			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
749
-		} else {
750
-			$emailTemplate->addFooter();
751
-		}
752
-
753
-		$message->setSubject($subject);
754
-		$message->setPlainBody($emailTemplate->renderText());
755
-		$message->setHtmlBody($emailTemplate->renderHtml());
756
-		$this->mailer->send($message);
757
-	}
758
-
759
-	/**
760
-	 * Update a share
761
-	 *
762
-	 * @param \OCP\Share\IShare $share
763
-	 * @return \OCP\Share\IShare The share object
764
-	 * @throws \InvalidArgumentException
765
-	 */
766
-	public function updateShare(\OCP\Share\IShare $share) {
767
-		$expirationDateUpdated = false;
768
-
769
-		$this->canShare($share);
770
-
771
-		try {
772
-			$originalShare = $this->getShareById($share->getFullId());
773
-		} catch (\UnexpectedValueException $e) {
774
-			throw new \InvalidArgumentException('Share does not have a full id');
775
-		}
776
-
777
-		// We can't change the share type!
778
-		if ($share->getShareType() !== $originalShare->getShareType()) {
779
-			throw new \InvalidArgumentException('Can’t change share type');
780
-		}
781
-
782
-		// We can only change the recipient on user shares
783
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
784
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
785
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
786
-		}
787
-
788
-		// Cannot share with the owner
789
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
790
-			$share->getSharedWith() === $share->getShareOwner()) {
791
-			throw new \InvalidArgumentException('Can’t share with the share owner');
792
-		}
793
-
794
-		$this->generalCreateChecks($share);
795
-
796
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
797
-			$this->userCreateChecks($share);
798
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
799
-			$this->groupCreateChecks($share);
800
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
801
-			$this->linkCreateChecks($share);
802
-
803
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
804
-
805
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
806
-				//Verify the expiration date
807
-				$this->validateExpirationDate($share);
808
-				$expirationDateUpdated = true;
809
-			}
810
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
811
-			$plainTextPassword = $share->getPassword();
812
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
813
-				$plainTextPassword = null;
814
-			}
815
-		}
816
-
817
-		$this->pathCreateChecks($share->getNode());
818
-
819
-		// Now update the share!
820
-		$provider = $this->factory->getProviderForType($share->getShareType());
821
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
822
-			$share = $provider->update($share, $plainTextPassword);
823
-		} else {
824
-			$share = $provider->update($share);
825
-		}
826
-
827
-		if ($expirationDateUpdated === true) {
828
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
829
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
830
-				'itemSource' => $share->getNode()->getId(),
831
-				'date' => $share->getExpirationDate(),
832
-				'uidOwner' => $share->getSharedBy(),
833
-			]);
834
-		}
835
-
836
-		if ($share->getPassword() !== $originalShare->getPassword()) {
837
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
838
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
839
-				'itemSource' => $share->getNode()->getId(),
840
-				'uidOwner' => $share->getSharedBy(),
841
-				'token' => $share->getToken(),
842
-				'disabled' => is_null($share->getPassword()),
843
-			]);
844
-		}
845
-
846
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
847
-			if ($this->userManager->userExists($share->getShareOwner())) {
848
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
849
-			} else {
850
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
851
-			}
852
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
853
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
854
-				'itemSource' => $share->getNode()->getId(),
855
-				'shareType' => $share->getShareType(),
856
-				'shareWith' => $share->getSharedWith(),
857
-				'uidOwner' => $share->getSharedBy(),
858
-				'permissions' => $share->getPermissions(),
859
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
860
-			));
861
-		}
862
-
863
-		return $share;
864
-	}
865
-
866
-	/**
867
-	 * Updates the password of the given share if it is not the same as the
868
-	 * password of the original share.
869
-	 *
870
-	 * @param \OCP\Share\IShare $share the share to update its password.
871
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
872
-	 *        password with.
873
-	 * @return boolean whether the password was updated or not.
874
-	 */
875
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
876
-		// Password updated.
877
-		if ($share->getPassword() !== $originalShare->getPassword()) {
878
-			//Verify the password
879
-			$this->verifyPassword($share->getPassword());
880
-
881
-			// If a password is set. Hash it!
882
-			if ($share->getPassword() !== null) {
883
-				$share->setPassword($this->hasher->hash($share->getPassword()));
884
-
885
-				return true;
886
-			}
887
-		}
888
-
889
-		return false;
890
-	}
891
-
892
-	/**
893
-	 * Delete all the children of this share
894
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
895
-	 *
896
-	 * @param \OCP\Share\IShare $share
897
-	 * @return \OCP\Share\IShare[] List of deleted shares
898
-	 */
899
-	protected function deleteChildren(\OCP\Share\IShare $share) {
900
-		$deletedShares = [];
901
-
902
-		$provider = $this->factory->getProviderForType($share->getShareType());
903
-
904
-		foreach ($provider->getChildren($share) as $child) {
905
-			$deletedChildren = $this->deleteChildren($child);
906
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
907
-
908
-			$provider->delete($child);
909
-			$deletedShares[] = $child;
910
-		}
911
-
912
-		return $deletedShares;
913
-	}
914
-
915
-	/**
916
-	 * Delete a share
917
-	 *
918
-	 * @param \OCP\Share\IShare $share
919
-	 * @throws ShareNotFound
920
-	 * @throws \InvalidArgumentException
921
-	 */
922
-	public function deleteShare(\OCP\Share\IShare $share) {
923
-
924
-		try {
925
-			$share->getFullId();
926
-		} catch (\UnexpectedValueException $e) {
927
-			throw new \InvalidArgumentException('Share does not have a full id');
928
-		}
929
-
930
-		$event = new GenericEvent($share);
931
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
932
-
933
-		// Get all children and delete them as well
934
-		$deletedShares = $this->deleteChildren($share);
935
-
936
-		// Do the actual delete
937
-		$provider = $this->factory->getProviderForType($share->getShareType());
938
-		$provider->delete($share);
939
-
940
-		// All the deleted shares caused by this delete
941
-		$deletedShares[] = $share;
942
-
943
-		// Emit post hook
944
-		$event->setArgument('deletedShares', $deletedShares);
945
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
946
-	}
947
-
948
-
949
-	/**
950
-	 * Unshare a file as the recipient.
951
-	 * This can be different from a regular delete for example when one of
952
-	 * the users in a groups deletes that share. But the provider should
953
-	 * handle this.
954
-	 *
955
-	 * @param \OCP\Share\IShare $share
956
-	 * @param string $recipientId
957
-	 */
958
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
959
-		list($providerId, ) = $this->splitFullId($share->getFullId());
960
-		$provider = $this->factory->getProvider($providerId);
961
-
962
-		$provider->deleteFromSelf($share, $recipientId);
963
-		$event = new GenericEvent($share);
964
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
965
-	}
966
-
967
-	/**
968
-	 * @inheritdoc
969
-	 */
970
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
971
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
972
-			throw new \InvalidArgumentException('Can’t change target of link share');
973
-		}
974
-
975
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
976
-			throw new \InvalidArgumentException('Invalid recipient');
977
-		}
978
-
979
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
980
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
981
-			if (is_null($sharedWith)) {
982
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
983
-			}
984
-			$recipient = $this->userManager->get($recipientId);
985
-			if (!$sharedWith->inGroup($recipient)) {
986
-				throw new \InvalidArgumentException('Invalid recipient');
987
-			}
988
-		}
989
-
990
-		list($providerId, ) = $this->splitFullId($share->getFullId());
991
-		$provider = $this->factory->getProvider($providerId);
992
-
993
-		$provider->move($share, $recipientId);
994
-	}
995
-
996
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
997
-		$providers = $this->factory->getAllProviders();
998
-
999
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1000
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1001
-			foreach ($newShares as $fid => $data) {
1002
-				if (!isset($shares[$fid])) {
1003
-					$shares[$fid] = [];
1004
-				}
1005
-
1006
-				$shares[$fid] = array_merge($shares[$fid], $data);
1007
-			}
1008
-			return $shares;
1009
-		}, []);
1010
-	}
1011
-
1012
-	/**
1013
-	 * @inheritdoc
1014
-	 */
1015
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1016
-		if ($path !== null &&
1017
-				!($path instanceof \OCP\Files\File) &&
1018
-				!($path instanceof \OCP\Files\Folder)) {
1019
-			throw new \InvalidArgumentException('invalid path');
1020
-		}
1021
-
1022
-		try {
1023
-			$provider = $this->factory->getProviderForType($shareType);
1024
-		} catch (ProviderException $e) {
1025
-			return [];
1026
-		}
1027
-
1028
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1029
-
1030
-		/*
607
+            $share->setToken(
608
+                $this->secureRandom->generate(
609
+                    \OC\Share\Constants::TOKEN_LENGTH,
610
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
611
+                )
612
+            );
613
+
614
+            //Verify the expiration date
615
+            $this->validateExpirationDate($share);
616
+
617
+            //Verify the password
618
+            $this->verifyPassword($share->getPassword());
619
+
620
+            // If a password is set. Hash it!
621
+            if ($share->getPassword() !== null) {
622
+                $share->setPassword($this->hasher->hash($share->getPassword()));
623
+            }
624
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
+            $share->setToken(
626
+                $this->secureRandom->generate(
627
+                    \OC\Share\Constants::TOKEN_LENGTH,
628
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
629
+                )
630
+            );
631
+        }
632
+
633
+        // Cannot share with the owner
634
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
635
+            $share->getSharedWith() === $share->getShareOwner()) {
636
+            throw new \InvalidArgumentException('Can’t share with the share owner');
637
+        }
638
+
639
+        // Generate the target
640
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
641
+        $target = \OC\Files\Filesystem::normalizePath($target);
642
+        $share->setTarget($target);
643
+
644
+        // Pre share event
645
+        $event = new GenericEvent($share);
646
+        $a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
647
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
648
+            throw new \Exception($event->getArgument('error'));
649
+        }
650
+
651
+        $oldShare = $share;
652
+        $provider = $this->factory->getProviderForType($share->getShareType());
653
+        $share = $provider->create($share);
654
+        //reuse the node we already have
655
+        $share->setNode($oldShare->getNode());
656
+
657
+        // Post share event
658
+        $event = new GenericEvent($share);
659
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
660
+
661
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662
+            $user = $this->userManager->get($share->getSharedWith());
663
+            if ($user !== null) {
664
+                $emailAddress = $user->getEMailAddress();
665
+                if ($emailAddress !== null && $emailAddress !== '') {
666
+                    $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
667
+                    $l = $this->l10nFactory->get('lib', $userLang);
668
+                    $this->sendMailNotification(
669
+                        $l,
670
+                        $share->getNode()->getName(),
671
+                        $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
672
+                        $share->getSharedBy(),
673
+                        $emailAddress,
674
+                        $share->getExpirationDate()
675
+                    );
676
+                    $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
677
+                } else {
678
+                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
679
+                }
680
+            } else {
681
+                $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
682
+            }
683
+        }
684
+
685
+        return $share;
686
+    }
687
+
688
+    /**
689
+     * @param IL10N $l Language of the recipient
690
+     * @param string $filename file/folder name
691
+     * @param string $link link to the file/folder
692
+     * @param string $initiator user ID of share sender
693
+     * @param string $shareWith email address of share receiver
694
+     * @param \DateTime|null $expiration
695
+     * @throws \Exception If mail couldn't be sent
696
+     */
697
+    protected function sendMailNotification(IL10N $l,
698
+                                            $filename,
699
+                                            $link,
700
+                                            $initiator,
701
+                                            $shareWith,
702
+                                            \DateTime $expiration = null) {
703
+        $initiatorUser = $this->userManager->get($initiator);
704
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
705
+        $subject = $l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename));
706
+
707
+        $message = $this->mailer->createMessage();
708
+
709
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
710
+            'filename' => $filename,
711
+            'link' => $link,
712
+            'initiator' => $initiatorDisplayName,
713
+            'expiration' => $expiration,
714
+            'shareWith' => $shareWith,
715
+        ]);
716
+
717
+        $emailTemplate->addHeader();
718
+        $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
719
+        $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
720
+
721
+        $emailTemplate->addBodyText(
722
+            $text . ' ' . $l->t('Click the button below to open it.'),
723
+            $text
724
+        );
725
+        $emailTemplate->addBodyButton(
726
+            $l->t('Open »%s«', [$filename]),
727
+            $link
728
+        );
729
+
730
+        $message->setTo([$shareWith]);
731
+
732
+        // The "From" contains the sharers name
733
+        $instanceName = $this->defaults->getName();
734
+        $senderName = $l->t(
735
+            '%s via %s',
736
+            [
737
+                $initiatorDisplayName,
738
+                $instanceName
739
+            ]
740
+        );
741
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
742
+
743
+        // The "Reply-To" is set to the sharer if an mail address is configured
744
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
745
+        $initiatorEmail = $initiatorUser->getEMailAddress();
746
+        if($initiatorEmail !== null) {
747
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
748
+            $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
749
+        } else {
750
+            $emailTemplate->addFooter();
751
+        }
752
+
753
+        $message->setSubject($subject);
754
+        $message->setPlainBody($emailTemplate->renderText());
755
+        $message->setHtmlBody($emailTemplate->renderHtml());
756
+        $this->mailer->send($message);
757
+    }
758
+
759
+    /**
760
+     * Update a share
761
+     *
762
+     * @param \OCP\Share\IShare $share
763
+     * @return \OCP\Share\IShare The share object
764
+     * @throws \InvalidArgumentException
765
+     */
766
+    public function updateShare(\OCP\Share\IShare $share) {
767
+        $expirationDateUpdated = false;
768
+
769
+        $this->canShare($share);
770
+
771
+        try {
772
+            $originalShare = $this->getShareById($share->getFullId());
773
+        } catch (\UnexpectedValueException $e) {
774
+            throw new \InvalidArgumentException('Share does not have a full id');
775
+        }
776
+
777
+        // We can't change the share type!
778
+        if ($share->getShareType() !== $originalShare->getShareType()) {
779
+            throw new \InvalidArgumentException('Can’t change share type');
780
+        }
781
+
782
+        // We can only change the recipient on user shares
783
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
784
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
785
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
786
+        }
787
+
788
+        // Cannot share with the owner
789
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
790
+            $share->getSharedWith() === $share->getShareOwner()) {
791
+            throw new \InvalidArgumentException('Can’t share with the share owner');
792
+        }
793
+
794
+        $this->generalCreateChecks($share);
795
+
796
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
797
+            $this->userCreateChecks($share);
798
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
799
+            $this->groupCreateChecks($share);
800
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
801
+            $this->linkCreateChecks($share);
802
+
803
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
804
+
805
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
806
+                //Verify the expiration date
807
+                $this->validateExpirationDate($share);
808
+                $expirationDateUpdated = true;
809
+            }
810
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
811
+            $plainTextPassword = $share->getPassword();
812
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
813
+                $plainTextPassword = null;
814
+            }
815
+        }
816
+
817
+        $this->pathCreateChecks($share->getNode());
818
+
819
+        // Now update the share!
820
+        $provider = $this->factory->getProviderForType($share->getShareType());
821
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
822
+            $share = $provider->update($share, $plainTextPassword);
823
+        } else {
824
+            $share = $provider->update($share);
825
+        }
826
+
827
+        if ($expirationDateUpdated === true) {
828
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
829
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
830
+                'itemSource' => $share->getNode()->getId(),
831
+                'date' => $share->getExpirationDate(),
832
+                'uidOwner' => $share->getSharedBy(),
833
+            ]);
834
+        }
835
+
836
+        if ($share->getPassword() !== $originalShare->getPassword()) {
837
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
838
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
839
+                'itemSource' => $share->getNode()->getId(),
840
+                'uidOwner' => $share->getSharedBy(),
841
+                'token' => $share->getToken(),
842
+                'disabled' => is_null($share->getPassword()),
843
+            ]);
844
+        }
845
+
846
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
847
+            if ($this->userManager->userExists($share->getShareOwner())) {
848
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
849
+            } else {
850
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
851
+            }
852
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
853
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
854
+                'itemSource' => $share->getNode()->getId(),
855
+                'shareType' => $share->getShareType(),
856
+                'shareWith' => $share->getSharedWith(),
857
+                'uidOwner' => $share->getSharedBy(),
858
+                'permissions' => $share->getPermissions(),
859
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
860
+            ));
861
+        }
862
+
863
+        return $share;
864
+    }
865
+
866
+    /**
867
+     * Updates the password of the given share if it is not the same as the
868
+     * password of the original share.
869
+     *
870
+     * @param \OCP\Share\IShare $share the share to update its password.
871
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
872
+     *        password with.
873
+     * @return boolean whether the password was updated or not.
874
+     */
875
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
876
+        // Password updated.
877
+        if ($share->getPassword() !== $originalShare->getPassword()) {
878
+            //Verify the password
879
+            $this->verifyPassword($share->getPassword());
880
+
881
+            // If a password is set. Hash it!
882
+            if ($share->getPassword() !== null) {
883
+                $share->setPassword($this->hasher->hash($share->getPassword()));
884
+
885
+                return true;
886
+            }
887
+        }
888
+
889
+        return false;
890
+    }
891
+
892
+    /**
893
+     * Delete all the children of this share
894
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
895
+     *
896
+     * @param \OCP\Share\IShare $share
897
+     * @return \OCP\Share\IShare[] List of deleted shares
898
+     */
899
+    protected function deleteChildren(\OCP\Share\IShare $share) {
900
+        $deletedShares = [];
901
+
902
+        $provider = $this->factory->getProviderForType($share->getShareType());
903
+
904
+        foreach ($provider->getChildren($share) as $child) {
905
+            $deletedChildren = $this->deleteChildren($child);
906
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
907
+
908
+            $provider->delete($child);
909
+            $deletedShares[] = $child;
910
+        }
911
+
912
+        return $deletedShares;
913
+    }
914
+
915
+    /**
916
+     * Delete a share
917
+     *
918
+     * @param \OCP\Share\IShare $share
919
+     * @throws ShareNotFound
920
+     * @throws \InvalidArgumentException
921
+     */
922
+    public function deleteShare(\OCP\Share\IShare $share) {
923
+
924
+        try {
925
+            $share->getFullId();
926
+        } catch (\UnexpectedValueException $e) {
927
+            throw new \InvalidArgumentException('Share does not have a full id');
928
+        }
929
+
930
+        $event = new GenericEvent($share);
931
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
932
+
933
+        // Get all children and delete them as well
934
+        $deletedShares = $this->deleteChildren($share);
935
+
936
+        // Do the actual delete
937
+        $provider = $this->factory->getProviderForType($share->getShareType());
938
+        $provider->delete($share);
939
+
940
+        // All the deleted shares caused by this delete
941
+        $deletedShares[] = $share;
942
+
943
+        // Emit post hook
944
+        $event->setArgument('deletedShares', $deletedShares);
945
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
946
+    }
947
+
948
+
949
+    /**
950
+     * Unshare a file as the recipient.
951
+     * This can be different from a regular delete for example when one of
952
+     * the users in a groups deletes that share. But the provider should
953
+     * handle this.
954
+     *
955
+     * @param \OCP\Share\IShare $share
956
+     * @param string $recipientId
957
+     */
958
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
959
+        list($providerId, ) = $this->splitFullId($share->getFullId());
960
+        $provider = $this->factory->getProvider($providerId);
961
+
962
+        $provider->deleteFromSelf($share, $recipientId);
963
+        $event = new GenericEvent($share);
964
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
965
+    }
966
+
967
+    /**
968
+     * @inheritdoc
969
+     */
970
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
971
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
972
+            throw new \InvalidArgumentException('Can’t change target of link share');
973
+        }
974
+
975
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
976
+            throw new \InvalidArgumentException('Invalid recipient');
977
+        }
978
+
979
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
980
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
981
+            if (is_null($sharedWith)) {
982
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
983
+            }
984
+            $recipient = $this->userManager->get($recipientId);
985
+            if (!$sharedWith->inGroup($recipient)) {
986
+                throw new \InvalidArgumentException('Invalid recipient');
987
+            }
988
+        }
989
+
990
+        list($providerId, ) = $this->splitFullId($share->getFullId());
991
+        $provider = $this->factory->getProvider($providerId);
992
+
993
+        $provider->move($share, $recipientId);
994
+    }
995
+
996
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
997
+        $providers = $this->factory->getAllProviders();
998
+
999
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1000
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1001
+            foreach ($newShares as $fid => $data) {
1002
+                if (!isset($shares[$fid])) {
1003
+                    $shares[$fid] = [];
1004
+                }
1005
+
1006
+                $shares[$fid] = array_merge($shares[$fid], $data);
1007
+            }
1008
+            return $shares;
1009
+        }, []);
1010
+    }
1011
+
1012
+    /**
1013
+     * @inheritdoc
1014
+     */
1015
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1016
+        if ($path !== null &&
1017
+                !($path instanceof \OCP\Files\File) &&
1018
+                !($path instanceof \OCP\Files\Folder)) {
1019
+            throw new \InvalidArgumentException('invalid path');
1020
+        }
1021
+
1022
+        try {
1023
+            $provider = $this->factory->getProviderForType($shareType);
1024
+        } catch (ProviderException $e) {
1025
+            return [];
1026
+        }
1027
+
1028
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1029
+
1030
+        /*
1031 1031
 		 * Work around so we don't return expired shares but still follow
1032 1032
 		 * proper pagination.
1033 1033
 		 */
1034 1034
 
1035
-		$shares2 = [];
1036
-
1037
-		while(true) {
1038
-			$added = 0;
1039
-			foreach ($shares as $share) {
1040
-
1041
-				try {
1042
-					$this->checkExpireDate($share);
1043
-				} catch (ShareNotFound $e) {
1044
-					//Ignore since this basically means the share is deleted
1045
-					continue;
1046
-				}
1047
-
1048
-				$added++;
1049
-				$shares2[] = $share;
1050
-
1051
-				if (count($shares2) === $limit) {
1052
-					break;
1053
-				}
1054
-			}
1055
-
1056
-			if (count($shares2) === $limit) {
1057
-				break;
1058
-			}
1059
-
1060
-			// If there was no limit on the select we are done
1061
-			if ($limit === -1) {
1062
-				break;
1063
-			}
1064
-
1065
-			$offset += $added;
1066
-
1067
-			// Fetch again $limit shares
1068
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1069
-
1070
-			// No more shares means we are done
1071
-			if (empty($shares)) {
1072
-				break;
1073
-			}
1074
-		}
1075
-
1076
-		$shares = $shares2;
1077
-
1078
-		return $shares;
1079
-	}
1080
-
1081
-	/**
1082
-	 * @inheritdoc
1083
-	 */
1084
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1085
-		try {
1086
-			$provider = $this->factory->getProviderForType($shareType);
1087
-		} catch (ProviderException $e) {
1088
-			return [];
1089
-		}
1090
-
1091
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1092
-
1093
-		// remove all shares which are already expired
1094
-		foreach ($shares as $key => $share) {
1095
-			try {
1096
-				$this->checkExpireDate($share);
1097
-			} catch (ShareNotFound $e) {
1098
-				unset($shares[$key]);
1099
-			}
1100
-		}
1101
-
1102
-		return $shares;
1103
-	}
1104
-
1105
-	/**
1106
-	 * @inheritdoc
1107
-	 */
1108
-	public function getShareById($id, $recipient = null) {
1109
-		if ($id === null) {
1110
-			throw new ShareNotFound();
1111
-		}
1112
-
1113
-		list($providerId, $id) = $this->splitFullId($id);
1114
-
1115
-		try {
1116
-			$provider = $this->factory->getProvider($providerId);
1117
-		} catch (ProviderException $e) {
1118
-			throw new ShareNotFound();
1119
-		}
1120
-
1121
-		$share = $provider->getShareById($id, $recipient);
1122
-
1123
-		$this->checkExpireDate($share);
1124
-
1125
-		return $share;
1126
-	}
1127
-
1128
-	/**
1129
-	 * Get all the shares for a given path
1130
-	 *
1131
-	 * @param \OCP\Files\Node $path
1132
-	 * @param int $page
1133
-	 * @param int $perPage
1134
-	 *
1135
-	 * @return Share[]
1136
-	 */
1137
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1138
-		return [];
1139
-	}
1140
-
1141
-	/**
1142
-	 * Get the share by token possible with password
1143
-	 *
1144
-	 * @param string $token
1145
-	 * @return Share
1146
-	 *
1147
-	 * @throws ShareNotFound
1148
-	 */
1149
-	public function getShareByToken($token) {
1150
-		$share = null;
1151
-		try {
1152
-			if($this->shareApiAllowLinks()) {
1153
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1154
-				$share = $provider->getShareByToken($token);
1155
-			}
1156
-		} catch (ProviderException $e) {
1157
-		} catch (ShareNotFound $e) {
1158
-		}
1159
-
1160
-
1161
-		// If it is not a link share try to fetch a federated share by token
1162
-		if ($share === null) {
1163
-			try {
1164
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1165
-				$share = $provider->getShareByToken($token);
1166
-			} catch (ProviderException $e) {
1167
-			} catch (ShareNotFound $e) {
1168
-			}
1169
-		}
1170
-
1171
-		// If it is not a link share try to fetch a mail share by token
1172
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1173
-			try {
1174
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1175
-				$share = $provider->getShareByToken($token);
1176
-			} catch (ProviderException $e) {
1177
-			} catch (ShareNotFound $e) {
1178
-			}
1179
-		}
1180
-
1181
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1182
-			try {
1183
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1184
-				$share = $provider->getShareByToken($token);
1185
-			} catch (ProviderException $e) {
1186
-			} catch (ShareNotFound $e) {
1187
-			}
1188
-		}
1189
-
1190
-		if ($share === null) {
1191
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1192
-		}
1193
-
1194
-		$this->checkExpireDate($share);
1195
-
1196
-		/*
1035
+        $shares2 = [];
1036
+
1037
+        while(true) {
1038
+            $added = 0;
1039
+            foreach ($shares as $share) {
1040
+
1041
+                try {
1042
+                    $this->checkExpireDate($share);
1043
+                } catch (ShareNotFound $e) {
1044
+                    //Ignore since this basically means the share is deleted
1045
+                    continue;
1046
+                }
1047
+
1048
+                $added++;
1049
+                $shares2[] = $share;
1050
+
1051
+                if (count($shares2) === $limit) {
1052
+                    break;
1053
+                }
1054
+            }
1055
+
1056
+            if (count($shares2) === $limit) {
1057
+                break;
1058
+            }
1059
+
1060
+            // If there was no limit on the select we are done
1061
+            if ($limit === -1) {
1062
+                break;
1063
+            }
1064
+
1065
+            $offset += $added;
1066
+
1067
+            // Fetch again $limit shares
1068
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1069
+
1070
+            // No more shares means we are done
1071
+            if (empty($shares)) {
1072
+                break;
1073
+            }
1074
+        }
1075
+
1076
+        $shares = $shares2;
1077
+
1078
+        return $shares;
1079
+    }
1080
+
1081
+    /**
1082
+     * @inheritdoc
1083
+     */
1084
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1085
+        try {
1086
+            $provider = $this->factory->getProviderForType($shareType);
1087
+        } catch (ProviderException $e) {
1088
+            return [];
1089
+        }
1090
+
1091
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1092
+
1093
+        // remove all shares which are already expired
1094
+        foreach ($shares as $key => $share) {
1095
+            try {
1096
+                $this->checkExpireDate($share);
1097
+            } catch (ShareNotFound $e) {
1098
+                unset($shares[$key]);
1099
+            }
1100
+        }
1101
+
1102
+        return $shares;
1103
+    }
1104
+
1105
+    /**
1106
+     * @inheritdoc
1107
+     */
1108
+    public function getShareById($id, $recipient = null) {
1109
+        if ($id === null) {
1110
+            throw new ShareNotFound();
1111
+        }
1112
+
1113
+        list($providerId, $id) = $this->splitFullId($id);
1114
+
1115
+        try {
1116
+            $provider = $this->factory->getProvider($providerId);
1117
+        } catch (ProviderException $e) {
1118
+            throw new ShareNotFound();
1119
+        }
1120
+
1121
+        $share = $provider->getShareById($id, $recipient);
1122
+
1123
+        $this->checkExpireDate($share);
1124
+
1125
+        return $share;
1126
+    }
1127
+
1128
+    /**
1129
+     * Get all the shares for a given path
1130
+     *
1131
+     * @param \OCP\Files\Node $path
1132
+     * @param int $page
1133
+     * @param int $perPage
1134
+     *
1135
+     * @return Share[]
1136
+     */
1137
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1138
+        return [];
1139
+    }
1140
+
1141
+    /**
1142
+     * Get the share by token possible with password
1143
+     *
1144
+     * @param string $token
1145
+     * @return Share
1146
+     *
1147
+     * @throws ShareNotFound
1148
+     */
1149
+    public function getShareByToken($token) {
1150
+        $share = null;
1151
+        try {
1152
+            if($this->shareApiAllowLinks()) {
1153
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1154
+                $share = $provider->getShareByToken($token);
1155
+            }
1156
+        } catch (ProviderException $e) {
1157
+        } catch (ShareNotFound $e) {
1158
+        }
1159
+
1160
+
1161
+        // If it is not a link share try to fetch a federated share by token
1162
+        if ($share === null) {
1163
+            try {
1164
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1165
+                $share = $provider->getShareByToken($token);
1166
+            } catch (ProviderException $e) {
1167
+            } catch (ShareNotFound $e) {
1168
+            }
1169
+        }
1170
+
1171
+        // If it is not a link share try to fetch a mail share by token
1172
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1173
+            try {
1174
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1175
+                $share = $provider->getShareByToken($token);
1176
+            } catch (ProviderException $e) {
1177
+            } catch (ShareNotFound $e) {
1178
+            }
1179
+        }
1180
+
1181
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1182
+            try {
1183
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1184
+                $share = $provider->getShareByToken($token);
1185
+            } catch (ProviderException $e) {
1186
+            } catch (ShareNotFound $e) {
1187
+            }
1188
+        }
1189
+
1190
+        if ($share === null) {
1191
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1192
+        }
1193
+
1194
+        $this->checkExpireDate($share);
1195
+
1196
+        /*
1197 1197
 		 * Reduce the permissions for link shares if public upload is not enabled
1198 1198
 		 */
1199
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1200
-			!$this->shareApiLinkAllowPublicUpload()) {
1201
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1202
-		}
1203
-
1204
-		return $share;
1205
-	}
1206
-
1207
-	protected function checkExpireDate($share) {
1208
-		if ($share->getExpirationDate() !== null &&
1209
-			$share->getExpirationDate() <= new \DateTime()) {
1210
-			$this->deleteShare($share);
1211
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1212
-		}
1213
-
1214
-	}
1215
-
1216
-	/**
1217
-	 * Verify the password of a public share
1218
-	 *
1219
-	 * @param \OCP\Share\IShare $share
1220
-	 * @param string $password
1221
-	 * @return bool
1222
-	 */
1223
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1224
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1225
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1226
-		if (!$passwordProtected) {
1227
-			//TODO maybe exception?
1228
-			return false;
1229
-		}
1230
-
1231
-		if ($password === null || $share->getPassword() === null) {
1232
-			return false;
1233
-		}
1234
-
1235
-		$newHash = '';
1236
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1237
-			return false;
1238
-		}
1239
-
1240
-		if (!empty($newHash)) {
1241
-			$share->setPassword($newHash);
1242
-			$provider = $this->factory->getProviderForType($share->getShareType());
1243
-			$provider->update($share);
1244
-		}
1245
-
1246
-		return true;
1247
-	}
1248
-
1249
-	/**
1250
-	 * @inheritdoc
1251
-	 */
1252
-	public function userDeleted($uid) {
1253
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1254
-
1255
-		foreach ($types as $type) {
1256
-			try {
1257
-				$provider = $this->factory->getProviderForType($type);
1258
-			} catch (ProviderException $e) {
1259
-				continue;
1260
-			}
1261
-			$provider->userDeleted($uid, $type);
1262
-		}
1263
-	}
1264
-
1265
-	/**
1266
-	 * @inheritdoc
1267
-	 */
1268
-	public function groupDeleted($gid) {
1269
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1270
-		$provider->groupDeleted($gid);
1271
-	}
1272
-
1273
-	/**
1274
-	 * @inheritdoc
1275
-	 */
1276
-	public function userDeletedFromGroup($uid, $gid) {
1277
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1278
-		$provider->userDeletedFromGroup($uid, $gid);
1279
-	}
1280
-
1281
-	/**
1282
-	 * Get access list to a path. This means
1283
-	 * all the users that can access a given path.
1284
-	 *
1285
-	 * Consider:
1286
-	 * -root
1287
-	 * |-folder1 (23)
1288
-	 *  |-folder2 (32)
1289
-	 *   |-fileA (42)
1290
-	 *
1291
-	 * fileA is shared with user1 and user1@server1
1292
-	 * folder2 is shared with group2 (user4 is a member of group2)
1293
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1294
-	 *
1295
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1296
-	 * [
1297
-	 *  users  => [
1298
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1299
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1300
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1301
-	 *  ],
1302
-	 *  remote => [
1303
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1304
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1305
-	 *  ],
1306
-	 *  public => bool
1307
-	 *  mail => bool
1308
-	 * ]
1309
-	 *
1310
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1311
-	 * [
1312
-	 *  users  => ['user1', 'user2', 'user4'],
1313
-	 *  remote => bool,
1314
-	 *  public => bool
1315
-	 *  mail => bool
1316
-	 * ]
1317
-	 *
1318
-	 * This is required for encryption/activity
1319
-	 *
1320
-	 * @param \OCP\Files\Node $path
1321
-	 * @param bool $recursive Should we check all parent folders as well
1322
-	 * @param bool $currentAccess Should the user have currently access to the file
1323
-	 * @return array
1324
-	 */
1325
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1326
-		$owner = $path->getOwner()->getUID();
1327
-
1328
-		if ($currentAccess) {
1329
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1330
-		} else {
1331
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1332
-		}
1333
-		if (!$this->userManager->userExists($owner)) {
1334
-			return $al;
1335
-		}
1336
-
1337
-		//Get node for the owner
1338
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1339
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1340
-			$path = $userFolder->getById($path->getId())[0];
1341
-		}
1342
-
1343
-		$providers = $this->factory->getAllProviders();
1344
-
1345
-		/** @var Node[] $nodes */
1346
-		$nodes = [];
1347
-
1348
-
1349
-		if ($currentAccess) {
1350
-			$ownerPath = $path->getPath();
1351
-			$ownerPath = explode('/', $ownerPath, 4);
1352
-			if (count($ownerPath) < 4) {
1353
-				$ownerPath = '';
1354
-			} else {
1355
-				$ownerPath = $ownerPath[3];
1356
-			}
1357
-			$al['users'][$owner] = [
1358
-				'node_id' => $path->getId(),
1359
-				'node_path' => '/' . $ownerPath,
1360
-			];
1361
-		} else {
1362
-			$al['users'][] = $owner;
1363
-		}
1364
-
1365
-		// Collect all the shares
1366
-		while ($path->getPath() !== $userFolder->getPath()) {
1367
-			$nodes[] = $path;
1368
-			if (!$recursive) {
1369
-				break;
1370
-			}
1371
-			$path = $path->getParent();
1372
-		}
1373
-
1374
-		foreach ($providers as $provider) {
1375
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1376
-
1377
-			foreach ($tmp as $k => $v) {
1378
-				if (isset($al[$k])) {
1379
-					if (is_array($al[$k])) {
1380
-						$al[$k] = array_merge($al[$k], $v);
1381
-					} else {
1382
-						$al[$k] = $al[$k] || $v;
1383
-					}
1384
-				} else {
1385
-					$al[$k] = $v;
1386
-				}
1387
-			}
1388
-		}
1389
-
1390
-		return $al;
1391
-	}
1392
-
1393
-	/**
1394
-	 * Create a new share
1395
-	 * @return \OCP\Share\IShare;
1396
-	 */
1397
-	public function newShare() {
1398
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1399
-	}
1400
-
1401
-	/**
1402
-	 * Is the share API enabled
1403
-	 *
1404
-	 * @return bool
1405
-	 */
1406
-	public function shareApiEnabled() {
1407
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1408
-	}
1409
-
1410
-	/**
1411
-	 * Is public link sharing enabled
1412
-	 *
1413
-	 * @return bool
1414
-	 */
1415
-	public function shareApiAllowLinks() {
1416
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1417
-	}
1418
-
1419
-	/**
1420
-	 * Is password on public link requires
1421
-	 *
1422
-	 * @return bool
1423
-	 */
1424
-	public function shareApiLinkEnforcePassword() {
1425
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1426
-	}
1427
-
1428
-	/**
1429
-	 * Is default expire date enabled
1430
-	 *
1431
-	 * @return bool
1432
-	 */
1433
-	public function shareApiLinkDefaultExpireDate() {
1434
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1435
-	}
1436
-
1437
-	/**
1438
-	 * Is default expire date enforced
1439
-	 *`
1440
-	 * @return bool
1441
-	 */
1442
-	public function shareApiLinkDefaultExpireDateEnforced() {
1443
-		return $this->shareApiLinkDefaultExpireDate() &&
1444
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1445
-	}
1446
-
1447
-	/**
1448
-	 * Number of default expire days
1449
-	 *shareApiLinkAllowPublicUpload
1450
-	 * @return int
1451
-	 */
1452
-	public function shareApiLinkDefaultExpireDays() {
1453
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1454
-	}
1455
-
1456
-	/**
1457
-	 * Allow public upload on link shares
1458
-	 *
1459
-	 * @return bool
1460
-	 */
1461
-	public function shareApiLinkAllowPublicUpload() {
1462
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1463
-	}
1464
-
1465
-	/**
1466
-	 * check if user can only share with group members
1467
-	 * @return bool
1468
-	 */
1469
-	public function shareWithGroupMembersOnly() {
1470
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1471
-	}
1472
-
1473
-	/**
1474
-	 * Check if users can share with groups
1475
-	 * @return bool
1476
-	 */
1477
-	public function allowGroupSharing() {
1478
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1479
-	}
1480
-
1481
-	/**
1482
-	 * Copied from \OC_Util::isSharingDisabledForUser
1483
-	 *
1484
-	 * TODO: Deprecate fuction from OC_Util
1485
-	 *
1486
-	 * @param string $userId
1487
-	 * @return bool
1488
-	 */
1489
-	public function sharingDisabledForUser($userId) {
1490
-		if ($userId === null) {
1491
-			return false;
1492
-		}
1493
-
1494
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1495
-			return $this->sharingDisabledForUsersCache[$userId];
1496
-		}
1497
-
1498
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1499
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1500
-			$excludedGroups = json_decode($groupsList);
1501
-			if (is_null($excludedGroups)) {
1502
-				$excludedGroups = explode(',', $groupsList);
1503
-				$newValue = json_encode($excludedGroups);
1504
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1505
-			}
1506
-			$user = $this->userManager->get($userId);
1507
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1508
-			if (!empty($usersGroups)) {
1509
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1510
-				// if the user is only in groups which are disabled for sharing then
1511
-				// sharing is also disabled for the user
1512
-				if (empty($remainingGroups)) {
1513
-					$this->sharingDisabledForUsersCache[$userId] = true;
1514
-					return true;
1515
-				}
1516
-			}
1517
-		}
1518
-
1519
-		$this->sharingDisabledForUsersCache[$userId] = false;
1520
-		return false;
1521
-	}
1522
-
1523
-	/**
1524
-	 * @inheritdoc
1525
-	 */
1526
-	public function outgoingServer2ServerSharesAllowed() {
1527
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1528
-	}
1529
-
1530
-	/**
1531
-	 * @inheritdoc
1532
-	 */
1533
-	public function shareProviderExists($shareType) {
1534
-		try {
1535
-			$this->factory->getProviderForType($shareType);
1536
-		} catch (ProviderException $e) {
1537
-			return false;
1538
-		}
1539
-
1540
-		return true;
1541
-	}
1199
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1200
+            !$this->shareApiLinkAllowPublicUpload()) {
1201
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1202
+        }
1203
+
1204
+        return $share;
1205
+    }
1206
+
1207
+    protected function checkExpireDate($share) {
1208
+        if ($share->getExpirationDate() !== null &&
1209
+            $share->getExpirationDate() <= new \DateTime()) {
1210
+            $this->deleteShare($share);
1211
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1212
+        }
1213
+
1214
+    }
1215
+
1216
+    /**
1217
+     * Verify the password of a public share
1218
+     *
1219
+     * @param \OCP\Share\IShare $share
1220
+     * @param string $password
1221
+     * @return bool
1222
+     */
1223
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1224
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1225
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1226
+        if (!$passwordProtected) {
1227
+            //TODO maybe exception?
1228
+            return false;
1229
+        }
1230
+
1231
+        if ($password === null || $share->getPassword() === null) {
1232
+            return false;
1233
+        }
1234
+
1235
+        $newHash = '';
1236
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1237
+            return false;
1238
+        }
1239
+
1240
+        if (!empty($newHash)) {
1241
+            $share->setPassword($newHash);
1242
+            $provider = $this->factory->getProviderForType($share->getShareType());
1243
+            $provider->update($share);
1244
+        }
1245
+
1246
+        return true;
1247
+    }
1248
+
1249
+    /**
1250
+     * @inheritdoc
1251
+     */
1252
+    public function userDeleted($uid) {
1253
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1254
+
1255
+        foreach ($types as $type) {
1256
+            try {
1257
+                $provider = $this->factory->getProviderForType($type);
1258
+            } catch (ProviderException $e) {
1259
+                continue;
1260
+            }
1261
+            $provider->userDeleted($uid, $type);
1262
+        }
1263
+    }
1264
+
1265
+    /**
1266
+     * @inheritdoc
1267
+     */
1268
+    public function groupDeleted($gid) {
1269
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1270
+        $provider->groupDeleted($gid);
1271
+    }
1272
+
1273
+    /**
1274
+     * @inheritdoc
1275
+     */
1276
+    public function userDeletedFromGroup($uid, $gid) {
1277
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1278
+        $provider->userDeletedFromGroup($uid, $gid);
1279
+    }
1280
+
1281
+    /**
1282
+     * Get access list to a path. This means
1283
+     * all the users that can access a given path.
1284
+     *
1285
+     * Consider:
1286
+     * -root
1287
+     * |-folder1 (23)
1288
+     *  |-folder2 (32)
1289
+     *   |-fileA (42)
1290
+     *
1291
+     * fileA is shared with user1 and user1@server1
1292
+     * folder2 is shared with group2 (user4 is a member of group2)
1293
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1294
+     *
1295
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1296
+     * [
1297
+     *  users  => [
1298
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1299
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1300
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1301
+     *  ],
1302
+     *  remote => [
1303
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1304
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1305
+     *  ],
1306
+     *  public => bool
1307
+     *  mail => bool
1308
+     * ]
1309
+     *
1310
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1311
+     * [
1312
+     *  users  => ['user1', 'user2', 'user4'],
1313
+     *  remote => bool,
1314
+     *  public => bool
1315
+     *  mail => bool
1316
+     * ]
1317
+     *
1318
+     * This is required for encryption/activity
1319
+     *
1320
+     * @param \OCP\Files\Node $path
1321
+     * @param bool $recursive Should we check all parent folders as well
1322
+     * @param bool $currentAccess Should the user have currently access to the file
1323
+     * @return array
1324
+     */
1325
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1326
+        $owner = $path->getOwner()->getUID();
1327
+
1328
+        if ($currentAccess) {
1329
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1330
+        } else {
1331
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1332
+        }
1333
+        if (!$this->userManager->userExists($owner)) {
1334
+            return $al;
1335
+        }
1336
+
1337
+        //Get node for the owner
1338
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1339
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1340
+            $path = $userFolder->getById($path->getId())[0];
1341
+        }
1342
+
1343
+        $providers = $this->factory->getAllProviders();
1344
+
1345
+        /** @var Node[] $nodes */
1346
+        $nodes = [];
1347
+
1348
+
1349
+        if ($currentAccess) {
1350
+            $ownerPath = $path->getPath();
1351
+            $ownerPath = explode('/', $ownerPath, 4);
1352
+            if (count($ownerPath) < 4) {
1353
+                $ownerPath = '';
1354
+            } else {
1355
+                $ownerPath = $ownerPath[3];
1356
+            }
1357
+            $al['users'][$owner] = [
1358
+                'node_id' => $path->getId(),
1359
+                'node_path' => '/' . $ownerPath,
1360
+            ];
1361
+        } else {
1362
+            $al['users'][] = $owner;
1363
+        }
1364
+
1365
+        // Collect all the shares
1366
+        while ($path->getPath() !== $userFolder->getPath()) {
1367
+            $nodes[] = $path;
1368
+            if (!$recursive) {
1369
+                break;
1370
+            }
1371
+            $path = $path->getParent();
1372
+        }
1373
+
1374
+        foreach ($providers as $provider) {
1375
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1376
+
1377
+            foreach ($tmp as $k => $v) {
1378
+                if (isset($al[$k])) {
1379
+                    if (is_array($al[$k])) {
1380
+                        $al[$k] = array_merge($al[$k], $v);
1381
+                    } else {
1382
+                        $al[$k] = $al[$k] || $v;
1383
+                    }
1384
+                } else {
1385
+                    $al[$k] = $v;
1386
+                }
1387
+            }
1388
+        }
1389
+
1390
+        return $al;
1391
+    }
1392
+
1393
+    /**
1394
+     * Create a new share
1395
+     * @return \OCP\Share\IShare;
1396
+     */
1397
+    public function newShare() {
1398
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1399
+    }
1400
+
1401
+    /**
1402
+     * Is the share API enabled
1403
+     *
1404
+     * @return bool
1405
+     */
1406
+    public function shareApiEnabled() {
1407
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1408
+    }
1409
+
1410
+    /**
1411
+     * Is public link sharing enabled
1412
+     *
1413
+     * @return bool
1414
+     */
1415
+    public function shareApiAllowLinks() {
1416
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1417
+    }
1418
+
1419
+    /**
1420
+     * Is password on public link requires
1421
+     *
1422
+     * @return bool
1423
+     */
1424
+    public function shareApiLinkEnforcePassword() {
1425
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1426
+    }
1427
+
1428
+    /**
1429
+     * Is default expire date enabled
1430
+     *
1431
+     * @return bool
1432
+     */
1433
+    public function shareApiLinkDefaultExpireDate() {
1434
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1435
+    }
1436
+
1437
+    /**
1438
+     * Is default expire date enforced
1439
+     *`
1440
+     * @return bool
1441
+     */
1442
+    public function shareApiLinkDefaultExpireDateEnforced() {
1443
+        return $this->shareApiLinkDefaultExpireDate() &&
1444
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1445
+    }
1446
+
1447
+    /**
1448
+     * Number of default expire days
1449
+     *shareApiLinkAllowPublicUpload
1450
+     * @return int
1451
+     */
1452
+    public function shareApiLinkDefaultExpireDays() {
1453
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1454
+    }
1455
+
1456
+    /**
1457
+     * Allow public upload on link shares
1458
+     *
1459
+     * @return bool
1460
+     */
1461
+    public function shareApiLinkAllowPublicUpload() {
1462
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1463
+    }
1464
+
1465
+    /**
1466
+     * check if user can only share with group members
1467
+     * @return bool
1468
+     */
1469
+    public function shareWithGroupMembersOnly() {
1470
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1471
+    }
1472
+
1473
+    /**
1474
+     * Check if users can share with groups
1475
+     * @return bool
1476
+     */
1477
+    public function allowGroupSharing() {
1478
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1479
+    }
1480
+
1481
+    /**
1482
+     * Copied from \OC_Util::isSharingDisabledForUser
1483
+     *
1484
+     * TODO: Deprecate fuction from OC_Util
1485
+     *
1486
+     * @param string $userId
1487
+     * @return bool
1488
+     */
1489
+    public function sharingDisabledForUser($userId) {
1490
+        if ($userId === null) {
1491
+            return false;
1492
+        }
1493
+
1494
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1495
+            return $this->sharingDisabledForUsersCache[$userId];
1496
+        }
1497
+
1498
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1499
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1500
+            $excludedGroups = json_decode($groupsList);
1501
+            if (is_null($excludedGroups)) {
1502
+                $excludedGroups = explode(',', $groupsList);
1503
+                $newValue = json_encode($excludedGroups);
1504
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1505
+            }
1506
+            $user = $this->userManager->get($userId);
1507
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1508
+            if (!empty($usersGroups)) {
1509
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1510
+                // if the user is only in groups which are disabled for sharing then
1511
+                // sharing is also disabled for the user
1512
+                if (empty($remainingGroups)) {
1513
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1514
+                    return true;
1515
+                }
1516
+            }
1517
+        }
1518
+
1519
+        $this->sharingDisabledForUsersCache[$userId] = false;
1520
+        return false;
1521
+    }
1522
+
1523
+    /**
1524
+     * @inheritdoc
1525
+     */
1526
+    public function outgoingServer2ServerSharesAllowed() {
1527
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1528
+    }
1529
+
1530
+    /**
1531
+     * @inheritdoc
1532
+     */
1533
+    public function shareProviderExists($shareType) {
1534
+        try {
1535
+            $this->factory->getProviderForType($shareType);
1536
+        } catch (ProviderException $e) {
1537
+            return false;
1538
+        }
1539
+
1540
+        return true;
1541
+    }
1542 1542
 
1543 1543
 }
Please login to merge, or discard this patch.