Completed
Pull Request — master (#6668)
by Robin
60:33 queued 44:54
created
lib/private/Server.php 2 patches
Indentation   +1785 added lines, -1785 removed lines patch added patch discarded remove patch
@@ -145,1794 +145,1794 @@
 block discarded – undo
145 145
  * TODO: hookup all manager classes
146 146
  */
147 147
 class Server extends ServerContainer implements IServerContainer {
148
-	/** @var string */
149
-	private $webRoot;
150
-
151
-	/**
152
-	 * @param string $webRoot
153
-	 * @param \OC\Config $config
154
-	 */
155
-	public function __construct($webRoot, \OC\Config $config) {
156
-		parent::__construct();
157
-		$this->webRoot = $webRoot;
158
-
159
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
160
-			return $c;
161
-		});
162
-
163
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
164
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
165
-
166
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
167
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
168
-
169
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
170
-
171
-
172
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
173
-			return new PreviewManager(
174
-				$c->getConfig(),
175
-				$c->getRootFolder(),
176
-				$c->getAppDataDir('preview'),
177
-				$c->getEventDispatcher(),
178
-				$c->getSession()->get('user_id')
179
-			);
180
-		});
181
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
182
-
183
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
184
-			return new \OC\Preview\Watcher(
185
-				$c->getAppDataDir('preview')
186
-			);
187
-		});
188
-
189
-		$this->registerService('EncryptionManager', function (Server $c) {
190
-			$view = new View();
191
-			$util = new Encryption\Util(
192
-				$view,
193
-				$c->getUserManager(),
194
-				$c->getGroupManager(),
195
-				$c->getConfig()
196
-			);
197
-			return new Encryption\Manager(
198
-				$c->getConfig(),
199
-				$c->getLogger(),
200
-				$c->getL10N('core'),
201
-				new View(),
202
-				$util,
203
-				new ArrayCache()
204
-			);
205
-		});
206
-
207
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
208
-			$util = new Encryption\Util(
209
-				new View(),
210
-				$c->getUserManager(),
211
-				$c->getGroupManager(),
212
-				$c->getConfig()
213
-			);
214
-			return new Encryption\File(
215
-				$util,
216
-				$c->getRootFolder(),
217
-				$c->getShareManager()
218
-			);
219
-		});
220
-
221
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
222
-			$view = new View();
223
-			$util = new Encryption\Util(
224
-				$view,
225
-				$c->getUserManager(),
226
-				$c->getGroupManager(),
227
-				$c->getConfig()
228
-			);
229
-
230
-			return new Encryption\Keys\Storage($view, $util);
231
-		});
232
-		$this->registerService('TagMapper', function (Server $c) {
233
-			return new TagMapper($c->getDatabaseConnection());
234
-		});
235
-
236
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
237
-			$tagMapper = $c->query('TagMapper');
238
-			return new TagManager($tagMapper, $c->getUserSession());
239
-		});
240
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
241
-
242
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
243
-			$config = $c->getConfig();
244
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
245
-			/** @var \OC\SystemTag\ManagerFactory $factory */
246
-			$factory = new $factoryClass($this);
247
-			return $factory;
248
-		});
249
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
250
-			return $c->query('SystemTagManagerFactory')->getManager();
251
-		});
252
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
253
-
254
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
255
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
256
-		});
257
-		$this->registerService('RootFolder', function (Server $c) {
258
-			$manager = \OC\Files\Filesystem::getMountManager(null);
259
-			$view = new View();
260
-			$root = new Root(
261
-				$manager,
262
-				$view,
263
-				null,
264
-				$c->getUserMountCache(),
265
-				$this->getLogger(),
266
-				$this->getUserManager()
267
-			);
268
-			$connector = new HookConnector($root, $view);
269
-			$connector->viewToNode();
270
-
271
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
272
-			$previewConnector->connectWatcher();
273
-
274
-			return $root;
275
-		});
276
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
277
-
278
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
279
-			return new LazyRoot(function () use ($c) {
280
-				return $c->query('RootFolder');
281
-			});
282
-		});
283
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
284
-
285
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
286
-			$config = $c->getConfig();
287
-			return new \OC\User\Manager($config);
288
-		});
289
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
290
-
291
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
292
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
294
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295
-			});
296
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
297
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298
-			});
299
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
300
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301
-			});
302
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
303
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304
-			});
305
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
306
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307
-			});
308
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
312
-			});
313
-			return $groupManager;
314
-		});
315
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316
-
317
-		$this->registerService(Store::class, function (Server $c) {
318
-			$session = $c->getSession();
319
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
321
-			} else {
322
-				$tokenProvider = null;
323
-			}
324
-			$logger = $c->getLogger();
325
-			return new Store($session, $logger, $tokenProvider);
326
-		});
327
-		$this->registerAlias(IStore::class, Store::class);
328
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
329
-			$dbConnection = $c->getDatabaseConnection();
330
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
331
-		});
332
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
333
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334
-			$crypto = $c->getCrypto();
335
-			$config = $c->getConfig();
336
-			$logger = $c->getLogger();
337
-			$timeFactory = new TimeFactory();
338
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
339
-		});
340
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341
-
342
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
343
-			$manager = $c->getUserManager();
344
-			$session = new \OC\Session\Memory('');
345
-			$timeFactory = new TimeFactory();
346
-			// Token providers might require a working database. This code
347
-			// might however be called when ownCloud is not yet setup.
348
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
349
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
350
-			} else {
351
-				$defaultTokenProvider = null;
352
-			}
353
-
354
-			$dispatcher = $c->getEventDispatcher();
355
-
356
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
357
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
358
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
359
-			});
360
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
361
-				/** @var $user \OC\User\User */
362
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
363
-			});
364
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
365
-				/** @var $user \OC\User\User */
366
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
367
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
368
-			});
369
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
370
-				/** @var $user \OC\User\User */
371
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
372
-			});
373
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
374
-				/** @var $user \OC\User\User */
375
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
376
-			});
377
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
378
-				/** @var $user \OC\User\User */
379
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
380
-			});
381
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
382
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
383
-			});
384
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
385
-				/** @var $user \OC\User\User */
386
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
387
-			});
388
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
389
-				/** @var $user \OC\User\User */
390
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
391
-			});
392
-			$userSession->listen('\OC\User', 'logout', function () {
393
-				\OC_Hook::emit('OC_User', 'logout', array());
394
-			});
395
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
396
-				/** @var $user \OC\User\User */
397
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
398
-			});
399
-			return $userSession;
400
-		});
401
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
402
-
403
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
404
-			return new \OC\Authentication\TwoFactorAuth\Manager(
405
-				$c->getAppManager(),
406
-				$c->getSession(),
407
-				$c->getConfig(),
408
-				$c->getActivityManager(),
409
-				$c->getLogger(),
410
-				$c->query(\OC\Authentication\Token\IProvider::class),
411
-				$c->query(ITimeFactory::class)
412
-			);
413
-		});
414
-
415
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
416
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
417
-
418
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
419
-			return new \OC\AllConfig(
420
-				$c->getSystemConfig()
421
-			);
422
-		});
423
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
424
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
425
-
426
-		$this->registerService('SystemConfig', function ($c) use ($config) {
427
-			return new \OC\SystemConfig($config);
428
-		});
429
-
430
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
431
-			return new \OC\AppConfig($c->getDatabaseConnection());
432
-		});
433
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
434
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
435
-
436
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
437
-			return new \OC\L10N\Factory(
438
-				$c->getConfig(),
439
-				$c->getRequest(),
440
-				$c->getUserSession(),
441
-				\OC::$SERVERROOT
442
-			);
443
-		});
444
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
445
-
446
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
447
-			$config = $c->getConfig();
448
-			$cacheFactory = $c->getMemCacheFactory();
449
-			$request = $c->getRequest();
450
-			return new \OC\URLGenerator(
451
-				$config,
452
-				$cacheFactory,
453
-				$request
454
-			);
455
-		});
456
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
457
-
458
-		$this->registerService('AppHelper', function ($c) {
459
-			return new \OC\AppHelper();
460
-		});
461
-		$this->registerAlias('AppFetcher', AppFetcher::class);
462
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
463
-
464
-		$this->registerService(\OCP\ICache::class, function ($c) {
465
-			return new Cache\File();
466
-		});
467
-		$this->registerAlias('UserCache', \OCP\ICache::class);
468
-
469
-		$this->registerService(Factory::class, function (Server $c) {
470
-
471
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
472
-				'\\OC\\Memcache\\ArrayCache',
473
-				'\\OC\\Memcache\\ArrayCache',
474
-				'\\OC\\Memcache\\ArrayCache'
475
-			);
476
-			$config = $c->getConfig();
477
-			$request = $c->getRequest();
478
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
479
-
480
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
481
-				$v = \OC_App::getAppVersions();
482
-				$v['core'] = implode(',', \OC_Util::getVersion());
483
-				$version = implode(',', $v);
484
-				$instanceId = \OC_Util::getInstanceId();
485
-				$path = \OC::$SERVERROOT;
486
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
487
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
488
-					$config->getSystemValue('memcache.local', null),
489
-					$config->getSystemValue('memcache.distributed', null),
490
-					$config->getSystemValue('memcache.locking', null)
491
-				);
492
-			}
493
-			return $arrayCacheFactory;
494
-
495
-		});
496
-		$this->registerAlias('MemCacheFactory', Factory::class);
497
-		$this->registerAlias(ICacheFactory::class, Factory::class);
498
-
499
-		$this->registerService('RedisFactory', function (Server $c) {
500
-			$systemConfig = $c->getSystemConfig();
501
-			return new RedisFactory($systemConfig);
502
-		});
503
-
504
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
505
-			return new \OC\Activity\Manager(
506
-				$c->getRequest(),
507
-				$c->getUserSession(),
508
-				$c->getConfig(),
509
-				$c->query(IValidator::class)
510
-			);
511
-		});
512
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
513
-
514
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
515
-			return new \OC\Activity\EventMerger(
516
-				$c->getL10N('lib')
517
-			);
518
-		});
519
-		$this->registerAlias(IValidator::class, Validator::class);
520
-
521
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
522
-			return new AvatarManager(
523
-				$c->getUserManager(),
524
-				$c->getAppDataDir('avatar'),
525
-				$c->getL10N('lib'),
526
-				$c->getLogger(),
527
-				$c->getConfig()
528
-			);
529
-		});
530
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
531
-
532
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
533
-
534
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
535
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
536
-			$logger = Log::getLogClass($logType);
537
-			call_user_func(array($logger, 'init'));
538
-			$config = $this->getSystemConfig();
539
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
540
-
541
-			return new Log($logger, $config, null, $registry);
542
-		});
543
-		$this->registerAlias('Logger', \OCP\ILogger::class);
544
-
545
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
546
-			$config = $c->getConfig();
547
-			return new \OC\BackgroundJob\JobList(
548
-				$c->getDatabaseConnection(),
549
-				$config,
550
-				new TimeFactory()
551
-			);
552
-		});
553
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
554
-
555
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
556
-			$cacheFactory = $c->getMemCacheFactory();
557
-			$logger = $c->getLogger();
558
-			if ($cacheFactory->isAvailableLowLatency()) {
559
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
560
-			} else {
561
-				$router = new \OC\Route\Router($logger);
562
-			}
563
-			return $router;
564
-		});
565
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
566
-
567
-		$this->registerService(\OCP\ISearch::class, function ($c) {
568
-			return new Search();
569
-		});
570
-		$this->registerAlias('Search', \OCP\ISearch::class);
571
-
572
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
573
-			return new \OC\Security\RateLimiting\Limiter(
574
-				$this->getUserSession(),
575
-				$this->getRequest(),
576
-				new \OC\AppFramework\Utility\TimeFactory(),
577
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
578
-			);
579
-		});
580
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
581
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
582
-				$this->getMemCacheFactory(),
583
-				new \OC\AppFramework\Utility\TimeFactory()
584
-			);
585
-		});
586
-
587
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
588
-			return new SecureRandom();
589
-		});
590
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
591
-
592
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
593
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
594
-		});
595
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
596
-
597
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
598
-			return new Hasher($c->getConfig());
599
-		});
600
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
601
-
602
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
603
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
604
-		});
605
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
606
-
607
-		$this->registerService(IDBConnection::class, function (Server $c) {
608
-			$systemConfig = $c->getSystemConfig();
609
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
610
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
611
-			if (!$factory->isValidType($type)) {
612
-				throw new \OC\DatabaseException('Invalid database type');
613
-			}
614
-			$connectionParams = $factory->createConnectionParams();
615
-			$connection = $factory->getConnection($type, $connectionParams);
616
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
617
-			return $connection;
618
-		});
619
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
620
-
621
-		$this->registerService('HTTPHelper', function (Server $c) {
622
-			$config = $c->getConfig();
623
-			return new HTTPHelper(
624
-				$config,
625
-				$c->getHTTPClientService()
626
-			);
627
-		});
628
-
629
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
630
-			$user = \OC_User::getUser();
631
-			$uid = $user ? $user : null;
632
-			return new ClientService(
633
-				$c->getConfig(),
634
-				new \OC\Security\CertificateManager(
635
-					$uid,
636
-					new View(),
637
-					$c->getConfig(),
638
-					$c->getLogger(),
639
-					$c->getSecureRandom()
640
-				)
641
-			);
642
-		});
643
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
644
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
645
-			$eventLogger = new EventLogger();
646
-			if ($c->getSystemConfig()->getValue('debug', false)) {
647
-				// In debug mode, module is being activated by default
648
-				$eventLogger->activate();
649
-			}
650
-			return $eventLogger;
651
-		});
652
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
653
-
654
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
655
-			$queryLogger = new QueryLogger();
656
-			if ($c->getSystemConfig()->getValue('debug', false)) {
657
-				// In debug mode, module is being activated by default
658
-				$queryLogger->activate();
659
-			}
660
-			return $queryLogger;
661
-		});
662
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
663
-
664
-		$this->registerService(TempManager::class, function (Server $c) {
665
-			return new TempManager(
666
-				$c->getLogger(),
667
-				$c->getConfig()
668
-			);
669
-		});
670
-		$this->registerAlias('TempManager', TempManager::class);
671
-		$this->registerAlias(ITempManager::class, TempManager::class);
672
-
673
-		$this->registerService(AppManager::class, function (Server $c) {
674
-			return new \OC\App\AppManager(
675
-				$c->getUserSession(),
676
-				$c->getAppConfig(),
677
-				$c->getGroupManager(),
678
-				$c->getMemCacheFactory(),
679
-				$c->getEventDispatcher()
680
-			);
681
-		});
682
-		$this->registerAlias('AppManager', AppManager::class);
683
-		$this->registerAlias(IAppManager::class, AppManager::class);
684
-
685
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
686
-			return new DateTimeZone(
687
-				$c->getConfig(),
688
-				$c->getSession()
689
-			);
690
-		});
691
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
692
-
693
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
694
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
695
-
696
-			return new DateTimeFormatter(
697
-				$c->getDateTimeZone()->getTimeZone(),
698
-				$c->getL10N('lib', $language)
699
-			);
700
-		});
701
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
702
-
703
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
704
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
705
-			$listener = new UserMountCacheListener($mountCache);
706
-			$listener->listen($c->getUserManager());
707
-			return $mountCache;
708
-		});
709
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
710
-
711
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
712
-			$loader = \OC\Files\Filesystem::getLoader();
713
-			$mountCache = $c->query('UserMountCache');
714
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
715
-
716
-			// builtin providers
717
-
718
-			$config = $c->getConfig();
719
-			$manager->registerProvider(new CacheMountProvider($config));
720
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
721
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
722
-
723
-			return $manager;
724
-		});
725
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
726
-
727
-		$this->registerService('IniWrapper', function ($c) {
728
-			return new IniGetWrapper();
729
-		});
730
-		$this->registerService('AsyncCommandBus', function (Server $c) {
731
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
732
-			if ($busClass) {
733
-				list($app, $class) = explode('::', $busClass, 2);
734
-				if ($c->getAppManager()->isInstalled($app)) {
735
-					\OC_App::loadApp($app);
736
-					return $c->query($class);
737
-				} else {
738
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
739
-				}
740
-			} else {
741
-				$jobList = $c->getJobList();
742
-				return new CronBus($jobList);
743
-			}
744
-		});
745
-		$this->registerService('TrustedDomainHelper', function ($c) {
746
-			return new TrustedDomainHelper($this->getConfig());
747
-		});
748
-		$this->registerService('Throttler', function (Server $c) {
749
-			return new Throttler(
750
-				$c->getDatabaseConnection(),
751
-				new TimeFactory(),
752
-				$c->getLogger(),
753
-				$c->getConfig()
754
-			);
755
-		});
756
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
757
-			// IConfig and IAppManager requires a working database. This code
758
-			// might however be called when ownCloud is not yet setup.
759
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
760
-				$config = $c->getConfig();
761
-				$appManager = $c->getAppManager();
762
-			} else {
763
-				$config = null;
764
-				$appManager = null;
765
-			}
766
-
767
-			return new Checker(
768
-				new EnvironmentHelper(),
769
-				new FileAccessHelper(),
770
-				new AppLocator(),
771
-				$config,
772
-				$c->getMemCacheFactory(),
773
-				$appManager,
774
-				$c->getTempManager()
775
-			);
776
-		});
777
-		$this->registerService(\OCP\IRequest::class, function ($c) {
778
-			if (isset($this['urlParams'])) {
779
-				$urlParams = $this['urlParams'];
780
-			} else {
781
-				$urlParams = [];
782
-			}
783
-
784
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
785
-				&& in_array('fakeinput', stream_get_wrappers())
786
-			) {
787
-				$stream = 'fakeinput://data';
788
-			} else {
789
-				$stream = 'php://input';
790
-			}
791
-
792
-			return new Request(
793
-				[
794
-					'get' => $_GET,
795
-					'post' => $_POST,
796
-					'files' => $_FILES,
797
-					'server' => $_SERVER,
798
-					'env' => $_ENV,
799
-					'cookies' => $_COOKIE,
800
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
801
-						? $_SERVER['REQUEST_METHOD']
802
-						: null,
803
-					'urlParams' => $urlParams,
804
-				],
805
-				$this->getSecureRandom(),
806
-				$this->getConfig(),
807
-				$this->getCsrfTokenManager(),
808
-				$stream
809
-			);
810
-		});
811
-		$this->registerAlias('Request', \OCP\IRequest::class);
812
-
813
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
814
-			return new Mailer(
815
-				$c->getConfig(),
816
-				$c->getLogger(),
817
-				$c->query(Defaults::class),
818
-				$c->getURLGenerator(),
819
-				$c->getL10N('lib')
820
-			);
821
-		});
822
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
823
-
824
-		$this->registerService('LDAPProvider', function (Server $c) {
825
-			$config = $c->getConfig();
826
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
827
-			if (is_null($factoryClass)) {
828
-				throw new \Exception('ldapProviderFactory not set');
829
-			}
830
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
831
-			$factory = new $factoryClass($this);
832
-			return $factory->getLDAPProvider();
833
-		});
834
-		$this->registerService(ILockingProvider::class, function (Server $c) {
835
-			$ini = $c->getIniWrapper();
836
-			$config = $c->getConfig();
837
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
838
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
839
-				/** @var \OC\Memcache\Factory $memcacheFactory */
840
-				$memcacheFactory = $c->getMemCacheFactory();
841
-				$memcache = $memcacheFactory->createLocking('lock');
842
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
843
-					return new MemcacheLockingProvider($memcache, $ttl);
844
-				}
845
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
846
-			}
847
-			return new NoopLockingProvider();
848
-		});
849
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
850
-
851
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
852
-			return new \OC\Files\Mount\Manager();
853
-		});
854
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
855
-
856
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
857
-			return new \OC\Files\Type\Detection(
858
-				$c->getURLGenerator(),
859
-				\OC::$configDir,
860
-				\OC::$SERVERROOT . '/resources/config/'
861
-			);
862
-		});
863
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
864
-
865
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
866
-			return new \OC\Files\Type\Loader(
867
-				$c->getDatabaseConnection()
868
-			);
869
-		});
870
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
871
-		$this->registerService(BundleFetcher::class, function () {
872
-			return new BundleFetcher($this->getL10N('lib'));
873
-		});
874
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
875
-			return new Manager(
876
-				$c->query(IValidator::class)
877
-			);
878
-		});
879
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
880
-
881
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
882
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
883
-			$manager->registerCapability(function () use ($c) {
884
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
885
-			});
886
-			$manager->registerCapability(function () use ($c) {
887
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
888
-			});
889
-			return $manager;
890
-		});
891
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
892
-
893
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
894
-			$config = $c->getConfig();
895
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
896
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
897
-			$factory = new $factoryClass($this);
898
-			return $factory->getManager();
899
-		});
900
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
901
-
902
-		$this->registerService('ThemingDefaults', function (Server $c) {
903
-			/*
148
+    /** @var string */
149
+    private $webRoot;
150
+
151
+    /**
152
+     * @param string $webRoot
153
+     * @param \OC\Config $config
154
+     */
155
+    public function __construct($webRoot, \OC\Config $config) {
156
+        parent::__construct();
157
+        $this->webRoot = $webRoot;
158
+
159
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
160
+            return $c;
161
+        });
162
+
163
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
164
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
165
+
166
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
167
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
168
+
169
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
170
+
171
+
172
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
173
+            return new PreviewManager(
174
+                $c->getConfig(),
175
+                $c->getRootFolder(),
176
+                $c->getAppDataDir('preview'),
177
+                $c->getEventDispatcher(),
178
+                $c->getSession()->get('user_id')
179
+            );
180
+        });
181
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
182
+
183
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
184
+            return new \OC\Preview\Watcher(
185
+                $c->getAppDataDir('preview')
186
+            );
187
+        });
188
+
189
+        $this->registerService('EncryptionManager', function (Server $c) {
190
+            $view = new View();
191
+            $util = new Encryption\Util(
192
+                $view,
193
+                $c->getUserManager(),
194
+                $c->getGroupManager(),
195
+                $c->getConfig()
196
+            );
197
+            return new Encryption\Manager(
198
+                $c->getConfig(),
199
+                $c->getLogger(),
200
+                $c->getL10N('core'),
201
+                new View(),
202
+                $util,
203
+                new ArrayCache()
204
+            );
205
+        });
206
+
207
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
208
+            $util = new Encryption\Util(
209
+                new View(),
210
+                $c->getUserManager(),
211
+                $c->getGroupManager(),
212
+                $c->getConfig()
213
+            );
214
+            return new Encryption\File(
215
+                $util,
216
+                $c->getRootFolder(),
217
+                $c->getShareManager()
218
+            );
219
+        });
220
+
221
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
222
+            $view = new View();
223
+            $util = new Encryption\Util(
224
+                $view,
225
+                $c->getUserManager(),
226
+                $c->getGroupManager(),
227
+                $c->getConfig()
228
+            );
229
+
230
+            return new Encryption\Keys\Storage($view, $util);
231
+        });
232
+        $this->registerService('TagMapper', function (Server $c) {
233
+            return new TagMapper($c->getDatabaseConnection());
234
+        });
235
+
236
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
237
+            $tagMapper = $c->query('TagMapper');
238
+            return new TagManager($tagMapper, $c->getUserSession());
239
+        });
240
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
241
+
242
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
243
+            $config = $c->getConfig();
244
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
245
+            /** @var \OC\SystemTag\ManagerFactory $factory */
246
+            $factory = new $factoryClass($this);
247
+            return $factory;
248
+        });
249
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
250
+            return $c->query('SystemTagManagerFactory')->getManager();
251
+        });
252
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
253
+
254
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
255
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
256
+        });
257
+        $this->registerService('RootFolder', function (Server $c) {
258
+            $manager = \OC\Files\Filesystem::getMountManager(null);
259
+            $view = new View();
260
+            $root = new Root(
261
+                $manager,
262
+                $view,
263
+                null,
264
+                $c->getUserMountCache(),
265
+                $this->getLogger(),
266
+                $this->getUserManager()
267
+            );
268
+            $connector = new HookConnector($root, $view);
269
+            $connector->viewToNode();
270
+
271
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
272
+            $previewConnector->connectWatcher();
273
+
274
+            return $root;
275
+        });
276
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
277
+
278
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
279
+            return new LazyRoot(function () use ($c) {
280
+                return $c->query('RootFolder');
281
+            });
282
+        });
283
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
284
+
285
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
286
+            $config = $c->getConfig();
287
+            return new \OC\User\Manager($config);
288
+        });
289
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
290
+
291
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
292
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
294
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295
+            });
296
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
297
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298
+            });
299
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
300
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301
+            });
302
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
303
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304
+            });
305
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
306
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307
+            });
308
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
312
+            });
313
+            return $groupManager;
314
+        });
315
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316
+
317
+        $this->registerService(Store::class, function (Server $c) {
318
+            $session = $c->getSession();
319
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
321
+            } else {
322
+                $tokenProvider = null;
323
+            }
324
+            $logger = $c->getLogger();
325
+            return new Store($session, $logger, $tokenProvider);
326
+        });
327
+        $this->registerAlias(IStore::class, Store::class);
328
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
329
+            $dbConnection = $c->getDatabaseConnection();
330
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
331
+        });
332
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
333
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334
+            $crypto = $c->getCrypto();
335
+            $config = $c->getConfig();
336
+            $logger = $c->getLogger();
337
+            $timeFactory = new TimeFactory();
338
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
339
+        });
340
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341
+
342
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
343
+            $manager = $c->getUserManager();
344
+            $session = new \OC\Session\Memory('');
345
+            $timeFactory = new TimeFactory();
346
+            // Token providers might require a working database. This code
347
+            // might however be called when ownCloud is not yet setup.
348
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
349
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
350
+            } else {
351
+                $defaultTokenProvider = null;
352
+            }
353
+
354
+            $dispatcher = $c->getEventDispatcher();
355
+
356
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
357
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
358
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
359
+            });
360
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
361
+                /** @var $user \OC\User\User */
362
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
363
+            });
364
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
365
+                /** @var $user \OC\User\User */
366
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
367
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
368
+            });
369
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
370
+                /** @var $user \OC\User\User */
371
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
372
+            });
373
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
374
+                /** @var $user \OC\User\User */
375
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
376
+            });
377
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
378
+                /** @var $user \OC\User\User */
379
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
380
+            });
381
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
382
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
383
+            });
384
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
385
+                /** @var $user \OC\User\User */
386
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
387
+            });
388
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
389
+                /** @var $user \OC\User\User */
390
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
391
+            });
392
+            $userSession->listen('\OC\User', 'logout', function () {
393
+                \OC_Hook::emit('OC_User', 'logout', array());
394
+            });
395
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
396
+                /** @var $user \OC\User\User */
397
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
398
+            });
399
+            return $userSession;
400
+        });
401
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
402
+
403
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
404
+            return new \OC\Authentication\TwoFactorAuth\Manager(
405
+                $c->getAppManager(),
406
+                $c->getSession(),
407
+                $c->getConfig(),
408
+                $c->getActivityManager(),
409
+                $c->getLogger(),
410
+                $c->query(\OC\Authentication\Token\IProvider::class),
411
+                $c->query(ITimeFactory::class)
412
+            );
413
+        });
414
+
415
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
416
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
417
+
418
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
419
+            return new \OC\AllConfig(
420
+                $c->getSystemConfig()
421
+            );
422
+        });
423
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
424
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
425
+
426
+        $this->registerService('SystemConfig', function ($c) use ($config) {
427
+            return new \OC\SystemConfig($config);
428
+        });
429
+
430
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
431
+            return new \OC\AppConfig($c->getDatabaseConnection());
432
+        });
433
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
434
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
435
+
436
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
437
+            return new \OC\L10N\Factory(
438
+                $c->getConfig(),
439
+                $c->getRequest(),
440
+                $c->getUserSession(),
441
+                \OC::$SERVERROOT
442
+            );
443
+        });
444
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
445
+
446
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
447
+            $config = $c->getConfig();
448
+            $cacheFactory = $c->getMemCacheFactory();
449
+            $request = $c->getRequest();
450
+            return new \OC\URLGenerator(
451
+                $config,
452
+                $cacheFactory,
453
+                $request
454
+            );
455
+        });
456
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
457
+
458
+        $this->registerService('AppHelper', function ($c) {
459
+            return new \OC\AppHelper();
460
+        });
461
+        $this->registerAlias('AppFetcher', AppFetcher::class);
462
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
463
+
464
+        $this->registerService(\OCP\ICache::class, function ($c) {
465
+            return new Cache\File();
466
+        });
467
+        $this->registerAlias('UserCache', \OCP\ICache::class);
468
+
469
+        $this->registerService(Factory::class, function (Server $c) {
470
+
471
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
472
+                '\\OC\\Memcache\\ArrayCache',
473
+                '\\OC\\Memcache\\ArrayCache',
474
+                '\\OC\\Memcache\\ArrayCache'
475
+            );
476
+            $config = $c->getConfig();
477
+            $request = $c->getRequest();
478
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
479
+
480
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
481
+                $v = \OC_App::getAppVersions();
482
+                $v['core'] = implode(',', \OC_Util::getVersion());
483
+                $version = implode(',', $v);
484
+                $instanceId = \OC_Util::getInstanceId();
485
+                $path = \OC::$SERVERROOT;
486
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
487
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
488
+                    $config->getSystemValue('memcache.local', null),
489
+                    $config->getSystemValue('memcache.distributed', null),
490
+                    $config->getSystemValue('memcache.locking', null)
491
+                );
492
+            }
493
+            return $arrayCacheFactory;
494
+
495
+        });
496
+        $this->registerAlias('MemCacheFactory', Factory::class);
497
+        $this->registerAlias(ICacheFactory::class, Factory::class);
498
+
499
+        $this->registerService('RedisFactory', function (Server $c) {
500
+            $systemConfig = $c->getSystemConfig();
501
+            return new RedisFactory($systemConfig);
502
+        });
503
+
504
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
505
+            return new \OC\Activity\Manager(
506
+                $c->getRequest(),
507
+                $c->getUserSession(),
508
+                $c->getConfig(),
509
+                $c->query(IValidator::class)
510
+            );
511
+        });
512
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
513
+
514
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
515
+            return new \OC\Activity\EventMerger(
516
+                $c->getL10N('lib')
517
+            );
518
+        });
519
+        $this->registerAlias(IValidator::class, Validator::class);
520
+
521
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
522
+            return new AvatarManager(
523
+                $c->getUserManager(),
524
+                $c->getAppDataDir('avatar'),
525
+                $c->getL10N('lib'),
526
+                $c->getLogger(),
527
+                $c->getConfig()
528
+            );
529
+        });
530
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
531
+
532
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
533
+
534
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
535
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
536
+            $logger = Log::getLogClass($logType);
537
+            call_user_func(array($logger, 'init'));
538
+            $config = $this->getSystemConfig();
539
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
540
+
541
+            return new Log($logger, $config, null, $registry);
542
+        });
543
+        $this->registerAlias('Logger', \OCP\ILogger::class);
544
+
545
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
546
+            $config = $c->getConfig();
547
+            return new \OC\BackgroundJob\JobList(
548
+                $c->getDatabaseConnection(),
549
+                $config,
550
+                new TimeFactory()
551
+            );
552
+        });
553
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
554
+
555
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
556
+            $cacheFactory = $c->getMemCacheFactory();
557
+            $logger = $c->getLogger();
558
+            if ($cacheFactory->isAvailableLowLatency()) {
559
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
560
+            } else {
561
+                $router = new \OC\Route\Router($logger);
562
+            }
563
+            return $router;
564
+        });
565
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
566
+
567
+        $this->registerService(\OCP\ISearch::class, function ($c) {
568
+            return new Search();
569
+        });
570
+        $this->registerAlias('Search', \OCP\ISearch::class);
571
+
572
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
573
+            return new \OC\Security\RateLimiting\Limiter(
574
+                $this->getUserSession(),
575
+                $this->getRequest(),
576
+                new \OC\AppFramework\Utility\TimeFactory(),
577
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
578
+            );
579
+        });
580
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
581
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
582
+                $this->getMemCacheFactory(),
583
+                new \OC\AppFramework\Utility\TimeFactory()
584
+            );
585
+        });
586
+
587
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
588
+            return new SecureRandom();
589
+        });
590
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
591
+
592
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
593
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
594
+        });
595
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
596
+
597
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
598
+            return new Hasher($c->getConfig());
599
+        });
600
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
601
+
602
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
603
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
604
+        });
605
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
606
+
607
+        $this->registerService(IDBConnection::class, function (Server $c) {
608
+            $systemConfig = $c->getSystemConfig();
609
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
610
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
611
+            if (!$factory->isValidType($type)) {
612
+                throw new \OC\DatabaseException('Invalid database type');
613
+            }
614
+            $connectionParams = $factory->createConnectionParams();
615
+            $connection = $factory->getConnection($type, $connectionParams);
616
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
617
+            return $connection;
618
+        });
619
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
620
+
621
+        $this->registerService('HTTPHelper', function (Server $c) {
622
+            $config = $c->getConfig();
623
+            return new HTTPHelper(
624
+                $config,
625
+                $c->getHTTPClientService()
626
+            );
627
+        });
628
+
629
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
630
+            $user = \OC_User::getUser();
631
+            $uid = $user ? $user : null;
632
+            return new ClientService(
633
+                $c->getConfig(),
634
+                new \OC\Security\CertificateManager(
635
+                    $uid,
636
+                    new View(),
637
+                    $c->getConfig(),
638
+                    $c->getLogger(),
639
+                    $c->getSecureRandom()
640
+                )
641
+            );
642
+        });
643
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
644
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
645
+            $eventLogger = new EventLogger();
646
+            if ($c->getSystemConfig()->getValue('debug', false)) {
647
+                // In debug mode, module is being activated by default
648
+                $eventLogger->activate();
649
+            }
650
+            return $eventLogger;
651
+        });
652
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
653
+
654
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
655
+            $queryLogger = new QueryLogger();
656
+            if ($c->getSystemConfig()->getValue('debug', false)) {
657
+                // In debug mode, module is being activated by default
658
+                $queryLogger->activate();
659
+            }
660
+            return $queryLogger;
661
+        });
662
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
663
+
664
+        $this->registerService(TempManager::class, function (Server $c) {
665
+            return new TempManager(
666
+                $c->getLogger(),
667
+                $c->getConfig()
668
+            );
669
+        });
670
+        $this->registerAlias('TempManager', TempManager::class);
671
+        $this->registerAlias(ITempManager::class, TempManager::class);
672
+
673
+        $this->registerService(AppManager::class, function (Server $c) {
674
+            return new \OC\App\AppManager(
675
+                $c->getUserSession(),
676
+                $c->getAppConfig(),
677
+                $c->getGroupManager(),
678
+                $c->getMemCacheFactory(),
679
+                $c->getEventDispatcher()
680
+            );
681
+        });
682
+        $this->registerAlias('AppManager', AppManager::class);
683
+        $this->registerAlias(IAppManager::class, AppManager::class);
684
+
685
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
686
+            return new DateTimeZone(
687
+                $c->getConfig(),
688
+                $c->getSession()
689
+            );
690
+        });
691
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
692
+
693
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
694
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
695
+
696
+            return new DateTimeFormatter(
697
+                $c->getDateTimeZone()->getTimeZone(),
698
+                $c->getL10N('lib', $language)
699
+            );
700
+        });
701
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
702
+
703
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
704
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
705
+            $listener = new UserMountCacheListener($mountCache);
706
+            $listener->listen($c->getUserManager());
707
+            return $mountCache;
708
+        });
709
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
710
+
711
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
712
+            $loader = \OC\Files\Filesystem::getLoader();
713
+            $mountCache = $c->query('UserMountCache');
714
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
715
+
716
+            // builtin providers
717
+
718
+            $config = $c->getConfig();
719
+            $manager->registerProvider(new CacheMountProvider($config));
720
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
721
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
722
+
723
+            return $manager;
724
+        });
725
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
726
+
727
+        $this->registerService('IniWrapper', function ($c) {
728
+            return new IniGetWrapper();
729
+        });
730
+        $this->registerService('AsyncCommandBus', function (Server $c) {
731
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
732
+            if ($busClass) {
733
+                list($app, $class) = explode('::', $busClass, 2);
734
+                if ($c->getAppManager()->isInstalled($app)) {
735
+                    \OC_App::loadApp($app);
736
+                    return $c->query($class);
737
+                } else {
738
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
739
+                }
740
+            } else {
741
+                $jobList = $c->getJobList();
742
+                return new CronBus($jobList);
743
+            }
744
+        });
745
+        $this->registerService('TrustedDomainHelper', function ($c) {
746
+            return new TrustedDomainHelper($this->getConfig());
747
+        });
748
+        $this->registerService('Throttler', function (Server $c) {
749
+            return new Throttler(
750
+                $c->getDatabaseConnection(),
751
+                new TimeFactory(),
752
+                $c->getLogger(),
753
+                $c->getConfig()
754
+            );
755
+        });
756
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
757
+            // IConfig and IAppManager requires a working database. This code
758
+            // might however be called when ownCloud is not yet setup.
759
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
760
+                $config = $c->getConfig();
761
+                $appManager = $c->getAppManager();
762
+            } else {
763
+                $config = null;
764
+                $appManager = null;
765
+            }
766
+
767
+            return new Checker(
768
+                new EnvironmentHelper(),
769
+                new FileAccessHelper(),
770
+                new AppLocator(),
771
+                $config,
772
+                $c->getMemCacheFactory(),
773
+                $appManager,
774
+                $c->getTempManager()
775
+            );
776
+        });
777
+        $this->registerService(\OCP\IRequest::class, function ($c) {
778
+            if (isset($this['urlParams'])) {
779
+                $urlParams = $this['urlParams'];
780
+            } else {
781
+                $urlParams = [];
782
+            }
783
+
784
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
785
+                && in_array('fakeinput', stream_get_wrappers())
786
+            ) {
787
+                $stream = 'fakeinput://data';
788
+            } else {
789
+                $stream = 'php://input';
790
+            }
791
+
792
+            return new Request(
793
+                [
794
+                    'get' => $_GET,
795
+                    'post' => $_POST,
796
+                    'files' => $_FILES,
797
+                    'server' => $_SERVER,
798
+                    'env' => $_ENV,
799
+                    'cookies' => $_COOKIE,
800
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
801
+                        ? $_SERVER['REQUEST_METHOD']
802
+                        : null,
803
+                    'urlParams' => $urlParams,
804
+                ],
805
+                $this->getSecureRandom(),
806
+                $this->getConfig(),
807
+                $this->getCsrfTokenManager(),
808
+                $stream
809
+            );
810
+        });
811
+        $this->registerAlias('Request', \OCP\IRequest::class);
812
+
813
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
814
+            return new Mailer(
815
+                $c->getConfig(),
816
+                $c->getLogger(),
817
+                $c->query(Defaults::class),
818
+                $c->getURLGenerator(),
819
+                $c->getL10N('lib')
820
+            );
821
+        });
822
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
823
+
824
+        $this->registerService('LDAPProvider', function (Server $c) {
825
+            $config = $c->getConfig();
826
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
827
+            if (is_null($factoryClass)) {
828
+                throw new \Exception('ldapProviderFactory not set');
829
+            }
830
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
831
+            $factory = new $factoryClass($this);
832
+            return $factory->getLDAPProvider();
833
+        });
834
+        $this->registerService(ILockingProvider::class, function (Server $c) {
835
+            $ini = $c->getIniWrapper();
836
+            $config = $c->getConfig();
837
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
838
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
839
+                /** @var \OC\Memcache\Factory $memcacheFactory */
840
+                $memcacheFactory = $c->getMemCacheFactory();
841
+                $memcache = $memcacheFactory->createLocking('lock');
842
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
843
+                    return new MemcacheLockingProvider($memcache, $ttl);
844
+                }
845
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
846
+            }
847
+            return new NoopLockingProvider();
848
+        });
849
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
850
+
851
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
852
+            return new \OC\Files\Mount\Manager();
853
+        });
854
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
855
+
856
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
857
+            return new \OC\Files\Type\Detection(
858
+                $c->getURLGenerator(),
859
+                \OC::$configDir,
860
+                \OC::$SERVERROOT . '/resources/config/'
861
+            );
862
+        });
863
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
864
+
865
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
866
+            return new \OC\Files\Type\Loader(
867
+                $c->getDatabaseConnection()
868
+            );
869
+        });
870
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
871
+        $this->registerService(BundleFetcher::class, function () {
872
+            return new BundleFetcher($this->getL10N('lib'));
873
+        });
874
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
875
+            return new Manager(
876
+                $c->query(IValidator::class)
877
+            );
878
+        });
879
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
880
+
881
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
882
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
883
+            $manager->registerCapability(function () use ($c) {
884
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
885
+            });
886
+            $manager->registerCapability(function () use ($c) {
887
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
888
+            });
889
+            return $manager;
890
+        });
891
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
892
+
893
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
894
+            $config = $c->getConfig();
895
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
896
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
897
+            $factory = new $factoryClass($this);
898
+            return $factory->getManager();
899
+        });
900
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
901
+
902
+        $this->registerService('ThemingDefaults', function (Server $c) {
903
+            /*
904 904
 			 * Dark magic for autoloader.
905 905
 			 * If we do a class_exists it will try to load the class which will
906 906
 			 * make composer cache the result. Resulting in errors when enabling
907 907
 			 * the theming app.
908 908
 			 */
909
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
910
-			if (isset($prefixes['OCA\\Theming\\'])) {
911
-				$classExists = true;
912
-			} else {
913
-				$classExists = false;
914
-			}
915
-
916
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
917
-				return new ThemingDefaults(
918
-					$c->getConfig(),
919
-					$c->getL10N('theming'),
920
-					$c->getURLGenerator(),
921
-					$c->getAppDataDir('theming'),
922
-					$c->getMemCacheFactory(),
923
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
924
-					$this->getAppManager()
925
-				);
926
-			}
927
-			return new \OC_Defaults();
928
-		});
929
-		$this->registerService(SCSSCacher::class, function (Server $c) {
930
-			/** @var Factory $cacheFactory */
931
-			$cacheFactory = $c->query(Factory::class);
932
-			return new SCSSCacher(
933
-				$c->getLogger(),
934
-				$c->query(\OC\Files\AppData\Factory::class),
935
-				$c->getURLGenerator(),
936
-				$c->getConfig(),
937
-				$c->getThemingDefaults(),
938
-				\OC::$SERVERROOT,
939
-				$cacheFactory->create('SCSS')
940
-			);
941
-		});
942
-		$this->registerService(EventDispatcher::class, function () {
943
-			return new EventDispatcher();
944
-		});
945
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
946
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
947
-
948
-		$this->registerService('CryptoWrapper', function (Server $c) {
949
-			// FIXME: Instantiiated here due to cyclic dependency
950
-			$request = new Request(
951
-				[
952
-					'get' => $_GET,
953
-					'post' => $_POST,
954
-					'files' => $_FILES,
955
-					'server' => $_SERVER,
956
-					'env' => $_ENV,
957
-					'cookies' => $_COOKIE,
958
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
959
-						? $_SERVER['REQUEST_METHOD']
960
-						: null,
961
-				],
962
-				$c->getSecureRandom(),
963
-				$c->getConfig()
964
-			);
965
-
966
-			return new CryptoWrapper(
967
-				$c->getConfig(),
968
-				$c->getCrypto(),
969
-				$c->getSecureRandom(),
970
-				$request
971
-			);
972
-		});
973
-		$this->registerService('CsrfTokenManager', function (Server $c) {
974
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
975
-
976
-			return new CsrfTokenManager(
977
-				$tokenGenerator,
978
-				$c->query(SessionStorage::class)
979
-			);
980
-		});
981
-		$this->registerService(SessionStorage::class, function (Server $c) {
982
-			return new SessionStorage($c->getSession());
983
-		});
984
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
985
-			return new ContentSecurityPolicyManager();
986
-		});
987
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
988
-
989
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
990
-			return new ContentSecurityPolicyNonceManager(
991
-				$c->getCsrfTokenManager(),
992
-				$c->getRequest()
993
-			);
994
-		});
995
-
996
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
997
-			$config = $c->getConfig();
998
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
999
-			/** @var \OCP\Share\IProviderFactory $factory */
1000
-			$factory = new $factoryClass($this);
1001
-
1002
-			$manager = new \OC\Share20\Manager(
1003
-				$c->getLogger(),
1004
-				$c->getConfig(),
1005
-				$c->getSecureRandom(),
1006
-				$c->getHasher(),
1007
-				$c->getMountManager(),
1008
-				$c->getGroupManager(),
1009
-				$c->getL10N('lib'),
1010
-				$c->getL10NFactory(),
1011
-				$factory,
1012
-				$c->getUserManager(),
1013
-				$c->getLazyRootFolder(),
1014
-				$c->getEventDispatcher(),
1015
-				$c->getMailer(),
1016
-				$c->getURLGenerator(),
1017
-				$c->getThemingDefaults()
1018
-			);
1019
-
1020
-			return $manager;
1021
-		});
1022
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1023
-
1024
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1025
-			$instance = new Collaboration\Collaborators\Search($c);
1026
-
1027
-			// register default plugins
1028
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1029
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1030
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1031
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1032
-
1033
-			return $instance;
1034
-		});
1035
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1036
-
1037
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1038
-
1039
-		$this->registerService('SettingsManager', function (Server $c) {
1040
-			$manager = new \OC\Settings\Manager(
1041
-				$c->getLogger(),
1042
-				$c->getDatabaseConnection(),
1043
-				$c->getL10N('lib'),
1044
-				$c->getConfig(),
1045
-				$c->getEncryptionManager(),
1046
-				$c->getUserManager(),
1047
-				$c->getLockingProvider(),
1048
-				$c->getRequest(),
1049
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1050
-				$c->getURLGenerator(),
1051
-				$c->query(AccountManager::class),
1052
-				$c->getGroupManager(),
1053
-				$c->getL10NFactory(),
1054
-				$c->getThemingDefaults(),
1055
-				$c->getAppManager()
1056
-			);
1057
-			return $manager;
1058
-		});
1059
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1060
-			return new \OC\Files\AppData\Factory(
1061
-				$c->getRootFolder(),
1062
-				$c->getSystemConfig()
1063
-			);
1064
-		});
1065
-
1066
-		$this->registerService('LockdownManager', function (Server $c) {
1067
-			return new LockdownManager(function () use ($c) {
1068
-				return $c->getSession();
1069
-			});
1070
-		});
1071
-
1072
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1073
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1074
-		});
1075
-
1076
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1077
-			return new CloudIdManager();
1078
-		});
1079
-
1080
-		/* To trick DI since we don't extend the DIContainer here */
1081
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1082
-			return new CleanPreviewsBackgroundJob(
1083
-				$c->getRootFolder(),
1084
-				$c->getLogger(),
1085
-				$c->getJobList(),
1086
-				new TimeFactory()
1087
-			);
1088
-		});
1089
-
1090
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1091
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1092
-
1093
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1094
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1095
-
1096
-		$this->registerService(Defaults::class, function (Server $c) {
1097
-			return new Defaults(
1098
-				$c->getThemingDefaults()
1099
-			);
1100
-		});
1101
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1102
-
1103
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1104
-			return $c->query(\OCP\IUserSession::class)->getSession();
1105
-		});
1106
-
1107
-		$this->registerService(IShareHelper::class, function (Server $c) {
1108
-			return new ShareHelper(
1109
-				$c->query(\OCP\Share\IManager::class)
1110
-			);
1111
-		});
1112
-
1113
-		$this->registerService(Installer::class, function(Server $c) {
1114
-			return new Installer(
1115
-				$c->getAppFetcher(),
1116
-				$c->getHTTPClientService(),
1117
-				$c->getTempManager(),
1118
-				$c->getLogger(),
1119
-				$c->getConfig()
1120
-			);
1121
-		});
1122
-
1123
-		$this->registerService(IApiFactory::class, function(Server $c) {
1124
-			return new ApiFactory($c->getHTTPClientService());
1125
-		});
1126
-
1127
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1128
-			$memcacheFactory = $c->getMemCacheFactory();
1129
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1130
-		});
1131
-
1132
-		$this->connectDispatcher();
1133
-	}
1134
-
1135
-	/**
1136
-	 * @return \OCP\Calendar\IManager
1137
-	 */
1138
-	public function getCalendarManager() {
1139
-		return $this->query('CalendarManager');
1140
-	}
1141
-
1142
-	private function connectDispatcher() {
1143
-		$dispatcher = $this->getEventDispatcher();
1144
-
1145
-		// Delete avatar on user deletion
1146
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1147
-			$logger = $this->getLogger();
1148
-			$manager = $this->getAvatarManager();
1149
-			/** @var IUser $user */
1150
-			$user = $e->getSubject();
1151
-
1152
-			try {
1153
-				$avatar = $manager->getAvatar($user->getUID());
1154
-				$avatar->remove();
1155
-			} catch (NotFoundException $e) {
1156
-				// no avatar to remove
1157
-			} catch (\Exception $e) {
1158
-				// Ignore exceptions
1159
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1160
-			}
1161
-		});
1162
-	}
1163
-
1164
-	/**
1165
-	 * @return \OCP\Contacts\IManager
1166
-	 */
1167
-	public function getContactsManager() {
1168
-		return $this->query('ContactsManager');
1169
-	}
1170
-
1171
-	/**
1172
-	 * @return \OC\Encryption\Manager
1173
-	 */
1174
-	public function getEncryptionManager() {
1175
-		return $this->query('EncryptionManager');
1176
-	}
1177
-
1178
-	/**
1179
-	 * @return \OC\Encryption\File
1180
-	 */
1181
-	public function getEncryptionFilesHelper() {
1182
-		return $this->query('EncryptionFileHelper');
1183
-	}
1184
-
1185
-	/**
1186
-	 * @return \OCP\Encryption\Keys\IStorage
1187
-	 */
1188
-	public function getEncryptionKeyStorage() {
1189
-		return $this->query('EncryptionKeyStorage');
1190
-	}
1191
-
1192
-	/**
1193
-	 * The current request object holding all information about the request
1194
-	 * currently being processed is returned from this method.
1195
-	 * In case the current execution was not initiated by a web request null is returned
1196
-	 *
1197
-	 * @return \OCP\IRequest
1198
-	 */
1199
-	public function getRequest() {
1200
-		return $this->query('Request');
1201
-	}
1202
-
1203
-	/**
1204
-	 * Returns the preview manager which can create preview images for a given file
1205
-	 *
1206
-	 * @return \OCP\IPreview
1207
-	 */
1208
-	public function getPreviewManager() {
1209
-		return $this->query('PreviewManager');
1210
-	}
1211
-
1212
-	/**
1213
-	 * Returns the tag manager which can get and set tags for different object types
1214
-	 *
1215
-	 * @see \OCP\ITagManager::load()
1216
-	 * @return \OCP\ITagManager
1217
-	 */
1218
-	public function getTagManager() {
1219
-		return $this->query('TagManager');
1220
-	}
1221
-
1222
-	/**
1223
-	 * Returns the system-tag manager
1224
-	 *
1225
-	 * @return \OCP\SystemTag\ISystemTagManager
1226
-	 *
1227
-	 * @since 9.0.0
1228
-	 */
1229
-	public function getSystemTagManager() {
1230
-		return $this->query('SystemTagManager');
1231
-	}
1232
-
1233
-	/**
1234
-	 * Returns the system-tag object mapper
1235
-	 *
1236
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1237
-	 *
1238
-	 * @since 9.0.0
1239
-	 */
1240
-	public function getSystemTagObjectMapper() {
1241
-		return $this->query('SystemTagObjectMapper');
1242
-	}
1243
-
1244
-	/**
1245
-	 * Returns the avatar manager, used for avatar functionality
1246
-	 *
1247
-	 * @return \OCP\IAvatarManager
1248
-	 */
1249
-	public function getAvatarManager() {
1250
-		return $this->query('AvatarManager');
1251
-	}
1252
-
1253
-	/**
1254
-	 * Returns the root folder of ownCloud's data directory
1255
-	 *
1256
-	 * @return \OCP\Files\IRootFolder
1257
-	 */
1258
-	public function getRootFolder() {
1259
-		return $this->query('LazyRootFolder');
1260
-	}
1261
-
1262
-	/**
1263
-	 * Returns the root folder of ownCloud's data directory
1264
-	 * This is the lazy variant so this gets only initialized once it
1265
-	 * is actually used.
1266
-	 *
1267
-	 * @return \OCP\Files\IRootFolder
1268
-	 */
1269
-	public function getLazyRootFolder() {
1270
-		return $this->query('LazyRootFolder');
1271
-	}
1272
-
1273
-	/**
1274
-	 * Returns a view to ownCloud's files folder
1275
-	 *
1276
-	 * @param string $userId user ID
1277
-	 * @return \OCP\Files\Folder|null
1278
-	 */
1279
-	public function getUserFolder($userId = null) {
1280
-		if ($userId === null) {
1281
-			$user = $this->getUserSession()->getUser();
1282
-			if (!$user) {
1283
-				return null;
1284
-			}
1285
-			$userId = $user->getUID();
1286
-		}
1287
-		$root = $this->getRootFolder();
1288
-		return $root->getUserFolder($userId);
1289
-	}
1290
-
1291
-	/**
1292
-	 * Returns an app-specific view in ownClouds data directory
1293
-	 *
1294
-	 * @return \OCP\Files\Folder
1295
-	 * @deprecated since 9.2.0 use IAppData
1296
-	 */
1297
-	public function getAppFolder() {
1298
-		$dir = '/' . \OC_App::getCurrentApp();
1299
-		$root = $this->getRootFolder();
1300
-		if (!$root->nodeExists($dir)) {
1301
-			$folder = $root->newFolder($dir);
1302
-		} else {
1303
-			$folder = $root->get($dir);
1304
-		}
1305
-		return $folder;
1306
-	}
1307
-
1308
-	/**
1309
-	 * @return \OC\User\Manager
1310
-	 */
1311
-	public function getUserManager() {
1312
-		return $this->query('UserManager');
1313
-	}
1314
-
1315
-	/**
1316
-	 * @return \OC\Group\Manager
1317
-	 */
1318
-	public function getGroupManager() {
1319
-		return $this->query('GroupManager');
1320
-	}
1321
-
1322
-	/**
1323
-	 * @return \OC\User\Session
1324
-	 */
1325
-	public function getUserSession() {
1326
-		return $this->query('UserSession');
1327
-	}
1328
-
1329
-	/**
1330
-	 * @return \OCP\ISession
1331
-	 */
1332
-	public function getSession() {
1333
-		return $this->query('UserSession')->getSession();
1334
-	}
1335
-
1336
-	/**
1337
-	 * @param \OCP\ISession $session
1338
-	 */
1339
-	public function setSession(\OCP\ISession $session) {
1340
-		$this->query(SessionStorage::class)->setSession($session);
1341
-		$this->query('UserSession')->setSession($session);
1342
-		$this->query(Store::class)->setSession($session);
1343
-	}
1344
-
1345
-	/**
1346
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1347
-	 */
1348
-	public function getTwoFactorAuthManager() {
1349
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1350
-	}
1351
-
1352
-	/**
1353
-	 * @return \OC\NavigationManager
1354
-	 */
1355
-	public function getNavigationManager() {
1356
-		return $this->query('NavigationManager');
1357
-	}
1358
-
1359
-	/**
1360
-	 * @return \OCP\IConfig
1361
-	 */
1362
-	public function getConfig() {
1363
-		return $this->query('AllConfig');
1364
-	}
1365
-
1366
-	/**
1367
-	 * @return \OC\SystemConfig
1368
-	 */
1369
-	public function getSystemConfig() {
1370
-		return $this->query('SystemConfig');
1371
-	}
1372
-
1373
-	/**
1374
-	 * Returns the app config manager
1375
-	 *
1376
-	 * @return \OCP\IAppConfig
1377
-	 */
1378
-	public function getAppConfig() {
1379
-		return $this->query('AppConfig');
1380
-	}
1381
-
1382
-	/**
1383
-	 * @return \OCP\L10N\IFactory
1384
-	 */
1385
-	public function getL10NFactory() {
1386
-		return $this->query('L10NFactory');
1387
-	}
1388
-
1389
-	/**
1390
-	 * get an L10N instance
1391
-	 *
1392
-	 * @param string $app appid
1393
-	 * @param string $lang
1394
-	 * @return IL10N
1395
-	 */
1396
-	public function getL10N($app, $lang = null) {
1397
-		return $this->getL10NFactory()->get($app, $lang);
1398
-	}
1399
-
1400
-	/**
1401
-	 * @return \OCP\IURLGenerator
1402
-	 */
1403
-	public function getURLGenerator() {
1404
-		return $this->query('URLGenerator');
1405
-	}
1406
-
1407
-	/**
1408
-	 * @return \OCP\IHelper
1409
-	 */
1410
-	public function getHelper() {
1411
-		return $this->query('AppHelper');
1412
-	}
1413
-
1414
-	/**
1415
-	 * @return AppFetcher
1416
-	 */
1417
-	public function getAppFetcher() {
1418
-		return $this->query(AppFetcher::class);
1419
-	}
1420
-
1421
-	/**
1422
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1423
-	 * getMemCacheFactory() instead.
1424
-	 *
1425
-	 * @return \OCP\ICache
1426
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1427
-	 */
1428
-	public function getCache() {
1429
-		return $this->query('UserCache');
1430
-	}
1431
-
1432
-	/**
1433
-	 * Returns an \OCP\CacheFactory instance
1434
-	 *
1435
-	 * @return \OCP\ICacheFactory
1436
-	 */
1437
-	public function getMemCacheFactory() {
1438
-		return $this->query('MemCacheFactory');
1439
-	}
1440
-
1441
-	/**
1442
-	 * Returns an \OC\RedisFactory instance
1443
-	 *
1444
-	 * @return \OC\RedisFactory
1445
-	 */
1446
-	public function getGetRedisFactory() {
1447
-		return $this->query('RedisFactory');
1448
-	}
1449
-
1450
-
1451
-	/**
1452
-	 * Returns the current session
1453
-	 *
1454
-	 * @return \OCP\IDBConnection
1455
-	 */
1456
-	public function getDatabaseConnection() {
1457
-		return $this->query('DatabaseConnection');
1458
-	}
1459
-
1460
-	/**
1461
-	 * Returns the activity manager
1462
-	 *
1463
-	 * @return \OCP\Activity\IManager
1464
-	 */
1465
-	public function getActivityManager() {
1466
-		return $this->query('ActivityManager');
1467
-	}
1468
-
1469
-	/**
1470
-	 * Returns an job list for controlling background jobs
1471
-	 *
1472
-	 * @return \OCP\BackgroundJob\IJobList
1473
-	 */
1474
-	public function getJobList() {
1475
-		return $this->query('JobList');
1476
-	}
1477
-
1478
-	/**
1479
-	 * Returns a logger instance
1480
-	 *
1481
-	 * @return \OCP\ILogger
1482
-	 */
1483
-	public function getLogger() {
1484
-		return $this->query('Logger');
1485
-	}
1486
-
1487
-	/**
1488
-	 * Returns a router for generating and matching urls
1489
-	 *
1490
-	 * @return \OCP\Route\IRouter
1491
-	 */
1492
-	public function getRouter() {
1493
-		return $this->query('Router');
1494
-	}
1495
-
1496
-	/**
1497
-	 * Returns a search instance
1498
-	 *
1499
-	 * @return \OCP\ISearch
1500
-	 */
1501
-	public function getSearch() {
1502
-		return $this->query('Search');
1503
-	}
1504
-
1505
-	/**
1506
-	 * Returns a SecureRandom instance
1507
-	 *
1508
-	 * @return \OCP\Security\ISecureRandom
1509
-	 */
1510
-	public function getSecureRandom() {
1511
-		return $this->query('SecureRandom');
1512
-	}
1513
-
1514
-	/**
1515
-	 * Returns a Crypto instance
1516
-	 *
1517
-	 * @return \OCP\Security\ICrypto
1518
-	 */
1519
-	public function getCrypto() {
1520
-		return $this->query('Crypto');
1521
-	}
1522
-
1523
-	/**
1524
-	 * Returns a Hasher instance
1525
-	 *
1526
-	 * @return \OCP\Security\IHasher
1527
-	 */
1528
-	public function getHasher() {
1529
-		return $this->query('Hasher');
1530
-	}
1531
-
1532
-	/**
1533
-	 * Returns a CredentialsManager instance
1534
-	 *
1535
-	 * @return \OCP\Security\ICredentialsManager
1536
-	 */
1537
-	public function getCredentialsManager() {
1538
-		return $this->query('CredentialsManager');
1539
-	}
1540
-
1541
-	/**
1542
-	 * Returns an instance of the HTTP helper class
1543
-	 *
1544
-	 * @deprecated Use getHTTPClientService()
1545
-	 * @return \OC\HTTPHelper
1546
-	 */
1547
-	public function getHTTPHelper() {
1548
-		return $this->query('HTTPHelper');
1549
-	}
1550
-
1551
-	/**
1552
-	 * Get the certificate manager for the user
1553
-	 *
1554
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1555
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1556
-	 */
1557
-	public function getCertificateManager($userId = '') {
1558
-		if ($userId === '') {
1559
-			$userSession = $this->getUserSession();
1560
-			$user = $userSession->getUser();
1561
-			if (is_null($user)) {
1562
-				return null;
1563
-			}
1564
-			$userId = $user->getUID();
1565
-		}
1566
-		return new CertificateManager(
1567
-			$userId,
1568
-			new View(),
1569
-			$this->getConfig(),
1570
-			$this->getLogger(),
1571
-			$this->getSecureRandom()
1572
-		);
1573
-	}
1574
-
1575
-	/**
1576
-	 * Returns an instance of the HTTP client service
1577
-	 *
1578
-	 * @return \OCP\Http\Client\IClientService
1579
-	 */
1580
-	public function getHTTPClientService() {
1581
-		return $this->query('HttpClientService');
1582
-	}
1583
-
1584
-	/**
1585
-	 * Create a new event source
1586
-	 *
1587
-	 * @return \OCP\IEventSource
1588
-	 */
1589
-	public function createEventSource() {
1590
-		return new \OC_EventSource();
1591
-	}
1592
-
1593
-	/**
1594
-	 * Get the active event logger
1595
-	 *
1596
-	 * The returned logger only logs data when debug mode is enabled
1597
-	 *
1598
-	 * @return \OCP\Diagnostics\IEventLogger
1599
-	 */
1600
-	public function getEventLogger() {
1601
-		return $this->query('EventLogger');
1602
-	}
1603
-
1604
-	/**
1605
-	 * Get the active query logger
1606
-	 *
1607
-	 * The returned logger only logs data when debug mode is enabled
1608
-	 *
1609
-	 * @return \OCP\Diagnostics\IQueryLogger
1610
-	 */
1611
-	public function getQueryLogger() {
1612
-		return $this->query('QueryLogger');
1613
-	}
1614
-
1615
-	/**
1616
-	 * Get the manager for temporary files and folders
1617
-	 *
1618
-	 * @return \OCP\ITempManager
1619
-	 */
1620
-	public function getTempManager() {
1621
-		return $this->query('TempManager');
1622
-	}
1623
-
1624
-	/**
1625
-	 * Get the app manager
1626
-	 *
1627
-	 * @return \OCP\App\IAppManager
1628
-	 */
1629
-	public function getAppManager() {
1630
-		return $this->query('AppManager');
1631
-	}
1632
-
1633
-	/**
1634
-	 * Creates a new mailer
1635
-	 *
1636
-	 * @return \OCP\Mail\IMailer
1637
-	 */
1638
-	public function getMailer() {
1639
-		return $this->query('Mailer');
1640
-	}
1641
-
1642
-	/**
1643
-	 * Get the webroot
1644
-	 *
1645
-	 * @return string
1646
-	 */
1647
-	public function getWebRoot() {
1648
-		return $this->webRoot;
1649
-	}
1650
-
1651
-	/**
1652
-	 * @return \OC\OCSClient
1653
-	 */
1654
-	public function getOcsClient() {
1655
-		return $this->query('OcsClient');
1656
-	}
1657
-
1658
-	/**
1659
-	 * @return \OCP\IDateTimeZone
1660
-	 */
1661
-	public function getDateTimeZone() {
1662
-		return $this->query('DateTimeZone');
1663
-	}
1664
-
1665
-	/**
1666
-	 * @return \OCP\IDateTimeFormatter
1667
-	 */
1668
-	public function getDateTimeFormatter() {
1669
-		return $this->query('DateTimeFormatter');
1670
-	}
1671
-
1672
-	/**
1673
-	 * @return \OCP\Files\Config\IMountProviderCollection
1674
-	 */
1675
-	public function getMountProviderCollection() {
1676
-		return $this->query('MountConfigManager');
1677
-	}
1678
-
1679
-	/**
1680
-	 * Get the IniWrapper
1681
-	 *
1682
-	 * @return IniGetWrapper
1683
-	 */
1684
-	public function getIniWrapper() {
1685
-		return $this->query('IniWrapper');
1686
-	}
1687
-
1688
-	/**
1689
-	 * @return \OCP\Command\IBus
1690
-	 */
1691
-	public function getCommandBus() {
1692
-		return $this->query('AsyncCommandBus');
1693
-	}
1694
-
1695
-	/**
1696
-	 * Get the trusted domain helper
1697
-	 *
1698
-	 * @return TrustedDomainHelper
1699
-	 */
1700
-	public function getTrustedDomainHelper() {
1701
-		return $this->query('TrustedDomainHelper');
1702
-	}
1703
-
1704
-	/**
1705
-	 * Get the locking provider
1706
-	 *
1707
-	 * @return \OCP\Lock\ILockingProvider
1708
-	 * @since 8.1.0
1709
-	 */
1710
-	public function getLockingProvider() {
1711
-		return $this->query('LockingProvider');
1712
-	}
1713
-
1714
-	/**
1715
-	 * @return \OCP\Files\Mount\IMountManager
1716
-	 **/
1717
-	function getMountManager() {
1718
-		return $this->query('MountManager');
1719
-	}
1720
-
1721
-	/** @return \OCP\Files\Config\IUserMountCache */
1722
-	function getUserMountCache() {
1723
-		return $this->query('UserMountCache');
1724
-	}
1725
-
1726
-	/**
1727
-	 * Get the MimeTypeDetector
1728
-	 *
1729
-	 * @return \OCP\Files\IMimeTypeDetector
1730
-	 */
1731
-	public function getMimeTypeDetector() {
1732
-		return $this->query('MimeTypeDetector');
1733
-	}
1734
-
1735
-	/**
1736
-	 * Get the MimeTypeLoader
1737
-	 *
1738
-	 * @return \OCP\Files\IMimeTypeLoader
1739
-	 */
1740
-	public function getMimeTypeLoader() {
1741
-		return $this->query('MimeTypeLoader');
1742
-	}
1743
-
1744
-	/**
1745
-	 * Get the manager of all the capabilities
1746
-	 *
1747
-	 * @return \OC\CapabilitiesManager
1748
-	 */
1749
-	public function getCapabilitiesManager() {
1750
-		return $this->query('CapabilitiesManager');
1751
-	}
1752
-
1753
-	/**
1754
-	 * Get the EventDispatcher
1755
-	 *
1756
-	 * @return EventDispatcherInterface
1757
-	 * @since 8.2.0
1758
-	 */
1759
-	public function getEventDispatcher() {
1760
-		return $this->query('EventDispatcher');
1761
-	}
1762
-
1763
-	/**
1764
-	 * Get the Notification Manager
1765
-	 *
1766
-	 * @return \OCP\Notification\IManager
1767
-	 * @since 8.2.0
1768
-	 */
1769
-	public function getNotificationManager() {
1770
-		return $this->query('NotificationManager');
1771
-	}
1772
-
1773
-	/**
1774
-	 * @return \OCP\Comments\ICommentsManager
1775
-	 */
1776
-	public function getCommentsManager() {
1777
-		return $this->query('CommentsManager');
1778
-	}
1779
-
1780
-	/**
1781
-	 * @return \OCA\Theming\ThemingDefaults
1782
-	 */
1783
-	public function getThemingDefaults() {
1784
-		return $this->query('ThemingDefaults');
1785
-	}
1786
-
1787
-	/**
1788
-	 * @return \OC\IntegrityCheck\Checker
1789
-	 */
1790
-	public function getIntegrityCodeChecker() {
1791
-		return $this->query('IntegrityCodeChecker');
1792
-	}
1793
-
1794
-	/**
1795
-	 * @return \OC\Session\CryptoWrapper
1796
-	 */
1797
-	public function getSessionCryptoWrapper() {
1798
-		return $this->query('CryptoWrapper');
1799
-	}
1800
-
1801
-	/**
1802
-	 * @return CsrfTokenManager
1803
-	 */
1804
-	public function getCsrfTokenManager() {
1805
-		return $this->query('CsrfTokenManager');
1806
-	}
1807
-
1808
-	/**
1809
-	 * @return Throttler
1810
-	 */
1811
-	public function getBruteForceThrottler() {
1812
-		return $this->query('Throttler');
1813
-	}
1814
-
1815
-	/**
1816
-	 * @return IContentSecurityPolicyManager
1817
-	 */
1818
-	public function getContentSecurityPolicyManager() {
1819
-		return $this->query('ContentSecurityPolicyManager');
1820
-	}
1821
-
1822
-	/**
1823
-	 * @return ContentSecurityPolicyNonceManager
1824
-	 */
1825
-	public function getContentSecurityPolicyNonceManager() {
1826
-		return $this->query('ContentSecurityPolicyNonceManager');
1827
-	}
1828
-
1829
-	/**
1830
-	 * Not a public API as of 8.2, wait for 9.0
1831
-	 *
1832
-	 * @return \OCA\Files_External\Service\BackendService
1833
-	 */
1834
-	public function getStoragesBackendService() {
1835
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1836
-	}
1837
-
1838
-	/**
1839
-	 * Not a public API as of 8.2, wait for 9.0
1840
-	 *
1841
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1842
-	 */
1843
-	public function getGlobalStoragesService() {
1844
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1845
-	}
1846
-
1847
-	/**
1848
-	 * Not a public API as of 8.2, wait for 9.0
1849
-	 *
1850
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1851
-	 */
1852
-	public function getUserGlobalStoragesService() {
1853
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1854
-	}
1855
-
1856
-	/**
1857
-	 * Not a public API as of 8.2, wait for 9.0
1858
-	 *
1859
-	 * @return \OCA\Files_External\Service\UserStoragesService
1860
-	 */
1861
-	public function getUserStoragesService() {
1862
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1863
-	}
1864
-
1865
-	/**
1866
-	 * @return \OCP\Share\IManager
1867
-	 */
1868
-	public function getShareManager() {
1869
-		return $this->query('ShareManager');
1870
-	}
1871
-
1872
-	/**
1873
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1874
-	 */
1875
-	public function getCollaboratorSearch() {
1876
-		return $this->query('CollaboratorSearch');
1877
-	}
1878
-
1879
-	/**
1880
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1881
-	 */
1882
-	public function getAutoCompleteManager(){
1883
-		return $this->query(IManager::class);
1884
-	}
1885
-
1886
-	/**
1887
-	 * Returns the LDAP Provider
1888
-	 *
1889
-	 * @return \OCP\LDAP\ILDAPProvider
1890
-	 */
1891
-	public function getLDAPProvider() {
1892
-		return $this->query('LDAPProvider');
1893
-	}
1894
-
1895
-	/**
1896
-	 * @return \OCP\Settings\IManager
1897
-	 */
1898
-	public function getSettingsManager() {
1899
-		return $this->query('SettingsManager');
1900
-	}
1901
-
1902
-	/**
1903
-	 * @return \OCP\Files\IAppData
1904
-	 */
1905
-	public function getAppDataDir($app) {
1906
-		/** @var \OC\Files\AppData\Factory $factory */
1907
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1908
-		return $factory->get($app);
1909
-	}
1910
-
1911
-	/**
1912
-	 * @return \OCP\Lockdown\ILockdownManager
1913
-	 */
1914
-	public function getLockdownManager() {
1915
-		return $this->query('LockdownManager');
1916
-	}
1917
-
1918
-	/**
1919
-	 * @return \OCP\Federation\ICloudIdManager
1920
-	 */
1921
-	public function getCloudIdManager() {
1922
-		return $this->query(ICloudIdManager::class);
1923
-	}
1924
-
1925
-	/**
1926
-	 * @return \OCP\Remote\Api\IApiFactory
1927
-	 */
1928
-	public function getRemoteApiFactory() {
1929
-		return $this->query(IApiFactory::class);
1930
-	}
1931
-
1932
-	/**
1933
-	 * @return \OCP\Remote\IInstanceFactory
1934
-	 */
1935
-	public function getRemoteInstanceFactory() {
1936
-		return $this->query(IInstanceFactory::class);
1937
-	}
909
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
910
+            if (isset($prefixes['OCA\\Theming\\'])) {
911
+                $classExists = true;
912
+            } else {
913
+                $classExists = false;
914
+            }
915
+
916
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
917
+                return new ThemingDefaults(
918
+                    $c->getConfig(),
919
+                    $c->getL10N('theming'),
920
+                    $c->getURLGenerator(),
921
+                    $c->getAppDataDir('theming'),
922
+                    $c->getMemCacheFactory(),
923
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
924
+                    $this->getAppManager()
925
+                );
926
+            }
927
+            return new \OC_Defaults();
928
+        });
929
+        $this->registerService(SCSSCacher::class, function (Server $c) {
930
+            /** @var Factory $cacheFactory */
931
+            $cacheFactory = $c->query(Factory::class);
932
+            return new SCSSCacher(
933
+                $c->getLogger(),
934
+                $c->query(\OC\Files\AppData\Factory::class),
935
+                $c->getURLGenerator(),
936
+                $c->getConfig(),
937
+                $c->getThemingDefaults(),
938
+                \OC::$SERVERROOT,
939
+                $cacheFactory->create('SCSS')
940
+            );
941
+        });
942
+        $this->registerService(EventDispatcher::class, function () {
943
+            return new EventDispatcher();
944
+        });
945
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
946
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
947
+
948
+        $this->registerService('CryptoWrapper', function (Server $c) {
949
+            // FIXME: Instantiiated here due to cyclic dependency
950
+            $request = new Request(
951
+                [
952
+                    'get' => $_GET,
953
+                    'post' => $_POST,
954
+                    'files' => $_FILES,
955
+                    'server' => $_SERVER,
956
+                    'env' => $_ENV,
957
+                    'cookies' => $_COOKIE,
958
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
959
+                        ? $_SERVER['REQUEST_METHOD']
960
+                        : null,
961
+                ],
962
+                $c->getSecureRandom(),
963
+                $c->getConfig()
964
+            );
965
+
966
+            return new CryptoWrapper(
967
+                $c->getConfig(),
968
+                $c->getCrypto(),
969
+                $c->getSecureRandom(),
970
+                $request
971
+            );
972
+        });
973
+        $this->registerService('CsrfTokenManager', function (Server $c) {
974
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
975
+
976
+            return new CsrfTokenManager(
977
+                $tokenGenerator,
978
+                $c->query(SessionStorage::class)
979
+            );
980
+        });
981
+        $this->registerService(SessionStorage::class, function (Server $c) {
982
+            return new SessionStorage($c->getSession());
983
+        });
984
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
985
+            return new ContentSecurityPolicyManager();
986
+        });
987
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
988
+
989
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
990
+            return new ContentSecurityPolicyNonceManager(
991
+                $c->getCsrfTokenManager(),
992
+                $c->getRequest()
993
+            );
994
+        });
995
+
996
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
997
+            $config = $c->getConfig();
998
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
999
+            /** @var \OCP\Share\IProviderFactory $factory */
1000
+            $factory = new $factoryClass($this);
1001
+
1002
+            $manager = new \OC\Share20\Manager(
1003
+                $c->getLogger(),
1004
+                $c->getConfig(),
1005
+                $c->getSecureRandom(),
1006
+                $c->getHasher(),
1007
+                $c->getMountManager(),
1008
+                $c->getGroupManager(),
1009
+                $c->getL10N('lib'),
1010
+                $c->getL10NFactory(),
1011
+                $factory,
1012
+                $c->getUserManager(),
1013
+                $c->getLazyRootFolder(),
1014
+                $c->getEventDispatcher(),
1015
+                $c->getMailer(),
1016
+                $c->getURLGenerator(),
1017
+                $c->getThemingDefaults()
1018
+            );
1019
+
1020
+            return $manager;
1021
+        });
1022
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1023
+
1024
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1025
+            $instance = new Collaboration\Collaborators\Search($c);
1026
+
1027
+            // register default plugins
1028
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1029
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1030
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1031
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1032
+
1033
+            return $instance;
1034
+        });
1035
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1036
+
1037
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1038
+
1039
+        $this->registerService('SettingsManager', function (Server $c) {
1040
+            $manager = new \OC\Settings\Manager(
1041
+                $c->getLogger(),
1042
+                $c->getDatabaseConnection(),
1043
+                $c->getL10N('lib'),
1044
+                $c->getConfig(),
1045
+                $c->getEncryptionManager(),
1046
+                $c->getUserManager(),
1047
+                $c->getLockingProvider(),
1048
+                $c->getRequest(),
1049
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1050
+                $c->getURLGenerator(),
1051
+                $c->query(AccountManager::class),
1052
+                $c->getGroupManager(),
1053
+                $c->getL10NFactory(),
1054
+                $c->getThemingDefaults(),
1055
+                $c->getAppManager()
1056
+            );
1057
+            return $manager;
1058
+        });
1059
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1060
+            return new \OC\Files\AppData\Factory(
1061
+                $c->getRootFolder(),
1062
+                $c->getSystemConfig()
1063
+            );
1064
+        });
1065
+
1066
+        $this->registerService('LockdownManager', function (Server $c) {
1067
+            return new LockdownManager(function () use ($c) {
1068
+                return $c->getSession();
1069
+            });
1070
+        });
1071
+
1072
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1073
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1074
+        });
1075
+
1076
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1077
+            return new CloudIdManager();
1078
+        });
1079
+
1080
+        /* To trick DI since we don't extend the DIContainer here */
1081
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1082
+            return new CleanPreviewsBackgroundJob(
1083
+                $c->getRootFolder(),
1084
+                $c->getLogger(),
1085
+                $c->getJobList(),
1086
+                new TimeFactory()
1087
+            );
1088
+        });
1089
+
1090
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1091
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1092
+
1093
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1094
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1095
+
1096
+        $this->registerService(Defaults::class, function (Server $c) {
1097
+            return new Defaults(
1098
+                $c->getThemingDefaults()
1099
+            );
1100
+        });
1101
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1102
+
1103
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1104
+            return $c->query(\OCP\IUserSession::class)->getSession();
1105
+        });
1106
+
1107
+        $this->registerService(IShareHelper::class, function (Server $c) {
1108
+            return new ShareHelper(
1109
+                $c->query(\OCP\Share\IManager::class)
1110
+            );
1111
+        });
1112
+
1113
+        $this->registerService(Installer::class, function(Server $c) {
1114
+            return new Installer(
1115
+                $c->getAppFetcher(),
1116
+                $c->getHTTPClientService(),
1117
+                $c->getTempManager(),
1118
+                $c->getLogger(),
1119
+                $c->getConfig()
1120
+            );
1121
+        });
1122
+
1123
+        $this->registerService(IApiFactory::class, function(Server $c) {
1124
+            return new ApiFactory($c->getHTTPClientService());
1125
+        });
1126
+
1127
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1128
+            $memcacheFactory = $c->getMemCacheFactory();
1129
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1130
+        });
1131
+
1132
+        $this->connectDispatcher();
1133
+    }
1134
+
1135
+    /**
1136
+     * @return \OCP\Calendar\IManager
1137
+     */
1138
+    public function getCalendarManager() {
1139
+        return $this->query('CalendarManager');
1140
+    }
1141
+
1142
+    private function connectDispatcher() {
1143
+        $dispatcher = $this->getEventDispatcher();
1144
+
1145
+        // Delete avatar on user deletion
1146
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1147
+            $logger = $this->getLogger();
1148
+            $manager = $this->getAvatarManager();
1149
+            /** @var IUser $user */
1150
+            $user = $e->getSubject();
1151
+
1152
+            try {
1153
+                $avatar = $manager->getAvatar($user->getUID());
1154
+                $avatar->remove();
1155
+            } catch (NotFoundException $e) {
1156
+                // no avatar to remove
1157
+            } catch (\Exception $e) {
1158
+                // Ignore exceptions
1159
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1160
+            }
1161
+        });
1162
+    }
1163
+
1164
+    /**
1165
+     * @return \OCP\Contacts\IManager
1166
+     */
1167
+    public function getContactsManager() {
1168
+        return $this->query('ContactsManager');
1169
+    }
1170
+
1171
+    /**
1172
+     * @return \OC\Encryption\Manager
1173
+     */
1174
+    public function getEncryptionManager() {
1175
+        return $this->query('EncryptionManager');
1176
+    }
1177
+
1178
+    /**
1179
+     * @return \OC\Encryption\File
1180
+     */
1181
+    public function getEncryptionFilesHelper() {
1182
+        return $this->query('EncryptionFileHelper');
1183
+    }
1184
+
1185
+    /**
1186
+     * @return \OCP\Encryption\Keys\IStorage
1187
+     */
1188
+    public function getEncryptionKeyStorage() {
1189
+        return $this->query('EncryptionKeyStorage');
1190
+    }
1191
+
1192
+    /**
1193
+     * The current request object holding all information about the request
1194
+     * currently being processed is returned from this method.
1195
+     * In case the current execution was not initiated by a web request null is returned
1196
+     *
1197
+     * @return \OCP\IRequest
1198
+     */
1199
+    public function getRequest() {
1200
+        return $this->query('Request');
1201
+    }
1202
+
1203
+    /**
1204
+     * Returns the preview manager which can create preview images for a given file
1205
+     *
1206
+     * @return \OCP\IPreview
1207
+     */
1208
+    public function getPreviewManager() {
1209
+        return $this->query('PreviewManager');
1210
+    }
1211
+
1212
+    /**
1213
+     * Returns the tag manager which can get and set tags for different object types
1214
+     *
1215
+     * @see \OCP\ITagManager::load()
1216
+     * @return \OCP\ITagManager
1217
+     */
1218
+    public function getTagManager() {
1219
+        return $this->query('TagManager');
1220
+    }
1221
+
1222
+    /**
1223
+     * Returns the system-tag manager
1224
+     *
1225
+     * @return \OCP\SystemTag\ISystemTagManager
1226
+     *
1227
+     * @since 9.0.0
1228
+     */
1229
+    public function getSystemTagManager() {
1230
+        return $this->query('SystemTagManager');
1231
+    }
1232
+
1233
+    /**
1234
+     * Returns the system-tag object mapper
1235
+     *
1236
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1237
+     *
1238
+     * @since 9.0.0
1239
+     */
1240
+    public function getSystemTagObjectMapper() {
1241
+        return $this->query('SystemTagObjectMapper');
1242
+    }
1243
+
1244
+    /**
1245
+     * Returns the avatar manager, used for avatar functionality
1246
+     *
1247
+     * @return \OCP\IAvatarManager
1248
+     */
1249
+    public function getAvatarManager() {
1250
+        return $this->query('AvatarManager');
1251
+    }
1252
+
1253
+    /**
1254
+     * Returns the root folder of ownCloud's data directory
1255
+     *
1256
+     * @return \OCP\Files\IRootFolder
1257
+     */
1258
+    public function getRootFolder() {
1259
+        return $this->query('LazyRootFolder');
1260
+    }
1261
+
1262
+    /**
1263
+     * Returns the root folder of ownCloud's data directory
1264
+     * This is the lazy variant so this gets only initialized once it
1265
+     * is actually used.
1266
+     *
1267
+     * @return \OCP\Files\IRootFolder
1268
+     */
1269
+    public function getLazyRootFolder() {
1270
+        return $this->query('LazyRootFolder');
1271
+    }
1272
+
1273
+    /**
1274
+     * Returns a view to ownCloud's files folder
1275
+     *
1276
+     * @param string $userId user ID
1277
+     * @return \OCP\Files\Folder|null
1278
+     */
1279
+    public function getUserFolder($userId = null) {
1280
+        if ($userId === null) {
1281
+            $user = $this->getUserSession()->getUser();
1282
+            if (!$user) {
1283
+                return null;
1284
+            }
1285
+            $userId = $user->getUID();
1286
+        }
1287
+        $root = $this->getRootFolder();
1288
+        return $root->getUserFolder($userId);
1289
+    }
1290
+
1291
+    /**
1292
+     * Returns an app-specific view in ownClouds data directory
1293
+     *
1294
+     * @return \OCP\Files\Folder
1295
+     * @deprecated since 9.2.0 use IAppData
1296
+     */
1297
+    public function getAppFolder() {
1298
+        $dir = '/' . \OC_App::getCurrentApp();
1299
+        $root = $this->getRootFolder();
1300
+        if (!$root->nodeExists($dir)) {
1301
+            $folder = $root->newFolder($dir);
1302
+        } else {
1303
+            $folder = $root->get($dir);
1304
+        }
1305
+        return $folder;
1306
+    }
1307
+
1308
+    /**
1309
+     * @return \OC\User\Manager
1310
+     */
1311
+    public function getUserManager() {
1312
+        return $this->query('UserManager');
1313
+    }
1314
+
1315
+    /**
1316
+     * @return \OC\Group\Manager
1317
+     */
1318
+    public function getGroupManager() {
1319
+        return $this->query('GroupManager');
1320
+    }
1321
+
1322
+    /**
1323
+     * @return \OC\User\Session
1324
+     */
1325
+    public function getUserSession() {
1326
+        return $this->query('UserSession');
1327
+    }
1328
+
1329
+    /**
1330
+     * @return \OCP\ISession
1331
+     */
1332
+    public function getSession() {
1333
+        return $this->query('UserSession')->getSession();
1334
+    }
1335
+
1336
+    /**
1337
+     * @param \OCP\ISession $session
1338
+     */
1339
+    public function setSession(\OCP\ISession $session) {
1340
+        $this->query(SessionStorage::class)->setSession($session);
1341
+        $this->query('UserSession')->setSession($session);
1342
+        $this->query(Store::class)->setSession($session);
1343
+    }
1344
+
1345
+    /**
1346
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1347
+     */
1348
+    public function getTwoFactorAuthManager() {
1349
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1350
+    }
1351
+
1352
+    /**
1353
+     * @return \OC\NavigationManager
1354
+     */
1355
+    public function getNavigationManager() {
1356
+        return $this->query('NavigationManager');
1357
+    }
1358
+
1359
+    /**
1360
+     * @return \OCP\IConfig
1361
+     */
1362
+    public function getConfig() {
1363
+        return $this->query('AllConfig');
1364
+    }
1365
+
1366
+    /**
1367
+     * @return \OC\SystemConfig
1368
+     */
1369
+    public function getSystemConfig() {
1370
+        return $this->query('SystemConfig');
1371
+    }
1372
+
1373
+    /**
1374
+     * Returns the app config manager
1375
+     *
1376
+     * @return \OCP\IAppConfig
1377
+     */
1378
+    public function getAppConfig() {
1379
+        return $this->query('AppConfig');
1380
+    }
1381
+
1382
+    /**
1383
+     * @return \OCP\L10N\IFactory
1384
+     */
1385
+    public function getL10NFactory() {
1386
+        return $this->query('L10NFactory');
1387
+    }
1388
+
1389
+    /**
1390
+     * get an L10N instance
1391
+     *
1392
+     * @param string $app appid
1393
+     * @param string $lang
1394
+     * @return IL10N
1395
+     */
1396
+    public function getL10N($app, $lang = null) {
1397
+        return $this->getL10NFactory()->get($app, $lang);
1398
+    }
1399
+
1400
+    /**
1401
+     * @return \OCP\IURLGenerator
1402
+     */
1403
+    public function getURLGenerator() {
1404
+        return $this->query('URLGenerator');
1405
+    }
1406
+
1407
+    /**
1408
+     * @return \OCP\IHelper
1409
+     */
1410
+    public function getHelper() {
1411
+        return $this->query('AppHelper');
1412
+    }
1413
+
1414
+    /**
1415
+     * @return AppFetcher
1416
+     */
1417
+    public function getAppFetcher() {
1418
+        return $this->query(AppFetcher::class);
1419
+    }
1420
+
1421
+    /**
1422
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1423
+     * getMemCacheFactory() instead.
1424
+     *
1425
+     * @return \OCP\ICache
1426
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1427
+     */
1428
+    public function getCache() {
1429
+        return $this->query('UserCache');
1430
+    }
1431
+
1432
+    /**
1433
+     * Returns an \OCP\CacheFactory instance
1434
+     *
1435
+     * @return \OCP\ICacheFactory
1436
+     */
1437
+    public function getMemCacheFactory() {
1438
+        return $this->query('MemCacheFactory');
1439
+    }
1440
+
1441
+    /**
1442
+     * Returns an \OC\RedisFactory instance
1443
+     *
1444
+     * @return \OC\RedisFactory
1445
+     */
1446
+    public function getGetRedisFactory() {
1447
+        return $this->query('RedisFactory');
1448
+    }
1449
+
1450
+
1451
+    /**
1452
+     * Returns the current session
1453
+     *
1454
+     * @return \OCP\IDBConnection
1455
+     */
1456
+    public function getDatabaseConnection() {
1457
+        return $this->query('DatabaseConnection');
1458
+    }
1459
+
1460
+    /**
1461
+     * Returns the activity manager
1462
+     *
1463
+     * @return \OCP\Activity\IManager
1464
+     */
1465
+    public function getActivityManager() {
1466
+        return $this->query('ActivityManager');
1467
+    }
1468
+
1469
+    /**
1470
+     * Returns an job list for controlling background jobs
1471
+     *
1472
+     * @return \OCP\BackgroundJob\IJobList
1473
+     */
1474
+    public function getJobList() {
1475
+        return $this->query('JobList');
1476
+    }
1477
+
1478
+    /**
1479
+     * Returns a logger instance
1480
+     *
1481
+     * @return \OCP\ILogger
1482
+     */
1483
+    public function getLogger() {
1484
+        return $this->query('Logger');
1485
+    }
1486
+
1487
+    /**
1488
+     * Returns a router for generating and matching urls
1489
+     *
1490
+     * @return \OCP\Route\IRouter
1491
+     */
1492
+    public function getRouter() {
1493
+        return $this->query('Router');
1494
+    }
1495
+
1496
+    /**
1497
+     * Returns a search instance
1498
+     *
1499
+     * @return \OCP\ISearch
1500
+     */
1501
+    public function getSearch() {
1502
+        return $this->query('Search');
1503
+    }
1504
+
1505
+    /**
1506
+     * Returns a SecureRandom instance
1507
+     *
1508
+     * @return \OCP\Security\ISecureRandom
1509
+     */
1510
+    public function getSecureRandom() {
1511
+        return $this->query('SecureRandom');
1512
+    }
1513
+
1514
+    /**
1515
+     * Returns a Crypto instance
1516
+     *
1517
+     * @return \OCP\Security\ICrypto
1518
+     */
1519
+    public function getCrypto() {
1520
+        return $this->query('Crypto');
1521
+    }
1522
+
1523
+    /**
1524
+     * Returns a Hasher instance
1525
+     *
1526
+     * @return \OCP\Security\IHasher
1527
+     */
1528
+    public function getHasher() {
1529
+        return $this->query('Hasher');
1530
+    }
1531
+
1532
+    /**
1533
+     * Returns a CredentialsManager instance
1534
+     *
1535
+     * @return \OCP\Security\ICredentialsManager
1536
+     */
1537
+    public function getCredentialsManager() {
1538
+        return $this->query('CredentialsManager');
1539
+    }
1540
+
1541
+    /**
1542
+     * Returns an instance of the HTTP helper class
1543
+     *
1544
+     * @deprecated Use getHTTPClientService()
1545
+     * @return \OC\HTTPHelper
1546
+     */
1547
+    public function getHTTPHelper() {
1548
+        return $this->query('HTTPHelper');
1549
+    }
1550
+
1551
+    /**
1552
+     * Get the certificate manager for the user
1553
+     *
1554
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1555
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1556
+     */
1557
+    public function getCertificateManager($userId = '') {
1558
+        if ($userId === '') {
1559
+            $userSession = $this->getUserSession();
1560
+            $user = $userSession->getUser();
1561
+            if (is_null($user)) {
1562
+                return null;
1563
+            }
1564
+            $userId = $user->getUID();
1565
+        }
1566
+        return new CertificateManager(
1567
+            $userId,
1568
+            new View(),
1569
+            $this->getConfig(),
1570
+            $this->getLogger(),
1571
+            $this->getSecureRandom()
1572
+        );
1573
+    }
1574
+
1575
+    /**
1576
+     * Returns an instance of the HTTP client service
1577
+     *
1578
+     * @return \OCP\Http\Client\IClientService
1579
+     */
1580
+    public function getHTTPClientService() {
1581
+        return $this->query('HttpClientService');
1582
+    }
1583
+
1584
+    /**
1585
+     * Create a new event source
1586
+     *
1587
+     * @return \OCP\IEventSource
1588
+     */
1589
+    public function createEventSource() {
1590
+        return new \OC_EventSource();
1591
+    }
1592
+
1593
+    /**
1594
+     * Get the active event logger
1595
+     *
1596
+     * The returned logger only logs data when debug mode is enabled
1597
+     *
1598
+     * @return \OCP\Diagnostics\IEventLogger
1599
+     */
1600
+    public function getEventLogger() {
1601
+        return $this->query('EventLogger');
1602
+    }
1603
+
1604
+    /**
1605
+     * Get the active query logger
1606
+     *
1607
+     * The returned logger only logs data when debug mode is enabled
1608
+     *
1609
+     * @return \OCP\Diagnostics\IQueryLogger
1610
+     */
1611
+    public function getQueryLogger() {
1612
+        return $this->query('QueryLogger');
1613
+    }
1614
+
1615
+    /**
1616
+     * Get the manager for temporary files and folders
1617
+     *
1618
+     * @return \OCP\ITempManager
1619
+     */
1620
+    public function getTempManager() {
1621
+        return $this->query('TempManager');
1622
+    }
1623
+
1624
+    /**
1625
+     * Get the app manager
1626
+     *
1627
+     * @return \OCP\App\IAppManager
1628
+     */
1629
+    public function getAppManager() {
1630
+        return $this->query('AppManager');
1631
+    }
1632
+
1633
+    /**
1634
+     * Creates a new mailer
1635
+     *
1636
+     * @return \OCP\Mail\IMailer
1637
+     */
1638
+    public function getMailer() {
1639
+        return $this->query('Mailer');
1640
+    }
1641
+
1642
+    /**
1643
+     * Get the webroot
1644
+     *
1645
+     * @return string
1646
+     */
1647
+    public function getWebRoot() {
1648
+        return $this->webRoot;
1649
+    }
1650
+
1651
+    /**
1652
+     * @return \OC\OCSClient
1653
+     */
1654
+    public function getOcsClient() {
1655
+        return $this->query('OcsClient');
1656
+    }
1657
+
1658
+    /**
1659
+     * @return \OCP\IDateTimeZone
1660
+     */
1661
+    public function getDateTimeZone() {
1662
+        return $this->query('DateTimeZone');
1663
+    }
1664
+
1665
+    /**
1666
+     * @return \OCP\IDateTimeFormatter
1667
+     */
1668
+    public function getDateTimeFormatter() {
1669
+        return $this->query('DateTimeFormatter');
1670
+    }
1671
+
1672
+    /**
1673
+     * @return \OCP\Files\Config\IMountProviderCollection
1674
+     */
1675
+    public function getMountProviderCollection() {
1676
+        return $this->query('MountConfigManager');
1677
+    }
1678
+
1679
+    /**
1680
+     * Get the IniWrapper
1681
+     *
1682
+     * @return IniGetWrapper
1683
+     */
1684
+    public function getIniWrapper() {
1685
+        return $this->query('IniWrapper');
1686
+    }
1687
+
1688
+    /**
1689
+     * @return \OCP\Command\IBus
1690
+     */
1691
+    public function getCommandBus() {
1692
+        return $this->query('AsyncCommandBus');
1693
+    }
1694
+
1695
+    /**
1696
+     * Get the trusted domain helper
1697
+     *
1698
+     * @return TrustedDomainHelper
1699
+     */
1700
+    public function getTrustedDomainHelper() {
1701
+        return $this->query('TrustedDomainHelper');
1702
+    }
1703
+
1704
+    /**
1705
+     * Get the locking provider
1706
+     *
1707
+     * @return \OCP\Lock\ILockingProvider
1708
+     * @since 8.1.0
1709
+     */
1710
+    public function getLockingProvider() {
1711
+        return $this->query('LockingProvider');
1712
+    }
1713
+
1714
+    /**
1715
+     * @return \OCP\Files\Mount\IMountManager
1716
+     **/
1717
+    function getMountManager() {
1718
+        return $this->query('MountManager');
1719
+    }
1720
+
1721
+    /** @return \OCP\Files\Config\IUserMountCache */
1722
+    function getUserMountCache() {
1723
+        return $this->query('UserMountCache');
1724
+    }
1725
+
1726
+    /**
1727
+     * Get the MimeTypeDetector
1728
+     *
1729
+     * @return \OCP\Files\IMimeTypeDetector
1730
+     */
1731
+    public function getMimeTypeDetector() {
1732
+        return $this->query('MimeTypeDetector');
1733
+    }
1734
+
1735
+    /**
1736
+     * Get the MimeTypeLoader
1737
+     *
1738
+     * @return \OCP\Files\IMimeTypeLoader
1739
+     */
1740
+    public function getMimeTypeLoader() {
1741
+        return $this->query('MimeTypeLoader');
1742
+    }
1743
+
1744
+    /**
1745
+     * Get the manager of all the capabilities
1746
+     *
1747
+     * @return \OC\CapabilitiesManager
1748
+     */
1749
+    public function getCapabilitiesManager() {
1750
+        return $this->query('CapabilitiesManager');
1751
+    }
1752
+
1753
+    /**
1754
+     * Get the EventDispatcher
1755
+     *
1756
+     * @return EventDispatcherInterface
1757
+     * @since 8.2.0
1758
+     */
1759
+    public function getEventDispatcher() {
1760
+        return $this->query('EventDispatcher');
1761
+    }
1762
+
1763
+    /**
1764
+     * Get the Notification Manager
1765
+     *
1766
+     * @return \OCP\Notification\IManager
1767
+     * @since 8.2.0
1768
+     */
1769
+    public function getNotificationManager() {
1770
+        return $this->query('NotificationManager');
1771
+    }
1772
+
1773
+    /**
1774
+     * @return \OCP\Comments\ICommentsManager
1775
+     */
1776
+    public function getCommentsManager() {
1777
+        return $this->query('CommentsManager');
1778
+    }
1779
+
1780
+    /**
1781
+     * @return \OCA\Theming\ThemingDefaults
1782
+     */
1783
+    public function getThemingDefaults() {
1784
+        return $this->query('ThemingDefaults');
1785
+    }
1786
+
1787
+    /**
1788
+     * @return \OC\IntegrityCheck\Checker
1789
+     */
1790
+    public function getIntegrityCodeChecker() {
1791
+        return $this->query('IntegrityCodeChecker');
1792
+    }
1793
+
1794
+    /**
1795
+     * @return \OC\Session\CryptoWrapper
1796
+     */
1797
+    public function getSessionCryptoWrapper() {
1798
+        return $this->query('CryptoWrapper');
1799
+    }
1800
+
1801
+    /**
1802
+     * @return CsrfTokenManager
1803
+     */
1804
+    public function getCsrfTokenManager() {
1805
+        return $this->query('CsrfTokenManager');
1806
+    }
1807
+
1808
+    /**
1809
+     * @return Throttler
1810
+     */
1811
+    public function getBruteForceThrottler() {
1812
+        return $this->query('Throttler');
1813
+    }
1814
+
1815
+    /**
1816
+     * @return IContentSecurityPolicyManager
1817
+     */
1818
+    public function getContentSecurityPolicyManager() {
1819
+        return $this->query('ContentSecurityPolicyManager');
1820
+    }
1821
+
1822
+    /**
1823
+     * @return ContentSecurityPolicyNonceManager
1824
+     */
1825
+    public function getContentSecurityPolicyNonceManager() {
1826
+        return $this->query('ContentSecurityPolicyNonceManager');
1827
+    }
1828
+
1829
+    /**
1830
+     * Not a public API as of 8.2, wait for 9.0
1831
+     *
1832
+     * @return \OCA\Files_External\Service\BackendService
1833
+     */
1834
+    public function getStoragesBackendService() {
1835
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1836
+    }
1837
+
1838
+    /**
1839
+     * Not a public API as of 8.2, wait for 9.0
1840
+     *
1841
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1842
+     */
1843
+    public function getGlobalStoragesService() {
1844
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1845
+    }
1846
+
1847
+    /**
1848
+     * Not a public API as of 8.2, wait for 9.0
1849
+     *
1850
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1851
+     */
1852
+    public function getUserGlobalStoragesService() {
1853
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1854
+    }
1855
+
1856
+    /**
1857
+     * Not a public API as of 8.2, wait for 9.0
1858
+     *
1859
+     * @return \OCA\Files_External\Service\UserStoragesService
1860
+     */
1861
+    public function getUserStoragesService() {
1862
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1863
+    }
1864
+
1865
+    /**
1866
+     * @return \OCP\Share\IManager
1867
+     */
1868
+    public function getShareManager() {
1869
+        return $this->query('ShareManager');
1870
+    }
1871
+
1872
+    /**
1873
+     * @return \OCP\Collaboration\Collaborators\ISearch
1874
+     */
1875
+    public function getCollaboratorSearch() {
1876
+        return $this->query('CollaboratorSearch');
1877
+    }
1878
+
1879
+    /**
1880
+     * @return \OCP\Collaboration\AutoComplete\IManager
1881
+     */
1882
+    public function getAutoCompleteManager(){
1883
+        return $this->query(IManager::class);
1884
+    }
1885
+
1886
+    /**
1887
+     * Returns the LDAP Provider
1888
+     *
1889
+     * @return \OCP\LDAP\ILDAPProvider
1890
+     */
1891
+    public function getLDAPProvider() {
1892
+        return $this->query('LDAPProvider');
1893
+    }
1894
+
1895
+    /**
1896
+     * @return \OCP\Settings\IManager
1897
+     */
1898
+    public function getSettingsManager() {
1899
+        return $this->query('SettingsManager');
1900
+    }
1901
+
1902
+    /**
1903
+     * @return \OCP\Files\IAppData
1904
+     */
1905
+    public function getAppDataDir($app) {
1906
+        /** @var \OC\Files\AppData\Factory $factory */
1907
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1908
+        return $factory->get($app);
1909
+    }
1910
+
1911
+    /**
1912
+     * @return \OCP\Lockdown\ILockdownManager
1913
+     */
1914
+    public function getLockdownManager() {
1915
+        return $this->query('LockdownManager');
1916
+    }
1917
+
1918
+    /**
1919
+     * @return \OCP\Federation\ICloudIdManager
1920
+     */
1921
+    public function getCloudIdManager() {
1922
+        return $this->query(ICloudIdManager::class);
1923
+    }
1924
+
1925
+    /**
1926
+     * @return \OCP\Remote\Api\IApiFactory
1927
+     */
1928
+    public function getRemoteApiFactory() {
1929
+        return $this->query(IApiFactory::class);
1930
+    }
1931
+
1932
+    /**
1933
+     * @return \OCP\Remote\IInstanceFactory
1934
+     */
1935
+    public function getRemoteInstanceFactory() {
1936
+        return $this->query(IInstanceFactory::class);
1937
+    }
1938 1938
 }
Please login to merge, or discard this patch.
Spacing   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 		parent::__construct();
157 157
 		$this->webRoot = $webRoot;
158 158
 
159
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
159
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
160 160
 			return $c;
161 161
 		});
162 162
 
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
170 170
 
171 171
 
172
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
172
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
173 173
 			return new PreviewManager(
174 174
 				$c->getConfig(),
175 175
 				$c->getRootFolder(),
@@ -180,13 +180,13 @@  discard block
 block discarded – undo
180 180
 		});
181 181
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
182 182
 
183
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
183
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
184 184
 			return new \OC\Preview\Watcher(
185 185
 				$c->getAppDataDir('preview')
186 186
 			);
187 187
 		});
188 188
 
189
-		$this->registerService('EncryptionManager', function (Server $c) {
189
+		$this->registerService('EncryptionManager', function(Server $c) {
190 190
 			$view = new View();
191 191
 			$util = new Encryption\Util(
192 192
 				$view,
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 			);
205 205
 		});
206 206
 
207
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
207
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
208 208
 			$util = new Encryption\Util(
209 209
 				new View(),
210 210
 				$c->getUserManager(),
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 			);
219 219
 		});
220 220
 
221
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
221
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
222 222
 			$view = new View();
223 223
 			$util = new Encryption\Util(
224 224
 				$view,
@@ -229,32 +229,32 @@  discard block
 block discarded – undo
229 229
 
230 230
 			return new Encryption\Keys\Storage($view, $util);
231 231
 		});
232
-		$this->registerService('TagMapper', function (Server $c) {
232
+		$this->registerService('TagMapper', function(Server $c) {
233 233
 			return new TagMapper($c->getDatabaseConnection());
234 234
 		});
235 235
 
236
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
236
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
237 237
 			$tagMapper = $c->query('TagMapper');
238 238
 			return new TagManager($tagMapper, $c->getUserSession());
239 239
 		});
240 240
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
241 241
 
242
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
242
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
243 243
 			$config = $c->getConfig();
244 244
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
245 245
 			/** @var \OC\SystemTag\ManagerFactory $factory */
246 246
 			$factory = new $factoryClass($this);
247 247
 			return $factory;
248 248
 		});
249
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
249
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
250 250
 			return $c->query('SystemTagManagerFactory')->getManager();
251 251
 		});
252 252
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
253 253
 
254
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
254
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
255 255
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
256 256
 		});
257
-		$this->registerService('RootFolder', function (Server $c) {
257
+		$this->registerService('RootFolder', function(Server $c) {
258 258
 			$manager = \OC\Files\Filesystem::getMountManager(null);
259 259
 			$view = new View();
260 260
 			$root = new Root(
@@ -275,37 +275,37 @@  discard block
 block discarded – undo
275 275
 		});
276 276
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
277 277
 
278
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
279
-			return new LazyRoot(function () use ($c) {
278
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
279
+			return new LazyRoot(function() use ($c) {
280 280
 				return $c->query('RootFolder');
281 281
 			});
282 282
 		});
283 283
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
284 284
 
285
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
285
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
286 286
 			$config = $c->getConfig();
287 287
 			return new \OC\User\Manager($config);
288 288
 		});
289 289
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
290 290
 
291
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
291
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
292 292
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
293
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
294 294
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295 295
 			});
296
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
296
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
297 297
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298 298
 			});
299
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
299
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
300 300
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301 301
 			});
302
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
302
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
303 303
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304 304
 			});
305
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
305
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
306 306
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307 307
 			});
308
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
308
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
309 309
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310 310
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311 311
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 		});
315 315
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316 316
 
317
-		$this->registerService(Store::class, function (Server $c) {
317
+		$this->registerService(Store::class, function(Server $c) {
318 318
 			$session = $c->getSession();
319 319
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320 320
 				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
@@ -325,11 +325,11 @@  discard block
 block discarded – undo
325 325
 			return new Store($session, $logger, $tokenProvider);
326 326
 		});
327 327
 		$this->registerAlias(IStore::class, Store::class);
328
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
328
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
329 329
 			$dbConnection = $c->getDatabaseConnection();
330 330
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
331 331
 		});
332
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
332
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
333 333
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334 334
 			$crypto = $c->getCrypto();
335 335
 			$config = $c->getConfig();
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 		});
340 340
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341 341
 
342
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
342
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
343 343
 			$manager = $c->getUserManager();
344 344
 			$session = new \OC\Session\Memory('');
345 345
 			$timeFactory = new TimeFactory();
@@ -354,45 +354,45 @@  discard block
 block discarded – undo
354 354
 			$dispatcher = $c->getEventDispatcher();
355 355
 
356 356
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
357
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
357
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
358 358
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
359 359
 			});
360
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
360
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
361 361
 				/** @var $user \OC\User\User */
362 362
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
363 363
 			});
364
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
364
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($dispatcher) {
365 365
 				/** @var $user \OC\User\User */
366 366
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
367 367
 				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
368 368
 			});
369
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
369
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
370 370
 				/** @var $user \OC\User\User */
371 371
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
372 372
 			});
373
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
373
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
374 374
 				/** @var $user \OC\User\User */
375 375
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
376 376
 			});
377
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
377
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
378 378
 				/** @var $user \OC\User\User */
379 379
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
380 380
 			});
381
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
381
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
382 382
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
383 383
 			});
384
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
384
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
385 385
 				/** @var $user \OC\User\User */
386 386
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
387 387
 			});
388
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
388
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
389 389
 				/** @var $user \OC\User\User */
390 390
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
391 391
 			});
392
-			$userSession->listen('\OC\User', 'logout', function () {
392
+			$userSession->listen('\OC\User', 'logout', function() {
393 393
 				\OC_Hook::emit('OC_User', 'logout', array());
394 394
 			});
395
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
395
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
396 396
 				/** @var $user \OC\User\User */
397 397
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
398 398
 			});
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 		});
401 401
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
402 402
 
403
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
403
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
404 404
 			return new \OC\Authentication\TwoFactorAuth\Manager(
405 405
 				$c->getAppManager(),
406 406
 				$c->getSession(),
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
416 416
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
417 417
 
418
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
418
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
419 419
 			return new \OC\AllConfig(
420 420
 				$c->getSystemConfig()
421 421
 			);
@@ -423,17 +423,17 @@  discard block
 block discarded – undo
423 423
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
424 424
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
425 425
 
426
-		$this->registerService('SystemConfig', function ($c) use ($config) {
426
+		$this->registerService('SystemConfig', function($c) use ($config) {
427 427
 			return new \OC\SystemConfig($config);
428 428
 		});
429 429
 
430
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
430
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
431 431
 			return new \OC\AppConfig($c->getDatabaseConnection());
432 432
 		});
433 433
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
434 434
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
435 435
 
436
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
436
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
437 437
 			return new \OC\L10N\Factory(
438 438
 				$c->getConfig(),
439 439
 				$c->getRequest(),
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
 		});
444 444
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
445 445
 
446
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
446
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
447 447
 			$config = $c->getConfig();
448 448
 			$cacheFactory = $c->getMemCacheFactory();
449 449
 			$request = $c->getRequest();
@@ -455,18 +455,18 @@  discard block
 block discarded – undo
455 455
 		});
456 456
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
457 457
 
458
-		$this->registerService('AppHelper', function ($c) {
458
+		$this->registerService('AppHelper', function($c) {
459 459
 			return new \OC\AppHelper();
460 460
 		});
461 461
 		$this->registerAlias('AppFetcher', AppFetcher::class);
462 462
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
463 463
 
464
-		$this->registerService(\OCP\ICache::class, function ($c) {
464
+		$this->registerService(\OCP\ICache::class, function($c) {
465 465
 			return new Cache\File();
466 466
 		});
467 467
 		$this->registerAlias('UserCache', \OCP\ICache::class);
468 468
 
469
-		$this->registerService(Factory::class, function (Server $c) {
469
+		$this->registerService(Factory::class, function(Server $c) {
470 470
 
471 471
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
472 472
 				'\\OC\\Memcache\\ArrayCache',
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
 				$version = implode(',', $v);
484 484
 				$instanceId = \OC_Util::getInstanceId();
485 485
 				$path = \OC::$SERVERROOT;
486
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
486
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.$urlGenerator->getBaseUrl());
487 487
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
488 488
 					$config->getSystemValue('memcache.local', null),
489 489
 					$config->getSystemValue('memcache.distributed', null),
@@ -496,12 +496,12 @@  discard block
 block discarded – undo
496 496
 		$this->registerAlias('MemCacheFactory', Factory::class);
497 497
 		$this->registerAlias(ICacheFactory::class, Factory::class);
498 498
 
499
-		$this->registerService('RedisFactory', function (Server $c) {
499
+		$this->registerService('RedisFactory', function(Server $c) {
500 500
 			$systemConfig = $c->getSystemConfig();
501 501
 			return new RedisFactory($systemConfig);
502 502
 		});
503 503
 
504
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
504
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
505 505
 			return new \OC\Activity\Manager(
506 506
 				$c->getRequest(),
507 507
 				$c->getUserSession(),
@@ -511,14 +511,14 @@  discard block
 block discarded – undo
511 511
 		});
512 512
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
513 513
 
514
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
514
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
515 515
 			return new \OC\Activity\EventMerger(
516 516
 				$c->getL10N('lib')
517 517
 			);
518 518
 		});
519 519
 		$this->registerAlias(IValidator::class, Validator::class);
520 520
 
521
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
521
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
522 522
 			return new AvatarManager(
523 523
 				$c->getUserManager(),
524 524
 				$c->getAppDataDir('avatar'),
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 
532 532
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
533 533
 
534
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
534
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
535 535
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
536 536
 			$logger = Log::getLogClass($logType);
537 537
 			call_user_func(array($logger, 'init'));
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 		});
543 543
 		$this->registerAlias('Logger', \OCP\ILogger::class);
544 544
 
545
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
545
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
546 546
 			$config = $c->getConfig();
547 547
 			return new \OC\BackgroundJob\JobList(
548 548
 				$c->getDatabaseConnection(),
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
 		});
553 553
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
554 554
 
555
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
555
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
556 556
 			$cacheFactory = $c->getMemCacheFactory();
557 557
 			$logger = $c->getLogger();
558 558
 			if ($cacheFactory->isAvailableLowLatency()) {
@@ -564,12 +564,12 @@  discard block
 block discarded – undo
564 564
 		});
565 565
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
566 566
 
567
-		$this->registerService(\OCP\ISearch::class, function ($c) {
567
+		$this->registerService(\OCP\ISearch::class, function($c) {
568 568
 			return new Search();
569 569
 		});
570 570
 		$this->registerAlias('Search', \OCP\ISearch::class);
571 571
 
572
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
572
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
573 573
 			return new \OC\Security\RateLimiting\Limiter(
574 574
 				$this->getUserSession(),
575 575
 				$this->getRequest(),
@@ -577,34 +577,34 @@  discard block
 block discarded – undo
577 577
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
578 578
 			);
579 579
 		});
580
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
580
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
581 581
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
582 582
 				$this->getMemCacheFactory(),
583 583
 				new \OC\AppFramework\Utility\TimeFactory()
584 584
 			);
585 585
 		});
586 586
 
587
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
587
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
588 588
 			return new SecureRandom();
589 589
 		});
590 590
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
591 591
 
592
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
592
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
593 593
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
594 594
 		});
595 595
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
596 596
 
597
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
597
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
598 598
 			return new Hasher($c->getConfig());
599 599
 		});
600 600
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
601 601
 
602
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
602
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
603 603
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
604 604
 		});
605 605
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
606 606
 
607
-		$this->registerService(IDBConnection::class, function (Server $c) {
607
+		$this->registerService(IDBConnection::class, function(Server $c) {
608 608
 			$systemConfig = $c->getSystemConfig();
609 609
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
610 610
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 		});
619 619
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
620 620
 
621
-		$this->registerService('HTTPHelper', function (Server $c) {
621
+		$this->registerService('HTTPHelper', function(Server $c) {
622 622
 			$config = $c->getConfig();
623 623
 			return new HTTPHelper(
624 624
 				$config,
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
 			);
627 627
 		});
628 628
 
629
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
629
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
630 630
 			$user = \OC_User::getUser();
631 631
 			$uid = $user ? $user : null;
632 632
 			return new ClientService(
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 			);
642 642
 		});
643 643
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
644
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
644
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
645 645
 			$eventLogger = new EventLogger();
646 646
 			if ($c->getSystemConfig()->getValue('debug', false)) {
647 647
 				// In debug mode, module is being activated by default
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
 		});
652 652
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
653 653
 
654
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
654
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
655 655
 			$queryLogger = new QueryLogger();
656 656
 			if ($c->getSystemConfig()->getValue('debug', false)) {
657 657
 				// In debug mode, module is being activated by default
@@ -661,7 +661,7 @@  discard block
 block discarded – undo
661 661
 		});
662 662
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
663 663
 
664
-		$this->registerService(TempManager::class, function (Server $c) {
664
+		$this->registerService(TempManager::class, function(Server $c) {
665 665
 			return new TempManager(
666 666
 				$c->getLogger(),
667 667
 				$c->getConfig()
@@ -670,7 +670,7 @@  discard block
 block discarded – undo
670 670
 		$this->registerAlias('TempManager', TempManager::class);
671 671
 		$this->registerAlias(ITempManager::class, TempManager::class);
672 672
 
673
-		$this->registerService(AppManager::class, function (Server $c) {
673
+		$this->registerService(AppManager::class, function(Server $c) {
674 674
 			return new \OC\App\AppManager(
675 675
 				$c->getUserSession(),
676 676
 				$c->getAppConfig(),
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 		$this->registerAlias('AppManager', AppManager::class);
683 683
 		$this->registerAlias(IAppManager::class, AppManager::class);
684 684
 
685
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
685
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
686 686
 			return new DateTimeZone(
687 687
 				$c->getConfig(),
688 688
 				$c->getSession()
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 		});
691 691
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
692 692
 
693
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
693
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
694 694
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
695 695
 
696 696
 			return new DateTimeFormatter(
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
 		});
701 701
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
702 702
 
703
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
703
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
704 704
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
705 705
 			$listener = new UserMountCacheListener($mountCache);
706 706
 			$listener->listen($c->getUserManager());
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
 		});
709 709
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
710 710
 
711
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
711
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
712 712
 			$loader = \OC\Files\Filesystem::getLoader();
713 713
 			$mountCache = $c->query('UserMountCache');
714 714
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -724,10 +724,10 @@  discard block
 block discarded – undo
724 724
 		});
725 725
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
726 726
 
727
-		$this->registerService('IniWrapper', function ($c) {
727
+		$this->registerService('IniWrapper', function($c) {
728 728
 			return new IniGetWrapper();
729 729
 		});
730
-		$this->registerService('AsyncCommandBus', function (Server $c) {
730
+		$this->registerService('AsyncCommandBus', function(Server $c) {
731 731
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
732 732
 			if ($busClass) {
733 733
 				list($app, $class) = explode('::', $busClass, 2);
@@ -742,10 +742,10 @@  discard block
 block discarded – undo
742 742
 				return new CronBus($jobList);
743 743
 			}
744 744
 		});
745
-		$this->registerService('TrustedDomainHelper', function ($c) {
745
+		$this->registerService('TrustedDomainHelper', function($c) {
746 746
 			return new TrustedDomainHelper($this->getConfig());
747 747
 		});
748
-		$this->registerService('Throttler', function (Server $c) {
748
+		$this->registerService('Throttler', function(Server $c) {
749 749
 			return new Throttler(
750 750
 				$c->getDatabaseConnection(),
751 751
 				new TimeFactory(),
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
 				$c->getConfig()
754 754
 			);
755 755
 		});
756
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
756
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
757 757
 			// IConfig and IAppManager requires a working database. This code
758 758
 			// might however be called when ownCloud is not yet setup.
759 759
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
 				$c->getTempManager()
775 775
 			);
776 776
 		});
777
-		$this->registerService(\OCP\IRequest::class, function ($c) {
777
+		$this->registerService(\OCP\IRequest::class, function($c) {
778 778
 			if (isset($this['urlParams'])) {
779 779
 				$urlParams = $this['urlParams'];
780 780
 			} else {
@@ -810,7 +810,7 @@  discard block
 block discarded – undo
810 810
 		});
811 811
 		$this->registerAlias('Request', \OCP\IRequest::class);
812 812
 
813
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
813
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
814 814
 			return new Mailer(
815 815
 				$c->getConfig(),
816 816
 				$c->getLogger(),
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
 		});
822 822
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
823 823
 
824
-		$this->registerService('LDAPProvider', function (Server $c) {
824
+		$this->registerService('LDAPProvider', function(Server $c) {
825 825
 			$config = $c->getConfig();
826 826
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
827 827
 			if (is_null($factoryClass)) {
@@ -831,7 +831,7 @@  discard block
 block discarded – undo
831 831
 			$factory = new $factoryClass($this);
832 832
 			return $factory->getLDAPProvider();
833 833
 		});
834
-		$this->registerService(ILockingProvider::class, function (Server $c) {
834
+		$this->registerService(ILockingProvider::class, function(Server $c) {
835 835
 			$ini = $c->getIniWrapper();
836 836
 			$config = $c->getConfig();
837 837
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -848,49 +848,49 @@  discard block
 block discarded – undo
848 848
 		});
849 849
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
850 850
 
851
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
851
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
852 852
 			return new \OC\Files\Mount\Manager();
853 853
 		});
854 854
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
855 855
 
856
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
856
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
857 857
 			return new \OC\Files\Type\Detection(
858 858
 				$c->getURLGenerator(),
859 859
 				\OC::$configDir,
860
-				\OC::$SERVERROOT . '/resources/config/'
860
+				\OC::$SERVERROOT.'/resources/config/'
861 861
 			);
862 862
 		});
863 863
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
864 864
 
865
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
865
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
866 866
 			return new \OC\Files\Type\Loader(
867 867
 				$c->getDatabaseConnection()
868 868
 			);
869 869
 		});
870 870
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
871
-		$this->registerService(BundleFetcher::class, function () {
871
+		$this->registerService(BundleFetcher::class, function() {
872 872
 			return new BundleFetcher($this->getL10N('lib'));
873 873
 		});
874
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
874
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
875 875
 			return new Manager(
876 876
 				$c->query(IValidator::class)
877 877
 			);
878 878
 		});
879 879
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
880 880
 
881
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
881
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
882 882
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
883
-			$manager->registerCapability(function () use ($c) {
883
+			$manager->registerCapability(function() use ($c) {
884 884
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
885 885
 			});
886
-			$manager->registerCapability(function () use ($c) {
886
+			$manager->registerCapability(function() use ($c) {
887 887
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
888 888
 			});
889 889
 			return $manager;
890 890
 		});
891 891
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
892 892
 
893
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
893
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
894 894
 			$config = $c->getConfig();
895 895
 			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
896 896
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -899,7 +899,7 @@  discard block
 block discarded – undo
899 899
 		});
900 900
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
901 901
 
902
-		$this->registerService('ThemingDefaults', function (Server $c) {
902
+		$this->registerService('ThemingDefaults', function(Server $c) {
903 903
 			/*
904 904
 			 * Dark magic for autoloader.
905 905
 			 * If we do a class_exists it will try to load the class which will
@@ -926,7 +926,7 @@  discard block
 block discarded – undo
926 926
 			}
927 927
 			return new \OC_Defaults();
928 928
 		});
929
-		$this->registerService(SCSSCacher::class, function (Server $c) {
929
+		$this->registerService(SCSSCacher::class, function(Server $c) {
930 930
 			/** @var Factory $cacheFactory */
931 931
 			$cacheFactory = $c->query(Factory::class);
932 932
 			return new SCSSCacher(
@@ -939,13 +939,13 @@  discard block
 block discarded – undo
939 939
 				$cacheFactory->create('SCSS')
940 940
 			);
941 941
 		});
942
-		$this->registerService(EventDispatcher::class, function () {
942
+		$this->registerService(EventDispatcher::class, function() {
943 943
 			return new EventDispatcher();
944 944
 		});
945 945
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
946 946
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
947 947
 
948
-		$this->registerService('CryptoWrapper', function (Server $c) {
948
+		$this->registerService('CryptoWrapper', function(Server $c) {
949 949
 			// FIXME: Instantiiated here due to cyclic dependency
950 950
 			$request = new Request(
951 951
 				[
@@ -970,7 +970,7 @@  discard block
 block discarded – undo
970 970
 				$request
971 971
 			);
972 972
 		});
973
-		$this->registerService('CsrfTokenManager', function (Server $c) {
973
+		$this->registerService('CsrfTokenManager', function(Server $c) {
974 974
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
975 975
 
976 976
 			return new CsrfTokenManager(
@@ -978,22 +978,22 @@  discard block
 block discarded – undo
978 978
 				$c->query(SessionStorage::class)
979 979
 			);
980 980
 		});
981
-		$this->registerService(SessionStorage::class, function (Server $c) {
981
+		$this->registerService(SessionStorage::class, function(Server $c) {
982 982
 			return new SessionStorage($c->getSession());
983 983
 		});
984
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
984
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
985 985
 			return new ContentSecurityPolicyManager();
986 986
 		});
987 987
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
988 988
 
989
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
989
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
990 990
 			return new ContentSecurityPolicyNonceManager(
991 991
 				$c->getCsrfTokenManager(),
992 992
 				$c->getRequest()
993 993
 			);
994 994
 		});
995 995
 
996
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
996
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
997 997
 			$config = $c->getConfig();
998 998
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
999 999
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1036,7 +1036,7 @@  discard block
 block discarded – undo
1036 1036
 
1037 1037
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1038 1038
 
1039
-		$this->registerService('SettingsManager', function (Server $c) {
1039
+		$this->registerService('SettingsManager', function(Server $c) {
1040 1040
 			$manager = new \OC\Settings\Manager(
1041 1041
 				$c->getLogger(),
1042 1042
 				$c->getDatabaseConnection(),
@@ -1056,29 +1056,29 @@  discard block
 block discarded – undo
1056 1056
 			);
1057 1057
 			return $manager;
1058 1058
 		});
1059
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1059
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1060 1060
 			return new \OC\Files\AppData\Factory(
1061 1061
 				$c->getRootFolder(),
1062 1062
 				$c->getSystemConfig()
1063 1063
 			);
1064 1064
 		});
1065 1065
 
1066
-		$this->registerService('LockdownManager', function (Server $c) {
1067
-			return new LockdownManager(function () use ($c) {
1066
+		$this->registerService('LockdownManager', function(Server $c) {
1067
+			return new LockdownManager(function() use ($c) {
1068 1068
 				return $c->getSession();
1069 1069
 			});
1070 1070
 		});
1071 1071
 
1072
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1072
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1073 1073
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1074 1074
 		});
1075 1075
 
1076
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1076
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1077 1077
 			return new CloudIdManager();
1078 1078
 		});
1079 1079
 
1080 1080
 		/* To trick DI since we don't extend the DIContainer here */
1081
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
1081
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
1082 1082
 			return new CleanPreviewsBackgroundJob(
1083 1083
 				$c->getRootFolder(),
1084 1084
 				$c->getLogger(),
@@ -1093,18 +1093,18 @@  discard block
 block discarded – undo
1093 1093
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1094 1094
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1095 1095
 
1096
-		$this->registerService(Defaults::class, function (Server $c) {
1096
+		$this->registerService(Defaults::class, function(Server $c) {
1097 1097
 			return new Defaults(
1098 1098
 				$c->getThemingDefaults()
1099 1099
 			);
1100 1100
 		});
1101 1101
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1102 1102
 
1103
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1103
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1104 1104
 			return $c->query(\OCP\IUserSession::class)->getSession();
1105 1105
 		});
1106 1106
 
1107
-		$this->registerService(IShareHelper::class, function (Server $c) {
1107
+		$this->registerService(IShareHelper::class, function(Server $c) {
1108 1108
 			return new ShareHelper(
1109 1109
 				$c->query(\OCP\Share\IManager::class)
1110 1110
 			);
@@ -1156,7 +1156,7 @@  discard block
 block discarded – undo
1156 1156
 				// no avatar to remove
1157 1157
 			} catch (\Exception $e) {
1158 1158
 				// Ignore exceptions
1159
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1159
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1160 1160
 			}
1161 1161
 		});
1162 1162
 	}
@@ -1295,7 +1295,7 @@  discard block
 block discarded – undo
1295 1295
 	 * @deprecated since 9.2.0 use IAppData
1296 1296
 	 */
1297 1297
 	public function getAppFolder() {
1298
-		$dir = '/' . \OC_App::getCurrentApp();
1298
+		$dir = '/'.\OC_App::getCurrentApp();
1299 1299
 		$root = $this->getRootFolder();
1300 1300
 		if (!$root->nodeExists($dir)) {
1301 1301
 			$folder = $root->newFolder($dir);
@@ -1879,7 +1879,7 @@  discard block
 block discarded – undo
1879 1879
 	/**
1880 1880
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1881 1881
 	 */
1882
-	public function getAutoCompleteManager(){
1882
+	public function getAutoCompleteManager() {
1883 1883
 		return $this->query(IManager::class);
1884 1884
 	}
1885 1885
 
Please login to merge, or discard this patch.
lib/private/Files/View.php 2 patches
Indentation   +2084 added lines, -2084 removed lines patch added patch discarded remove patch
@@ -80,2088 +80,2088 @@
 block discarded – undo
80 80
  * \OC\Files\Storage\Storage object
81 81
  */
82 82
 class View {
83
-	/** @var string */
84
-	private $fakeRoot = '';
85
-
86
-	/**
87
-	 * @var \OCP\Lock\ILockingProvider
88
-	 */
89
-	protected $lockingProvider;
90
-
91
-	private $lockingEnabled;
92
-
93
-	private $updaterEnabled = true;
94
-
95
-	/** @var \OC\User\Manager */
96
-	private $userManager;
97
-
98
-	/** @var \OCP\ILogger */
99
-	private $logger;
100
-
101
-	/**
102
-	 * @param string $root
103
-	 * @throws \Exception If $root contains an invalid path
104
-	 */
105
-	public function __construct($root = '') {
106
-		if (is_null($root)) {
107
-			throw new \InvalidArgumentException('Root can\'t be null');
108
-		}
109
-		if (!Filesystem::isValidPath($root)) {
110
-			throw new \Exception();
111
-		}
112
-
113
-		$this->fakeRoot = $root;
114
-		$this->lockingProvider = \OC::$server->getLockingProvider();
115
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
116
-		$this->userManager = \OC::$server->getUserManager();
117
-		$this->logger = \OC::$server->getLogger();
118
-	}
119
-
120
-	public function getAbsolutePath($path = '/') {
121
-		if ($path === null) {
122
-			return null;
123
-		}
124
-		$this->assertPathLength($path);
125
-		if ($path === '') {
126
-			$path = '/';
127
-		}
128
-		if ($path[0] !== '/') {
129
-			$path = '/' . $path;
130
-		}
131
-		return $this->fakeRoot . $path;
132
-	}
133
-
134
-	/**
135
-	 * change the root to a fake root
136
-	 *
137
-	 * @param string $fakeRoot
138
-	 * @return boolean|null
139
-	 */
140
-	public function chroot($fakeRoot) {
141
-		if (!$fakeRoot == '') {
142
-			if ($fakeRoot[0] !== '/') {
143
-				$fakeRoot = '/' . $fakeRoot;
144
-			}
145
-		}
146
-		$this->fakeRoot = $fakeRoot;
147
-	}
148
-
149
-	/**
150
-	 * get the fake root
151
-	 *
152
-	 * @return string
153
-	 */
154
-	public function getRoot() {
155
-		return $this->fakeRoot;
156
-	}
157
-
158
-	/**
159
-	 * get path relative to the root of the view
160
-	 *
161
-	 * @param string $path
162
-	 * @return string
163
-	 */
164
-	public function getRelativePath($path) {
165
-		$this->assertPathLength($path);
166
-		if ($this->fakeRoot == '') {
167
-			return $path;
168
-		}
169
-
170
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
171
-			return '/';
172
-		}
173
-
174
-		// missing slashes can cause wrong matches!
175
-		$root = rtrim($this->fakeRoot, '/') . '/';
176
-
177
-		if (strpos($path, $root) !== 0) {
178
-			return null;
179
-		} else {
180
-			$path = substr($path, strlen($this->fakeRoot));
181
-			if (strlen($path) === 0) {
182
-				return '/';
183
-			} else {
184
-				return $path;
185
-			}
186
-		}
187
-	}
188
-
189
-	/**
190
-	 * get the mountpoint of the storage object for a path
191
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
192
-	 * returned mountpoint is relative to the absolute root of the filesystem
193
-	 * and does not take the chroot into account )
194
-	 *
195
-	 * @param string $path
196
-	 * @return string
197
-	 */
198
-	public function getMountPoint($path) {
199
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
200
-	}
201
-
202
-	/**
203
-	 * get the mountpoint of the storage object for a path
204
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
205
-	 * returned mountpoint is relative to the absolute root of the filesystem
206
-	 * and does not take the chroot into account )
207
-	 *
208
-	 * @param string $path
209
-	 * @return \OCP\Files\Mount\IMountPoint
210
-	 */
211
-	public function getMount($path) {
212
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
213
-	}
214
-
215
-	/**
216
-	 * resolve a path to a storage and internal path
217
-	 *
218
-	 * @param string $path
219
-	 * @return array an array consisting of the storage and the internal path
220
-	 */
221
-	public function resolvePath($path) {
222
-		$a = $this->getAbsolutePath($path);
223
-		$p = Filesystem::normalizePath($a);
224
-		return Filesystem::resolvePath($p);
225
-	}
226
-
227
-	/**
228
-	 * return the path to a local version of the file
229
-	 * we need this because we can't know if a file is stored local or not from
230
-	 * outside the filestorage and for some purposes a local file is needed
231
-	 *
232
-	 * @param string $path
233
-	 * @return string
234
-	 */
235
-	public function getLocalFile($path) {
236
-		$parent = substr($path, 0, strrpos($path, '/'));
237
-		$path = $this->getAbsolutePath($path);
238
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
239
-		if (Filesystem::isValidPath($parent) and $storage) {
240
-			return $storage->getLocalFile($internalPath);
241
-		} else {
242
-			return null;
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * @param string $path
248
-	 * @return string
249
-	 */
250
-	public function getLocalFolder($path) {
251
-		$parent = substr($path, 0, strrpos($path, '/'));
252
-		$path = $this->getAbsolutePath($path);
253
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
254
-		if (Filesystem::isValidPath($parent) and $storage) {
255
-			return $storage->getLocalFolder($internalPath);
256
-		} else {
257
-			return null;
258
-		}
259
-	}
260
-
261
-	/**
262
-	 * the following functions operate with arguments and return values identical
263
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
264
-	 * for \OC\Files\Storage\Storage via basicOperation().
265
-	 */
266
-	public function mkdir($path) {
267
-		return $this->basicOperation('mkdir', $path, array('create', 'write'));
268
-	}
269
-
270
-	/**
271
-	 * remove mount point
272
-	 *
273
-	 * @param \OC\Files\Mount\MoveableMount $mount
274
-	 * @param string $path relative to data/
275
-	 * @return boolean
276
-	 */
277
-	protected function removeMount($mount, $path) {
278
-		if ($mount instanceof MoveableMount) {
279
-			// cut of /user/files to get the relative path to data/user/files
280
-			$pathParts = explode('/', $path, 4);
281
-			$relPath = '/' . $pathParts[3];
282
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
283
-			\OC_Hook::emit(
284
-				Filesystem::CLASSNAME, "umount",
285
-				array(Filesystem::signal_param_path => $relPath)
286
-			);
287
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
288
-			$result = $mount->removeMount();
289
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
290
-			if ($result) {
291
-				\OC_Hook::emit(
292
-					Filesystem::CLASSNAME, "post_umount",
293
-					array(Filesystem::signal_param_path => $relPath)
294
-				);
295
-			}
296
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
297
-			return $result;
298
-		} else {
299
-			// do not allow deleting the storage's root / the mount point
300
-			// because for some storages it might delete the whole contents
301
-			// but isn't supposed to work that way
302
-			return false;
303
-		}
304
-	}
305
-
306
-	public function disableCacheUpdate() {
307
-		$this->updaterEnabled = false;
308
-	}
309
-
310
-	public function enableCacheUpdate() {
311
-		$this->updaterEnabled = true;
312
-	}
313
-
314
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
315
-		if ($this->updaterEnabled) {
316
-			if (is_null($time)) {
317
-				$time = time();
318
-			}
319
-			$storage->getUpdater()->update($internalPath, $time);
320
-		}
321
-	}
322
-
323
-	protected function removeUpdate(Storage $storage, $internalPath) {
324
-		if ($this->updaterEnabled) {
325
-			$storage->getUpdater()->remove($internalPath);
326
-		}
327
-	}
328
-
329
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
330
-		if ($this->updaterEnabled) {
331
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
332
-		}
333
-	}
334
-
335
-	/**
336
-	 * @param string $path
337
-	 * @return bool|mixed
338
-	 */
339
-	public function rmdir($path) {
340
-		$absolutePath = $this->getAbsolutePath($path);
341
-		$mount = Filesystem::getMountManager()->find($absolutePath);
342
-		if ($mount->getInternalPath($absolutePath) === '') {
343
-			return $this->removeMount($mount, $absolutePath);
344
-		}
345
-		if ($this->is_dir($path)) {
346
-			$result = $this->basicOperation('rmdir', $path, array('delete'));
347
-		} else {
348
-			$result = false;
349
-		}
350
-
351
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
352
-			$storage = $mount->getStorage();
353
-			$internalPath = $mount->getInternalPath($absolutePath);
354
-			$storage->getUpdater()->remove($internalPath);
355
-		}
356
-		return $result;
357
-	}
358
-
359
-	/**
360
-	 * @param string $path
361
-	 * @return resource
362
-	 */
363
-	public function opendir($path) {
364
-		return $this->basicOperation('opendir', $path, array('read'));
365
-	}
366
-
367
-	/**
368
-	 * @param string $path
369
-	 * @return bool|mixed
370
-	 */
371
-	public function is_dir($path) {
372
-		if ($path == '/') {
373
-			return true;
374
-		}
375
-		return $this->basicOperation('is_dir', $path);
376
-	}
377
-
378
-	/**
379
-	 * @param string $path
380
-	 * @return bool|mixed
381
-	 */
382
-	public function is_file($path) {
383
-		if ($path == '/') {
384
-			return false;
385
-		}
386
-		return $this->basicOperation('is_file', $path);
387
-	}
388
-
389
-	/**
390
-	 * @param string $path
391
-	 * @return mixed
392
-	 */
393
-	public function stat($path) {
394
-		return $this->basicOperation('stat', $path);
395
-	}
396
-
397
-	/**
398
-	 * @param string $path
399
-	 * @return mixed
400
-	 */
401
-	public function filetype($path) {
402
-		return $this->basicOperation('filetype', $path);
403
-	}
404
-
405
-	/**
406
-	 * @param string $path
407
-	 * @return mixed
408
-	 */
409
-	public function filesize($path) {
410
-		return $this->basicOperation('filesize', $path);
411
-	}
412
-
413
-	/**
414
-	 * @param string $path
415
-	 * @return bool|mixed
416
-	 * @throws \OCP\Files\InvalidPathException
417
-	 */
418
-	public function readfile($path) {
419
-		$this->assertPathLength($path);
420
-		@ob_end_clean();
421
-		$handle = $this->fopen($path, 'rb');
422
-		if ($handle) {
423
-			$chunkSize = 8192; // 8 kB chunks
424
-			while (!feof($handle)) {
425
-				echo fread($handle, $chunkSize);
426
-				flush();
427
-			}
428
-			fclose($handle);
429
-			$size = $this->filesize($path);
430
-			return $size;
431
-		}
432
-		return false;
433
-	}
434
-
435
-	/**
436
-	 * @param string $path
437
-	 * @param int $from
438
-	 * @param int $to
439
-	 * @return bool|mixed
440
-	 * @throws \OCP\Files\InvalidPathException
441
-	 * @throws \OCP\Files\UnseekableException
442
-	 */
443
-	public function readfilePart($path, $from, $to) {
444
-		$this->assertPathLength($path);
445
-		@ob_end_clean();
446
-		$handle = $this->fopen($path, 'rb');
447
-		if ($handle) {
448
-			$chunkSize = 8192; // 8 kB chunks
449
-			$startReading = true;
450
-
451
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
452
-				// forward file handle via chunked fread because fseek seem to have failed
453
-
454
-				$end = $from + 1;
455
-				while (!feof($handle) && ftell($handle) < $end) {
456
-					$len = $from - ftell($handle);
457
-					if ($len > $chunkSize) {
458
-						$len = $chunkSize;
459
-					}
460
-					$result = fread($handle, $len);
461
-
462
-					if ($result === false) {
463
-						$startReading = false;
464
-						break;
465
-					}
466
-				}
467
-			}
468
-
469
-			if ($startReading) {
470
-				$end = $to + 1;
471
-				while (!feof($handle) && ftell($handle) < $end) {
472
-					$len = $end - ftell($handle);
473
-					if ($len > $chunkSize) {
474
-						$len = $chunkSize;
475
-					}
476
-					echo fread($handle, $len);
477
-					flush();
478
-				}
479
-				$size = ftell($handle) - $from;
480
-				return $size;
481
-			}
482
-
483
-			throw new \OCP\Files\UnseekableException('fseek error');
484
-		}
485
-		return false;
486
-	}
487
-
488
-	/**
489
-	 * @param string $path
490
-	 * @return mixed
491
-	 */
492
-	public function isCreatable($path) {
493
-		return $this->basicOperation('isCreatable', $path);
494
-	}
495
-
496
-	/**
497
-	 * @param string $path
498
-	 * @return mixed
499
-	 */
500
-	public function isReadable($path) {
501
-		return $this->basicOperation('isReadable', $path);
502
-	}
503
-
504
-	/**
505
-	 * @param string $path
506
-	 * @return mixed
507
-	 */
508
-	public function isUpdatable($path) {
509
-		return $this->basicOperation('isUpdatable', $path);
510
-	}
511
-
512
-	/**
513
-	 * @param string $path
514
-	 * @return bool|mixed
515
-	 */
516
-	public function isDeletable($path) {
517
-		$absolutePath = $this->getAbsolutePath($path);
518
-		$mount = Filesystem::getMountManager()->find($absolutePath);
519
-		if ($mount->getInternalPath($absolutePath) === '') {
520
-			return $mount instanceof MoveableMount;
521
-		}
522
-		return $this->basicOperation('isDeletable', $path);
523
-	}
524
-
525
-	/**
526
-	 * @param string $path
527
-	 * @return mixed
528
-	 */
529
-	public function isSharable($path) {
530
-		return $this->basicOperation('isSharable', $path);
531
-	}
532
-
533
-	/**
534
-	 * @param string $path
535
-	 * @return bool|mixed
536
-	 */
537
-	public function file_exists($path) {
538
-		if ($path == '/') {
539
-			return true;
540
-		}
541
-		return $this->basicOperation('file_exists', $path);
542
-	}
543
-
544
-	/**
545
-	 * @param string $path
546
-	 * @return mixed
547
-	 */
548
-	public function filemtime($path) {
549
-		return $this->basicOperation('filemtime', $path);
550
-	}
551
-
552
-	/**
553
-	 * @param string $path
554
-	 * @param int|string $mtime
555
-	 * @return bool
556
-	 */
557
-	public function touch($path, $mtime = null) {
558
-		if (!is_null($mtime) and !is_numeric($mtime)) {
559
-			$mtime = strtotime($mtime);
560
-		}
561
-
562
-		$hooks = array('touch');
563
-
564
-		if (!$this->file_exists($path)) {
565
-			$hooks[] = 'create';
566
-			$hooks[] = 'write';
567
-		}
568
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
569
-		if (!$result) {
570
-			// If create file fails because of permissions on external storage like SMB folders,
571
-			// check file exists and return false if not.
572
-			if (!$this->file_exists($path)) {
573
-				return false;
574
-			}
575
-			if (is_null($mtime)) {
576
-				$mtime = time();
577
-			}
578
-			//if native touch fails, we emulate it by changing the mtime in the cache
579
-			$this->putFileInfo($path, array('mtime' => floor($mtime)));
580
-		}
581
-		return true;
582
-	}
583
-
584
-	/**
585
-	 * @param string $path
586
-	 * @return mixed
587
-	 */
588
-	public function file_get_contents($path) {
589
-		return $this->basicOperation('file_get_contents', $path, array('read'));
590
-	}
591
-
592
-	/**
593
-	 * @param bool $exists
594
-	 * @param string $path
595
-	 * @param bool $run
596
-	 */
597
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
598
-		if (!$exists) {
599
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
600
-				Filesystem::signal_param_path => $this->getHookPath($path),
601
-				Filesystem::signal_param_run => &$run,
602
-			));
603
-		} else {
604
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
605
-				Filesystem::signal_param_path => $this->getHookPath($path),
606
-				Filesystem::signal_param_run => &$run,
607
-			));
608
-		}
609
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
610
-			Filesystem::signal_param_path => $this->getHookPath($path),
611
-			Filesystem::signal_param_run => &$run,
612
-		));
613
-	}
614
-
615
-	/**
616
-	 * @param bool $exists
617
-	 * @param string $path
618
-	 */
619
-	protected function emit_file_hooks_post($exists, $path) {
620
-		if (!$exists) {
621
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
622
-				Filesystem::signal_param_path => $this->getHookPath($path),
623
-			));
624
-		} else {
625
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
626
-				Filesystem::signal_param_path => $this->getHookPath($path),
627
-			));
628
-		}
629
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
630
-			Filesystem::signal_param_path => $this->getHookPath($path),
631
-		));
632
-	}
633
-
634
-	/**
635
-	 * @param string $path
636
-	 * @param mixed $data
637
-	 * @return bool|mixed
638
-	 * @throws \Exception
639
-	 */
640
-	public function file_put_contents($path, $data) {
641
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
642
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
643
-			if (Filesystem::isValidPath($path)
644
-				and !Filesystem::isFileBlacklisted($path)
645
-			) {
646
-				$path = $this->getRelativePath($absolutePath);
647
-
648
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
649
-
650
-				$exists = $this->file_exists($path);
651
-				$run = true;
652
-				if ($this->shouldEmitHooks($path)) {
653
-					$this->emit_file_hooks_pre($exists, $path, $run);
654
-				}
655
-				if (!$run) {
656
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
657
-					return false;
658
-				}
659
-
660
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
661
-
662
-				/** @var \OC\Files\Storage\Storage $storage */
663
-				list($storage, $internalPath) = $this->resolvePath($path);
664
-				$target = $storage->fopen($internalPath, 'w');
665
-				if ($target) {
666
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
667
-					fclose($target);
668
-					fclose($data);
669
-
670
-					$this->writeUpdate($storage, $internalPath);
671
-
672
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
673
-
674
-					if ($this->shouldEmitHooks($path) && $result !== false) {
675
-						$this->emit_file_hooks_post($exists, $path);
676
-					}
677
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
678
-					return $result;
679
-				} else {
680
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
681
-					return false;
682
-				}
683
-			} else {
684
-				return false;
685
-			}
686
-		} else {
687
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
688
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
689
-		}
690
-	}
691
-
692
-	/**
693
-	 * @param string $path
694
-	 * @return bool|mixed
695
-	 */
696
-	public function unlink($path) {
697
-		if ($path === '' || $path === '/') {
698
-			// do not allow deleting the root
699
-			return false;
700
-		}
701
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
702
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
703
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
704
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
705
-			return $this->removeMount($mount, $absolutePath);
706
-		}
707
-		if ($this->is_dir($path)) {
708
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
709
-		} else {
710
-			$result = $this->basicOperation('unlink', $path, ['delete']);
711
-		}
712
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
713
-			$storage = $mount->getStorage();
714
-			$internalPath = $mount->getInternalPath($absolutePath);
715
-			$storage->getUpdater()->remove($internalPath);
716
-			return true;
717
-		} else {
718
-			return $result;
719
-		}
720
-	}
721
-
722
-	/**
723
-	 * @param string $directory
724
-	 * @return bool|mixed
725
-	 */
726
-	public function deleteAll($directory) {
727
-		return $this->rmdir($directory);
728
-	}
729
-
730
-	/**
731
-	 * Rename/move a file or folder from the source path to target path.
732
-	 *
733
-	 * @param string $path1 source path
734
-	 * @param string $path2 target path
735
-	 *
736
-	 * @return bool|mixed
737
-	 */
738
-	public function rename($path1, $path2) {
739
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
740
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
741
-		$result = false;
742
-		if (
743
-			Filesystem::isValidPath($path2)
744
-			and Filesystem::isValidPath($path1)
745
-			and !Filesystem::isFileBlacklisted($path2)
746
-		) {
747
-			$path1 = $this->getRelativePath($absolutePath1);
748
-			$path2 = $this->getRelativePath($absolutePath2);
749
-			$exists = $this->file_exists($path2);
750
-
751
-			if ($path1 == null or $path2 == null) {
752
-				return false;
753
-			}
754
-
755
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
756
-			try {
757
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
758
-
759
-				$run = true;
760
-				if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
761
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
762
-					$this->emit_file_hooks_pre($exists, $path2, $run);
763
-				} elseif ($this->shouldEmitHooks($path1)) {
764
-					\OC_Hook::emit(
765
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
766
-						array(
767
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
768
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
769
-							Filesystem::signal_param_run => &$run
770
-						)
771
-					);
772
-				}
773
-				if ($run) {
774
-					$this->verifyPath(dirname($path2), basename($path2));
775
-
776
-					$manager = Filesystem::getMountManager();
777
-					$mount1 = $this->getMount($path1);
778
-					$mount2 = $this->getMount($path2);
779
-					$storage1 = $mount1->getStorage();
780
-					$storage2 = $mount2->getStorage();
781
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
782
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
783
-
784
-					$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
785
-					try {
786
-						$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
787
-
788
-						if ($internalPath1 === '') {
789
-							if ($mount1 instanceof MoveableMount) {
790
-								if ($this->isTargetAllowed($absolutePath2)) {
791
-									/**
792
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
793
-									 */
794
-									$sourceMountPoint = $mount1->getMountPoint();
795
-									$result = $mount1->moveMount($absolutePath2);
796
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
797
-								} else {
798
-									$result = false;
799
-								}
800
-							} else {
801
-								$result = false;
802
-							}
803
-							// moving a file/folder within the same mount point
804
-						} elseif ($storage1 === $storage2) {
805
-							if ($storage1) {
806
-								$result = $storage1->rename($internalPath1, $internalPath2);
807
-							} else {
808
-								$result = false;
809
-							}
810
-							// moving a file/folder between storages (from $storage1 to $storage2)
811
-						} else {
812
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
813
-						}
814
-
815
-						if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
816
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
817
-							$this->writeUpdate($storage2, $internalPath2);
818
-						} else if ($result) {
819
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
820
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
821
-							}
822
-						}
823
-					} catch(\Exception $e) {
824
-						throw $e;
825
-					} finally {
826
-						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
827
-						$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
828
-					}
829
-
830
-					if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
831
-						if ($this->shouldEmitHooks()) {
832
-							$this->emit_file_hooks_post($exists, $path2);
833
-						}
834
-					} elseif ($result) {
835
-						if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
836
-							\OC_Hook::emit(
837
-								Filesystem::CLASSNAME,
838
-								Filesystem::signal_post_rename,
839
-								array(
840
-									Filesystem::signal_param_oldpath => $this->getHookPath($path1),
841
-									Filesystem::signal_param_newpath => $this->getHookPath($path2)
842
-								)
843
-							);
844
-						}
845
-					}
846
-				}
847
-			} catch(\Exception $e) {
848
-				throw $e;
849
-			} finally {
850
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
851
-				$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
852
-			}
853
-		}
854
-		return $result;
855
-	}
856
-
857
-	/**
858
-	 * Copy a file/folder from the source path to target path
859
-	 *
860
-	 * @param string $path1 source path
861
-	 * @param string $path2 target path
862
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
863
-	 *
864
-	 * @return bool|mixed
865
-	 */
866
-	public function copy($path1, $path2, $preserveMtime = false) {
867
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
868
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
869
-		$result = false;
870
-		if (
871
-			Filesystem::isValidPath($path2)
872
-			and Filesystem::isValidPath($path1)
873
-			and !Filesystem::isFileBlacklisted($path2)
874
-		) {
875
-			$path1 = $this->getRelativePath($absolutePath1);
876
-			$path2 = $this->getRelativePath($absolutePath2);
877
-
878
-			if ($path1 == null or $path2 == null) {
879
-				return false;
880
-			}
881
-			$run = true;
882
-
883
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
884
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
885
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
886
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
887
-
888
-			try {
889
-
890
-				$exists = $this->file_exists($path2);
891
-				if ($this->shouldEmitHooks()) {
892
-					\OC_Hook::emit(
893
-						Filesystem::CLASSNAME,
894
-						Filesystem::signal_copy,
895
-						array(
896
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
897
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
898
-							Filesystem::signal_param_run => &$run
899
-						)
900
-					);
901
-					$this->emit_file_hooks_pre($exists, $path2, $run);
902
-				}
903
-				if ($run) {
904
-					$mount1 = $this->getMount($path1);
905
-					$mount2 = $this->getMount($path2);
906
-					$storage1 = $mount1->getStorage();
907
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
908
-					$storage2 = $mount2->getStorage();
909
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
910
-
911
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
912
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
913
-
914
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
915
-						if ($storage1) {
916
-							$result = $storage1->copy($internalPath1, $internalPath2);
917
-						} else {
918
-							$result = false;
919
-						}
920
-					} else {
921
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
922
-					}
923
-
924
-					$this->writeUpdate($storage2, $internalPath2);
925
-
926
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
927
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
928
-
929
-					if ($this->shouldEmitHooks() && $result !== false) {
930
-						\OC_Hook::emit(
931
-							Filesystem::CLASSNAME,
932
-							Filesystem::signal_post_copy,
933
-							array(
934
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
935
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
936
-							)
937
-						);
938
-						$this->emit_file_hooks_post($exists, $path2);
939
-					}
940
-
941
-				}
942
-			} catch (\Exception $e) {
943
-				$this->unlockFile($path2, $lockTypePath2);
944
-				$this->unlockFile($path1, $lockTypePath1);
945
-				throw $e;
946
-			}
947
-
948
-			$this->unlockFile($path2, $lockTypePath2);
949
-			$this->unlockFile($path1, $lockTypePath1);
950
-
951
-		}
952
-		return $result;
953
-	}
954
-
955
-	/**
956
-	 * @param string $path
957
-	 * @param string $mode 'r' or 'w'
958
-	 * @return resource
959
-	 */
960
-	public function fopen($path, $mode) {
961
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
962
-		$hooks = array();
963
-		switch ($mode) {
964
-			case 'r':
965
-				$hooks[] = 'read';
966
-				break;
967
-			case 'r+':
968
-			case 'w+':
969
-			case 'x+':
970
-			case 'a+':
971
-				$hooks[] = 'read';
972
-				$hooks[] = 'write';
973
-				break;
974
-			case 'w':
975
-			case 'x':
976
-			case 'a':
977
-				$hooks[] = 'write';
978
-				break;
979
-			default:
980
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
981
-		}
982
-
983
-		if ($mode !== 'r' && $mode !== 'w') {
984
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
985
-		}
986
-
987
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
988
-	}
989
-
990
-	/**
991
-	 * @param string $path
992
-	 * @return bool|string
993
-	 * @throws \OCP\Files\InvalidPathException
994
-	 */
995
-	public function toTmpFile($path) {
996
-		$this->assertPathLength($path);
997
-		if (Filesystem::isValidPath($path)) {
998
-			$source = $this->fopen($path, 'r');
999
-			if ($source) {
1000
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1001
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1002
-				file_put_contents($tmpFile, $source);
1003
-				return $tmpFile;
1004
-			} else {
1005
-				return false;
1006
-			}
1007
-		} else {
1008
-			return false;
1009
-		}
1010
-	}
1011
-
1012
-	/**
1013
-	 * @param string $tmpFile
1014
-	 * @param string $path
1015
-	 * @return bool|mixed
1016
-	 * @throws \OCP\Files\InvalidPathException
1017
-	 */
1018
-	public function fromTmpFile($tmpFile, $path) {
1019
-		$this->assertPathLength($path);
1020
-		if (Filesystem::isValidPath($path)) {
1021
-
1022
-			// Get directory that the file is going into
1023
-			$filePath = dirname($path);
1024
-
1025
-			// Create the directories if any
1026
-			if (!$this->file_exists($filePath)) {
1027
-				$result = $this->createParentDirectories($filePath);
1028
-				if ($result === false) {
1029
-					return false;
1030
-				}
1031
-			}
1032
-
1033
-			$source = fopen($tmpFile, 'r');
1034
-			if ($source) {
1035
-				$result = $this->file_put_contents($path, $source);
1036
-				// $this->file_put_contents() might have already closed
1037
-				// the resource, so we check it, before trying to close it
1038
-				// to avoid messages in the error log.
1039
-				if (is_resource($source)) {
1040
-					fclose($source);
1041
-				}
1042
-				unlink($tmpFile);
1043
-				return $result;
1044
-			} else {
1045
-				return false;
1046
-			}
1047
-		} else {
1048
-			return false;
1049
-		}
1050
-	}
1051
-
1052
-
1053
-	/**
1054
-	 * @param string $path
1055
-	 * @return mixed
1056
-	 * @throws \OCP\Files\InvalidPathException
1057
-	 */
1058
-	public function getMimeType($path) {
1059
-		$this->assertPathLength($path);
1060
-		return $this->basicOperation('getMimeType', $path);
1061
-	}
1062
-
1063
-	/**
1064
-	 * @param string $type
1065
-	 * @param string $path
1066
-	 * @param bool $raw
1067
-	 * @return bool|null|string
1068
-	 */
1069
-	public function hash($type, $path, $raw = false) {
1070
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1071
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1072
-		if (Filesystem::isValidPath($path)) {
1073
-			$path = $this->getRelativePath($absolutePath);
1074
-			if ($path == null) {
1075
-				return false;
1076
-			}
1077
-			if ($this->shouldEmitHooks($path)) {
1078
-				\OC_Hook::emit(
1079
-					Filesystem::CLASSNAME,
1080
-					Filesystem::signal_read,
1081
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1082
-				);
1083
-			}
1084
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1085
-			if ($storage) {
1086
-				$result = $storage->hash($type, $internalPath, $raw);
1087
-				return $result;
1088
-			}
1089
-		}
1090
-		return null;
1091
-	}
1092
-
1093
-	/**
1094
-	 * @param string $path
1095
-	 * @return mixed
1096
-	 * @throws \OCP\Files\InvalidPathException
1097
-	 */
1098
-	public function free_space($path = '/') {
1099
-		$this->assertPathLength($path);
1100
-		$result = $this->basicOperation('free_space', $path);
1101
-		if ($result === null) {
1102
-			throw new InvalidPathException();
1103
-		}
1104
-		return $result;
1105
-	}
1106
-
1107
-	/**
1108
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1109
-	 *
1110
-	 * @param string $operation
1111
-	 * @param string $path
1112
-	 * @param array $hooks (optional)
1113
-	 * @param mixed $extraParam (optional)
1114
-	 * @return mixed
1115
-	 * @throws \Exception
1116
-	 *
1117
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1118
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1119
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1120
-	 */
1121
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1122
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1123
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1124
-		if (Filesystem::isValidPath($path)
1125
-			and !Filesystem::isFileBlacklisted($path)
1126
-		) {
1127
-			$path = $this->getRelativePath($absolutePath);
1128
-			if ($path == null) {
1129
-				return false;
1130
-			}
1131
-
1132
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1133
-				// always a shared lock during pre-hooks so the hook can read the file
1134
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1135
-			}
1136
-
1137
-			$run = $this->runHooks($hooks, $path);
1138
-			/** @var \OC\Files\Storage\Storage $storage */
1139
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1140
-			if ($run and $storage) {
1141
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1142
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1143
-				}
1144
-				try {
1145
-					if (!is_null($extraParam)) {
1146
-						$result = $storage->$operation($internalPath, $extraParam);
1147
-					} else {
1148
-						$result = $storage->$operation($internalPath);
1149
-					}
1150
-				} catch (\Exception $e) {
1151
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1152
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1153
-					} else if (in_array('read', $hooks)) {
1154
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1155
-					}
1156
-					throw $e;
1157
-				}
1158
-
1159
-				if ($result && in_array('delete', $hooks) and $result) {
1160
-					$this->removeUpdate($storage, $internalPath);
1161
-				}
1162
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1163
-					$this->writeUpdate($storage, $internalPath);
1164
-				}
1165
-				if ($result && in_array('touch', $hooks)) {
1166
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1167
-				}
1168
-
1169
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1170
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1171
-				}
1172
-
1173
-				$unlockLater = false;
1174
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1175
-					$unlockLater = true;
1176
-					// make sure our unlocking callback will still be called if connection is aborted
1177
-					ignore_user_abort(true);
1178
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1179
-						if (in_array('write', $hooks)) {
1180
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1181
-						} else if (in_array('read', $hooks)) {
1182
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1183
-						}
1184
-					});
1185
-				}
1186
-
1187
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1188
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1189
-						$this->runHooks($hooks, $path, true);
1190
-					}
1191
-				}
1192
-
1193
-				if (!$unlockLater
1194
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1195
-				) {
1196
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1197
-				}
1198
-				return $result;
1199
-			} else {
1200
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1201
-			}
1202
-		}
1203
-		return null;
1204
-	}
1205
-
1206
-	/**
1207
-	 * get the path relative to the default root for hook usage
1208
-	 *
1209
-	 * @param string $path
1210
-	 * @return string
1211
-	 */
1212
-	private function getHookPath($path) {
1213
-		if (!Filesystem::getView()) {
1214
-			return $path;
1215
-		}
1216
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1217
-	}
1218
-
1219
-	private function shouldEmitHooks($path = '') {
1220
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1221
-			return false;
1222
-		}
1223
-		if (!Filesystem::$loaded) {
1224
-			return false;
1225
-		}
1226
-		$defaultRoot = Filesystem::getRoot();
1227
-		if ($defaultRoot === null) {
1228
-			return false;
1229
-		}
1230
-		if ($this->fakeRoot === $defaultRoot) {
1231
-			return true;
1232
-		}
1233
-		$fullPath = $this->getAbsolutePath($path);
1234
-
1235
-		if ($fullPath === $defaultRoot) {
1236
-			return true;
1237
-		}
1238
-
1239
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1240
-	}
1241
-
1242
-	/**
1243
-	 * @param string[] $hooks
1244
-	 * @param string $path
1245
-	 * @param bool $post
1246
-	 * @return bool
1247
-	 */
1248
-	private function runHooks($hooks, $path, $post = false) {
1249
-		$relativePath = $path;
1250
-		$path = $this->getHookPath($path);
1251
-		$prefix = ($post) ? 'post_' : '';
1252
-		$run = true;
1253
-		if ($this->shouldEmitHooks($relativePath)) {
1254
-			foreach ($hooks as $hook) {
1255
-				if ($hook != 'read') {
1256
-					\OC_Hook::emit(
1257
-						Filesystem::CLASSNAME,
1258
-						$prefix . $hook,
1259
-						array(
1260
-							Filesystem::signal_param_run => &$run,
1261
-							Filesystem::signal_param_path => $path
1262
-						)
1263
-					);
1264
-				} elseif (!$post) {
1265
-					\OC_Hook::emit(
1266
-						Filesystem::CLASSNAME,
1267
-						$prefix . $hook,
1268
-						array(
1269
-							Filesystem::signal_param_path => $path
1270
-						)
1271
-					);
1272
-				}
1273
-			}
1274
-		}
1275
-		return $run;
1276
-	}
1277
-
1278
-	/**
1279
-	 * check if a file or folder has been updated since $time
1280
-	 *
1281
-	 * @param string $path
1282
-	 * @param int $time
1283
-	 * @return bool
1284
-	 */
1285
-	public function hasUpdated($path, $time) {
1286
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1287
-	}
1288
-
1289
-	/**
1290
-	 * @param string $ownerId
1291
-	 * @return \OC\User\User
1292
-	 */
1293
-	private function getUserObjectForOwner($ownerId) {
1294
-		$owner = $this->userManager->get($ownerId);
1295
-		if ($owner instanceof IUser) {
1296
-			return $owner;
1297
-		} else {
1298
-			return new User($ownerId, null);
1299
-		}
1300
-	}
1301
-
1302
-	/**
1303
-	 * Get file info from cache
1304
-	 *
1305
-	 * If the file is not in cached it will be scanned
1306
-	 * If the file has changed on storage the cache will be updated
1307
-	 *
1308
-	 * @param \OC\Files\Storage\Storage $storage
1309
-	 * @param string $internalPath
1310
-	 * @param string $relativePath
1311
-	 * @return ICacheEntry|bool
1312
-	 */
1313
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1314
-		$cache = $storage->getCache($internalPath);
1315
-		$data = $cache->get($internalPath);
1316
-		$watcher = $storage->getWatcher($internalPath);
1317
-
1318
-		try {
1319
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1320
-			if (!$data || $data['size'] === -1) {
1321
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1322
-				if (!$storage->file_exists($internalPath)) {
1323
-					$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1324
-					return false;
1325
-				}
1326
-				$scanner = $storage->getScanner($internalPath);
1327
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1328
-				$data = $cache->get($internalPath);
1329
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1330
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1331
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1332
-				$watcher->update($internalPath, $data);
1333
-				$storage->getPropagator()->propagateChange($internalPath, time());
1334
-				$data = $cache->get($internalPath);
1335
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1336
-			}
1337
-		} catch (LockedException $e) {
1338
-			// if the file is locked we just use the old cache info
1339
-		}
1340
-
1341
-		return $data;
1342
-	}
1343
-
1344
-	/**
1345
-	 * get the filesystem info
1346
-	 *
1347
-	 * @param string $path
1348
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1349
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1350
-	 * defaults to true
1351
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1352
-	 */
1353
-	public function getFileInfo($path, $includeMountPoints = true) {
1354
-		$this->assertPathLength($path);
1355
-		if (!Filesystem::isValidPath($path)) {
1356
-			return false;
1357
-		}
1358
-		if (Cache\Scanner::isPartialFile($path)) {
1359
-			return $this->getPartFileInfo($path);
1360
-		}
1361
-		$relativePath = $path;
1362
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1363
-
1364
-		$mount = Filesystem::getMountManager()->find($path);
1365
-		if (!$mount) {
1366
-			return false;
1367
-		}
1368
-		$storage = $mount->getStorage();
1369
-		$internalPath = $mount->getInternalPath($path);
1370
-		if ($storage) {
1371
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1372
-
1373
-			if (!$data instanceof ICacheEntry) {
1374
-				return false;
1375
-			}
1376
-
1377
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1378
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1379
-			}
1380
-
1381
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1382
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1383
-
1384
-			if ($data and isset($data['fileid'])) {
1385
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1386
-					//add the sizes of other mount points to the folder
1387
-					$extOnly = ($includeMountPoints === 'ext');
1388
-					$mounts = Filesystem::getMountManager()->findIn($path);
1389
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1390
-						$subStorage = $mount->getStorage();
1391
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1392
-					}));
1393
-				}
1394
-			}
1395
-
1396
-			return $info;
1397
-		}
1398
-
1399
-		return false;
1400
-	}
1401
-
1402
-	/**
1403
-	 * get the content of a directory
1404
-	 *
1405
-	 * @param string $directory path under datadirectory
1406
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1407
-	 * @return FileInfo[]
1408
-	 */
1409
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1410
-		$this->assertPathLength($directory);
1411
-		if (!Filesystem::isValidPath($directory)) {
1412
-			return [];
1413
-		}
1414
-		$path = $this->getAbsolutePath($directory);
1415
-		$path = Filesystem::normalizePath($path);
1416
-		$mount = $this->getMount($directory);
1417
-		if (!$mount) {
1418
-			return [];
1419
-		}
1420
-		$storage = $mount->getStorage();
1421
-		$internalPath = $mount->getInternalPath($path);
1422
-		if ($storage) {
1423
-			$cache = $storage->getCache($internalPath);
1424
-			$user = \OC_User::getUser();
1425
-
1426
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1427
-
1428
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1429
-				return [];
1430
-			}
1431
-
1432
-			$folderId = $data['fileid'];
1433
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1434
-
1435
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1436
-			/**
1437
-			 * @var \OC\Files\FileInfo[] $files
1438
-			 */
1439
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1440
-				if ($sharingDisabled) {
1441
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1442
-				}
1443
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1444
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1445
-			}, $contents);
1446
-
1447
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1448
-			$mounts = Filesystem::getMountManager()->findIn($path);
1449
-			$dirLength = strlen($path);
1450
-			foreach ($mounts as $mount) {
1451
-				$mountPoint = $mount->getMountPoint();
1452
-				$subStorage = $mount->getStorage();
1453
-				if ($subStorage) {
1454
-					$subCache = $subStorage->getCache('');
1455
-
1456
-					$rootEntry = $subCache->get('');
1457
-					if (!$rootEntry) {
1458
-						$subScanner = $subStorage->getScanner('');
1459
-						try {
1460
-							$subScanner->scanFile('');
1461
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1462
-							continue;
1463
-						} catch (\OCP\Files\StorageInvalidException $e) {
1464
-							continue;
1465
-						} catch (\Exception $e) {
1466
-							// sometimes when the storage is not available it can be any exception
1467
-							\OCP\Util::writeLog(
1468
-								'core',
1469
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1470
-								get_class($e) . ': ' . $e->getMessage(),
1471
-								\OCP\Util::ERROR
1472
-							);
1473
-							continue;
1474
-						}
1475
-						$rootEntry = $subCache->get('');
1476
-					}
1477
-
1478
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1479
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1480
-						if ($pos = strpos($relativePath, '/')) {
1481
-							//mountpoint inside subfolder add size to the correct folder
1482
-							$entryName = substr($relativePath, 0, $pos);
1483
-							foreach ($files as &$entry) {
1484
-								if ($entry->getName() === $entryName) {
1485
-									$entry->addSubEntry($rootEntry, $mountPoint);
1486
-								}
1487
-							}
1488
-						} else { //mountpoint in this folder, add an entry for it
1489
-							$rootEntry['name'] = $relativePath;
1490
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1491
-							$permissions = $rootEntry['permissions'];
1492
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1493
-							// for shared files/folders we use the permissions given by the owner
1494
-							if ($mount instanceof MoveableMount) {
1495
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1496
-							} else {
1497
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1498
-							}
1499
-
1500
-							//remove any existing entry with the same name
1501
-							foreach ($files as $i => $file) {
1502
-								if ($file['name'] === $rootEntry['name']) {
1503
-									unset($files[$i]);
1504
-									break;
1505
-								}
1506
-							}
1507
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1508
-
1509
-							// if sharing was disabled for the user we remove the share permissions
1510
-							if (\OCP\Util::isSharingDisabledForUser()) {
1511
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1512
-							}
1513
-
1514
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1515
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1516
-						}
1517
-					}
1518
-				}
1519
-			}
1520
-
1521
-			if ($mimetype_filter) {
1522
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1523
-					if (strpos($mimetype_filter, '/')) {
1524
-						return $file->getMimetype() === $mimetype_filter;
1525
-					} else {
1526
-						return $file->getMimePart() === $mimetype_filter;
1527
-					}
1528
-				});
1529
-			}
1530
-
1531
-			return $files;
1532
-		} else {
1533
-			return [];
1534
-		}
1535
-	}
1536
-
1537
-	/**
1538
-	 * change file metadata
1539
-	 *
1540
-	 * @param string $path
1541
-	 * @param array|\OCP\Files\FileInfo $data
1542
-	 * @return int
1543
-	 *
1544
-	 * returns the fileid of the updated file
1545
-	 */
1546
-	public function putFileInfo($path, $data) {
1547
-		$this->assertPathLength($path);
1548
-		if ($data instanceof FileInfo) {
1549
-			$data = $data->getData();
1550
-		}
1551
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1552
-		/**
1553
-		 * @var \OC\Files\Storage\Storage $storage
1554
-		 * @var string $internalPath
1555
-		 */
1556
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1557
-		if ($storage) {
1558
-			$cache = $storage->getCache($path);
1559
-
1560
-			if (!$cache->inCache($internalPath)) {
1561
-				$scanner = $storage->getScanner($internalPath);
1562
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1563
-			}
1564
-
1565
-			return $cache->put($internalPath, $data);
1566
-		} else {
1567
-			return -1;
1568
-		}
1569
-	}
1570
-
1571
-	/**
1572
-	 * search for files with the name matching $query
1573
-	 *
1574
-	 * @param string $query
1575
-	 * @return FileInfo[]
1576
-	 */
1577
-	public function search($query) {
1578
-		return $this->searchCommon('search', array('%' . $query . '%'));
1579
-	}
1580
-
1581
-	/**
1582
-	 * search for files with the name matching $query
1583
-	 *
1584
-	 * @param string $query
1585
-	 * @return FileInfo[]
1586
-	 */
1587
-	public function searchRaw($query) {
1588
-		return $this->searchCommon('search', array($query));
1589
-	}
1590
-
1591
-	/**
1592
-	 * search for files by mimetype
1593
-	 *
1594
-	 * @param string $mimetype
1595
-	 * @return FileInfo[]
1596
-	 */
1597
-	public function searchByMime($mimetype) {
1598
-		return $this->searchCommon('searchByMime', array($mimetype));
1599
-	}
1600
-
1601
-	/**
1602
-	 * search for files by tag
1603
-	 *
1604
-	 * @param string|int $tag name or tag id
1605
-	 * @param string $userId owner of the tags
1606
-	 * @return FileInfo[]
1607
-	 */
1608
-	public function searchByTag($tag, $userId) {
1609
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1610
-	}
1611
-
1612
-	/**
1613
-	 * @param string $method cache method
1614
-	 * @param array $args
1615
-	 * @return FileInfo[]
1616
-	 */
1617
-	private function searchCommon($method, $args) {
1618
-		$files = array();
1619
-		$rootLength = strlen($this->fakeRoot);
1620
-
1621
-		$mount = $this->getMount('');
1622
-		$mountPoint = $mount->getMountPoint();
1623
-		$storage = $mount->getStorage();
1624
-		if ($storage) {
1625
-			$cache = $storage->getCache('');
1626
-
1627
-			$results = call_user_func_array(array($cache, $method), $args);
1628
-			foreach ($results as $result) {
1629
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1630
-					$internalPath = $result['path'];
1631
-					$path = $mountPoint . $result['path'];
1632
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1633
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1634
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1635
-				}
1636
-			}
1637
-
1638
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1639
-			foreach ($mounts as $mount) {
1640
-				$mountPoint = $mount->getMountPoint();
1641
-				$storage = $mount->getStorage();
1642
-				if ($storage) {
1643
-					$cache = $storage->getCache('');
1644
-
1645
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1646
-					$results = call_user_func_array(array($cache, $method), $args);
1647
-					if ($results) {
1648
-						foreach ($results as $result) {
1649
-							$internalPath = $result['path'];
1650
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1651
-							$path = rtrim($mountPoint . $internalPath, '/');
1652
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1653
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1654
-						}
1655
-					}
1656
-				}
1657
-			}
1658
-		}
1659
-		return $files;
1660
-	}
1661
-
1662
-	/**
1663
-	 * Get the owner for a file or folder
1664
-	 *
1665
-	 * @param string $path
1666
-	 * @return string the user id of the owner
1667
-	 * @throws NotFoundException
1668
-	 */
1669
-	public function getOwner($path) {
1670
-		$info = $this->getFileInfo($path);
1671
-		if (!$info) {
1672
-			throw new NotFoundException($path . ' not found while trying to get owner');
1673
-		}
1674
-		return $info->getOwner()->getUID();
1675
-	}
1676
-
1677
-	/**
1678
-	 * get the ETag for a file or folder
1679
-	 *
1680
-	 * @param string $path
1681
-	 * @return string
1682
-	 */
1683
-	public function getETag($path) {
1684
-		/**
1685
-		 * @var Storage\Storage $storage
1686
-		 * @var string $internalPath
1687
-		 */
1688
-		list($storage, $internalPath) = $this->resolvePath($path);
1689
-		if ($storage) {
1690
-			return $storage->getETag($internalPath);
1691
-		} else {
1692
-			return null;
1693
-		}
1694
-	}
1695
-
1696
-	/**
1697
-	 * Get the path of a file by id, relative to the view
1698
-	 *
1699
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1700
-	 *
1701
-	 * @param int $id
1702
-	 * @throws NotFoundException
1703
-	 * @return string
1704
-	 */
1705
-	public function getPath($id) {
1706
-		$id = (int)$id;
1707
-		$manager = Filesystem::getMountManager();
1708
-		$mounts = $manager->findIn($this->fakeRoot);
1709
-		$mounts[] = $manager->find($this->fakeRoot);
1710
-		// reverse the array so we start with the storage this view is in
1711
-		// which is the most likely to contain the file we're looking for
1712
-		$mounts = array_reverse($mounts);
1713
-		foreach ($mounts as $mount) {
1714
-			/**
1715
-			 * @var \OC\Files\Mount\MountPoint $mount
1716
-			 */
1717
-			if ($mount->getStorage()) {
1718
-				$cache = $mount->getStorage()->getCache();
1719
-				$internalPath = $cache->getPathById($id);
1720
-				if (is_string($internalPath)) {
1721
-					$fullPath = $mount->getMountPoint() . $internalPath;
1722
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1723
-						return $path;
1724
-					}
1725
-				}
1726
-			}
1727
-		}
1728
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1729
-	}
1730
-
1731
-	/**
1732
-	 * @param string $path
1733
-	 * @throws InvalidPathException
1734
-	 */
1735
-	private function assertPathLength($path) {
1736
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1737
-		// Check for the string length - performed using isset() instead of strlen()
1738
-		// because isset() is about 5x-40x faster.
1739
-		if (isset($path[$maxLen])) {
1740
-			$pathLen = strlen($path);
1741
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1742
-		}
1743
-	}
1744
-
1745
-	/**
1746
-	 * check if it is allowed to move a mount point to a given target.
1747
-	 * It is not allowed to move a mount point into a different mount point or
1748
-	 * into an already shared folder
1749
-	 *
1750
-	 * @param string $target path
1751
-	 * @return boolean
1752
-	 */
1753
-	private function isTargetAllowed($target) {
1754
-
1755
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1756
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1757
-			\OCP\Util::writeLog('files',
1758
-				'It is not allowed to move one mount point into another one',
1759
-				\OCP\Util::DEBUG);
1760
-			return false;
1761
-		}
1762
-
1763
-		// note: cannot use the view because the target is already locked
1764
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1765
-		if ($fileId === -1) {
1766
-			// target might not exist, need to check parent instead
1767
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1768
-		}
1769
-
1770
-		// check if any of the parents were shared by the current owner (include collections)
1771
-		$shares = \OCP\Share::getItemShared(
1772
-			'folder',
1773
-			$fileId,
1774
-			\OCP\Share::FORMAT_NONE,
1775
-			null,
1776
-			true
1777
-		);
1778
-
1779
-		if (count($shares) > 0) {
1780
-			\OCP\Util::writeLog('files',
1781
-				'It is not allowed to move one mount point into a shared folder',
1782
-				\OCP\Util::DEBUG);
1783
-			return false;
1784
-		}
1785
-
1786
-		return true;
1787
-	}
1788
-
1789
-	/**
1790
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1791
-	 *
1792
-	 * @param string $path
1793
-	 * @return \OCP\Files\FileInfo
1794
-	 */
1795
-	private function getPartFileInfo($path) {
1796
-		$mount = $this->getMount($path);
1797
-		$storage = $mount->getStorage();
1798
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1799
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1800
-		return new FileInfo(
1801
-			$this->getAbsolutePath($path),
1802
-			$storage,
1803
-			$internalPath,
1804
-			[
1805
-				'fileid' => null,
1806
-				'mimetype' => $storage->getMimeType($internalPath),
1807
-				'name' => basename($path),
1808
-				'etag' => null,
1809
-				'size' => $storage->filesize($internalPath),
1810
-				'mtime' => $storage->filemtime($internalPath),
1811
-				'encrypted' => false,
1812
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1813
-			],
1814
-			$mount,
1815
-			$owner
1816
-		);
1817
-	}
1818
-
1819
-	/**
1820
-	 * @param string $path
1821
-	 * @param string $fileName
1822
-	 * @throws InvalidPathException
1823
-	 */
1824
-	public function verifyPath($path, $fileName) {
1825
-		try {
1826
-			/** @type \OCP\Files\Storage $storage */
1827
-			list($storage, $internalPath) = $this->resolvePath($path);
1828
-			$storage->verifyPath($internalPath, $fileName);
1829
-		} catch (ReservedWordException $ex) {
1830
-			$l = \OC::$server->getL10N('lib');
1831
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1832
-		} catch (InvalidCharacterInPathException $ex) {
1833
-			$l = \OC::$server->getL10N('lib');
1834
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1835
-		} catch (FileNameTooLongException $ex) {
1836
-			$l = \OC::$server->getL10N('lib');
1837
-			throw new InvalidPathException($l->t('File name is too long'));
1838
-		} catch (InvalidDirectoryException $ex) {
1839
-			$l = \OC::$server->getL10N('lib');
1840
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1841
-		} catch (EmptyFileNameException $ex) {
1842
-			$l = \OC::$server->getL10N('lib');
1843
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1844
-		}
1845
-	}
1846
-
1847
-	/**
1848
-	 * get all parent folders of $path
1849
-	 *
1850
-	 * @param string $path
1851
-	 * @return string[]
1852
-	 */
1853
-	private function getParents($path) {
1854
-		$path = trim($path, '/');
1855
-		if (!$path) {
1856
-			return [];
1857
-		}
1858
-
1859
-		$parts = explode('/', $path);
1860
-
1861
-		// remove the single file
1862
-		array_pop($parts);
1863
-		$result = array('/');
1864
-		$resultPath = '';
1865
-		foreach ($parts as $part) {
1866
-			if ($part) {
1867
-				$resultPath .= '/' . $part;
1868
-				$result[] = $resultPath;
1869
-			}
1870
-		}
1871
-		return $result;
1872
-	}
1873
-
1874
-	/**
1875
-	 * Returns the mount point for which to lock
1876
-	 *
1877
-	 * @param string $absolutePath absolute path
1878
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1879
-	 * is mounted directly on the given path, false otherwise
1880
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1881
-	 */
1882
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1883
-		$results = [];
1884
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1885
-		if (!$mount) {
1886
-			return $results;
1887
-		}
1888
-
1889
-		if ($useParentMount) {
1890
-			// find out if something is mounted directly on the path
1891
-			$internalPath = $mount->getInternalPath($absolutePath);
1892
-			if ($internalPath === '') {
1893
-				// resolve the parent mount instead
1894
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1895
-			}
1896
-		}
1897
-
1898
-		return $mount;
1899
-	}
1900
-
1901
-	/**
1902
-	 * Lock the given path
1903
-	 *
1904
-	 * @param string $path the path of the file to lock, relative to the view
1905
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1906
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1907
-	 *
1908
-	 * @return bool False if the path is excluded from locking, true otherwise
1909
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1910
-	 */
1911
-	private function lockPath($path, $type, $lockMountPoint = false) {
1912
-		$absolutePath = $this->getAbsolutePath($path);
1913
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1914
-		if (!$this->shouldLockFile($absolutePath)) {
1915
-			return false;
1916
-		}
1917
-
1918
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1919
-		if ($mount) {
1920
-			try {
1921
-				$storage = $mount->getStorage();
1922
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1923
-					$storage->acquireLock(
1924
-						$mount->getInternalPath($absolutePath),
1925
-						$type,
1926
-						$this->lockingProvider
1927
-					);
1928
-				}
1929
-			} catch (\OCP\Lock\LockedException $e) {
1930
-				// rethrow with the a human-readable path
1931
-				throw new \OCP\Lock\LockedException(
1932
-					$this->getPathRelativeToFiles($absolutePath),
1933
-					$e
1934
-				);
1935
-			}
1936
-		}
1937
-
1938
-		return true;
1939
-	}
1940
-
1941
-	/**
1942
-	 * Change the lock type
1943
-	 *
1944
-	 * @param string $path the path of the file to lock, relative to the view
1945
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1946
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1947
-	 *
1948
-	 * @return bool False if the path is excluded from locking, true otherwise
1949
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1950
-	 */
1951
-	public function changeLock($path, $type, $lockMountPoint = false) {
1952
-		$path = Filesystem::normalizePath($path);
1953
-		$absolutePath = $this->getAbsolutePath($path);
1954
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1955
-		if (!$this->shouldLockFile($absolutePath)) {
1956
-			return false;
1957
-		}
1958
-
1959
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1960
-		if ($mount) {
1961
-			try {
1962
-				$storage = $mount->getStorage();
1963
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1964
-					$storage->changeLock(
1965
-						$mount->getInternalPath($absolutePath),
1966
-						$type,
1967
-						$this->lockingProvider
1968
-					);
1969
-				}
1970
-			} catch (\OCP\Lock\LockedException $e) {
1971
-				try {
1972
-					// rethrow with the a human-readable path
1973
-					throw new \OCP\Lock\LockedException(
1974
-						$this->getPathRelativeToFiles($absolutePath),
1975
-						$e
1976
-					);
1977
-				} catch (\InvalidArgumentException $e) {
1978
-					throw new \OCP\Lock\LockedException(
1979
-						$absolutePath,
1980
-						$e
1981
-					);
1982
-				}
1983
-			}
1984
-		}
1985
-
1986
-		return true;
1987
-	}
1988
-
1989
-	/**
1990
-	 * Unlock the given path
1991
-	 *
1992
-	 * @param string $path the path of the file to unlock, relative to the view
1993
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1994
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1995
-	 *
1996
-	 * @return bool False if the path is excluded from locking, true otherwise
1997
-	 */
1998
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1999
-		$absolutePath = $this->getAbsolutePath($path);
2000
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2001
-		if (!$this->shouldLockFile($absolutePath)) {
2002
-			return false;
2003
-		}
2004
-
2005
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2006
-		if ($mount) {
2007
-			$storage = $mount->getStorage();
2008
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2009
-				$storage->releaseLock(
2010
-					$mount->getInternalPath($absolutePath),
2011
-					$type,
2012
-					$this->lockingProvider
2013
-				);
2014
-			}
2015
-		}
2016
-
2017
-		return true;
2018
-	}
2019
-
2020
-	/**
2021
-	 * Lock a path and all its parents up to the root of the view
2022
-	 *
2023
-	 * @param string $path the path of the file to lock relative to the view
2024
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2025
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2026
-	 *
2027
-	 * @return bool False if the path is excluded from locking, true otherwise
2028
-	 */
2029
-	public function lockFile($path, $type, $lockMountPoint = false) {
2030
-		$absolutePath = $this->getAbsolutePath($path);
2031
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2032
-		if (!$this->shouldLockFile($absolutePath)) {
2033
-			return false;
2034
-		}
2035
-
2036
-		$this->lockPath($path, $type, $lockMountPoint);
2037
-
2038
-		$parents = $this->getParents($path);
2039
-		foreach ($parents as $parent) {
2040
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2041
-		}
2042
-
2043
-		return true;
2044
-	}
2045
-
2046
-	/**
2047
-	 * Unlock a path and all its parents up to the root of the view
2048
-	 *
2049
-	 * @param string $path the path of the file to lock relative to the view
2050
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
-	 *
2053
-	 * @return bool False if the path is excluded from locking, true otherwise
2054
-	 */
2055
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2056
-		$absolutePath = $this->getAbsolutePath($path);
2057
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2058
-		if (!$this->shouldLockFile($absolutePath)) {
2059
-			return false;
2060
-		}
2061
-
2062
-		$this->unlockPath($path, $type, $lockMountPoint);
2063
-
2064
-		$parents = $this->getParents($path);
2065
-		foreach ($parents as $parent) {
2066
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2067
-		}
2068
-
2069
-		return true;
2070
-	}
2071
-
2072
-	/**
2073
-	 * Only lock files in data/user/files/
2074
-	 *
2075
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2076
-	 * @return bool
2077
-	 */
2078
-	protected function shouldLockFile($path) {
2079
-		$path = Filesystem::normalizePath($path);
2080
-
2081
-		$pathSegments = explode('/', $path);
2082
-		if (isset($pathSegments[2])) {
2083
-			// E.g.: /username/files/path-to-file
2084
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2085
-		}
2086
-
2087
-		return strpos($path, '/appdata_') !== 0;
2088
-	}
2089
-
2090
-	/**
2091
-	 * Shortens the given absolute path to be relative to
2092
-	 * "$user/files".
2093
-	 *
2094
-	 * @param string $absolutePath absolute path which is under "files"
2095
-	 *
2096
-	 * @return string path relative to "files" with trimmed slashes or null
2097
-	 * if the path was NOT relative to files
2098
-	 *
2099
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2100
-	 * @since 8.1.0
2101
-	 */
2102
-	public function getPathRelativeToFiles($absolutePath) {
2103
-		$path = Filesystem::normalizePath($absolutePath);
2104
-		$parts = explode('/', trim($path, '/'), 3);
2105
-		// "$user", "files", "path/to/dir"
2106
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2107
-			$this->logger->error(
2108
-				'$absolutePath must be relative to "files", value is "%s"',
2109
-				[
2110
-					$absolutePath
2111
-				]
2112
-			);
2113
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2114
-		}
2115
-		if (isset($parts[2])) {
2116
-			return $parts[2];
2117
-		}
2118
-		return '';
2119
-	}
2120
-
2121
-	/**
2122
-	 * @param string $filename
2123
-	 * @return array
2124
-	 * @throws \OC\User\NoUserException
2125
-	 * @throws NotFoundException
2126
-	 */
2127
-	public function getUidAndFilename($filename) {
2128
-		$info = $this->getFileInfo($filename);
2129
-		if (!$info instanceof \OCP\Files\FileInfo) {
2130
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2131
-		}
2132
-		$uid = $info->getOwner()->getUID();
2133
-		if ($uid != \OCP\User::getUser()) {
2134
-			Filesystem::initMountPoints($uid);
2135
-			$ownerView = new View('/' . $uid . '/files');
2136
-			try {
2137
-				$filename = $ownerView->getPath($info['fileid']);
2138
-			} catch (NotFoundException $e) {
2139
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2140
-			}
2141
-		}
2142
-		return [$uid, $filename];
2143
-	}
2144
-
2145
-	/**
2146
-	 * Creates parent non-existing folders
2147
-	 *
2148
-	 * @param string $filePath
2149
-	 * @return bool
2150
-	 */
2151
-	private function createParentDirectories($filePath) {
2152
-		$directoryParts = explode('/', $filePath);
2153
-		$directoryParts = array_filter($directoryParts);
2154
-		foreach ($directoryParts as $key => $part) {
2155
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2156
-			$currentPath = '/' . implode('/', $currentPathElements);
2157
-			if ($this->is_file($currentPath)) {
2158
-				return false;
2159
-			}
2160
-			if (!$this->file_exists($currentPath)) {
2161
-				$this->mkdir($currentPath);
2162
-			}
2163
-		}
2164
-
2165
-		return true;
2166
-	}
83
+    /** @var string */
84
+    private $fakeRoot = '';
85
+
86
+    /**
87
+     * @var \OCP\Lock\ILockingProvider
88
+     */
89
+    protected $lockingProvider;
90
+
91
+    private $lockingEnabled;
92
+
93
+    private $updaterEnabled = true;
94
+
95
+    /** @var \OC\User\Manager */
96
+    private $userManager;
97
+
98
+    /** @var \OCP\ILogger */
99
+    private $logger;
100
+
101
+    /**
102
+     * @param string $root
103
+     * @throws \Exception If $root contains an invalid path
104
+     */
105
+    public function __construct($root = '') {
106
+        if (is_null($root)) {
107
+            throw new \InvalidArgumentException('Root can\'t be null');
108
+        }
109
+        if (!Filesystem::isValidPath($root)) {
110
+            throw new \Exception();
111
+        }
112
+
113
+        $this->fakeRoot = $root;
114
+        $this->lockingProvider = \OC::$server->getLockingProvider();
115
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
116
+        $this->userManager = \OC::$server->getUserManager();
117
+        $this->logger = \OC::$server->getLogger();
118
+    }
119
+
120
+    public function getAbsolutePath($path = '/') {
121
+        if ($path === null) {
122
+            return null;
123
+        }
124
+        $this->assertPathLength($path);
125
+        if ($path === '') {
126
+            $path = '/';
127
+        }
128
+        if ($path[0] !== '/') {
129
+            $path = '/' . $path;
130
+        }
131
+        return $this->fakeRoot . $path;
132
+    }
133
+
134
+    /**
135
+     * change the root to a fake root
136
+     *
137
+     * @param string $fakeRoot
138
+     * @return boolean|null
139
+     */
140
+    public function chroot($fakeRoot) {
141
+        if (!$fakeRoot == '') {
142
+            if ($fakeRoot[0] !== '/') {
143
+                $fakeRoot = '/' . $fakeRoot;
144
+            }
145
+        }
146
+        $this->fakeRoot = $fakeRoot;
147
+    }
148
+
149
+    /**
150
+     * get the fake root
151
+     *
152
+     * @return string
153
+     */
154
+    public function getRoot() {
155
+        return $this->fakeRoot;
156
+    }
157
+
158
+    /**
159
+     * get path relative to the root of the view
160
+     *
161
+     * @param string $path
162
+     * @return string
163
+     */
164
+    public function getRelativePath($path) {
165
+        $this->assertPathLength($path);
166
+        if ($this->fakeRoot == '') {
167
+            return $path;
168
+        }
169
+
170
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
171
+            return '/';
172
+        }
173
+
174
+        // missing slashes can cause wrong matches!
175
+        $root = rtrim($this->fakeRoot, '/') . '/';
176
+
177
+        if (strpos($path, $root) !== 0) {
178
+            return null;
179
+        } else {
180
+            $path = substr($path, strlen($this->fakeRoot));
181
+            if (strlen($path) === 0) {
182
+                return '/';
183
+            } else {
184
+                return $path;
185
+            }
186
+        }
187
+    }
188
+
189
+    /**
190
+     * get the mountpoint of the storage object for a path
191
+     * ( note: because a storage is not always mounted inside the fakeroot, the
192
+     * returned mountpoint is relative to the absolute root of the filesystem
193
+     * and does not take the chroot into account )
194
+     *
195
+     * @param string $path
196
+     * @return string
197
+     */
198
+    public function getMountPoint($path) {
199
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
200
+    }
201
+
202
+    /**
203
+     * get the mountpoint of the storage object for a path
204
+     * ( note: because a storage is not always mounted inside the fakeroot, the
205
+     * returned mountpoint is relative to the absolute root of the filesystem
206
+     * and does not take the chroot into account )
207
+     *
208
+     * @param string $path
209
+     * @return \OCP\Files\Mount\IMountPoint
210
+     */
211
+    public function getMount($path) {
212
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
213
+    }
214
+
215
+    /**
216
+     * resolve a path to a storage and internal path
217
+     *
218
+     * @param string $path
219
+     * @return array an array consisting of the storage and the internal path
220
+     */
221
+    public function resolvePath($path) {
222
+        $a = $this->getAbsolutePath($path);
223
+        $p = Filesystem::normalizePath($a);
224
+        return Filesystem::resolvePath($p);
225
+    }
226
+
227
+    /**
228
+     * return the path to a local version of the file
229
+     * we need this because we can't know if a file is stored local or not from
230
+     * outside the filestorage and for some purposes a local file is needed
231
+     *
232
+     * @param string $path
233
+     * @return string
234
+     */
235
+    public function getLocalFile($path) {
236
+        $parent = substr($path, 0, strrpos($path, '/'));
237
+        $path = $this->getAbsolutePath($path);
238
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
239
+        if (Filesystem::isValidPath($parent) and $storage) {
240
+            return $storage->getLocalFile($internalPath);
241
+        } else {
242
+            return null;
243
+        }
244
+    }
245
+
246
+    /**
247
+     * @param string $path
248
+     * @return string
249
+     */
250
+    public function getLocalFolder($path) {
251
+        $parent = substr($path, 0, strrpos($path, '/'));
252
+        $path = $this->getAbsolutePath($path);
253
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
254
+        if (Filesystem::isValidPath($parent) and $storage) {
255
+            return $storage->getLocalFolder($internalPath);
256
+        } else {
257
+            return null;
258
+        }
259
+    }
260
+
261
+    /**
262
+     * the following functions operate with arguments and return values identical
263
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
264
+     * for \OC\Files\Storage\Storage via basicOperation().
265
+     */
266
+    public function mkdir($path) {
267
+        return $this->basicOperation('mkdir', $path, array('create', 'write'));
268
+    }
269
+
270
+    /**
271
+     * remove mount point
272
+     *
273
+     * @param \OC\Files\Mount\MoveableMount $mount
274
+     * @param string $path relative to data/
275
+     * @return boolean
276
+     */
277
+    protected function removeMount($mount, $path) {
278
+        if ($mount instanceof MoveableMount) {
279
+            // cut of /user/files to get the relative path to data/user/files
280
+            $pathParts = explode('/', $path, 4);
281
+            $relPath = '/' . $pathParts[3];
282
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
283
+            \OC_Hook::emit(
284
+                Filesystem::CLASSNAME, "umount",
285
+                array(Filesystem::signal_param_path => $relPath)
286
+            );
287
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
288
+            $result = $mount->removeMount();
289
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
290
+            if ($result) {
291
+                \OC_Hook::emit(
292
+                    Filesystem::CLASSNAME, "post_umount",
293
+                    array(Filesystem::signal_param_path => $relPath)
294
+                );
295
+            }
296
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
297
+            return $result;
298
+        } else {
299
+            // do not allow deleting the storage's root / the mount point
300
+            // because for some storages it might delete the whole contents
301
+            // but isn't supposed to work that way
302
+            return false;
303
+        }
304
+    }
305
+
306
+    public function disableCacheUpdate() {
307
+        $this->updaterEnabled = false;
308
+    }
309
+
310
+    public function enableCacheUpdate() {
311
+        $this->updaterEnabled = true;
312
+    }
313
+
314
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
315
+        if ($this->updaterEnabled) {
316
+            if (is_null($time)) {
317
+                $time = time();
318
+            }
319
+            $storage->getUpdater()->update($internalPath, $time);
320
+        }
321
+    }
322
+
323
+    protected function removeUpdate(Storage $storage, $internalPath) {
324
+        if ($this->updaterEnabled) {
325
+            $storage->getUpdater()->remove($internalPath);
326
+        }
327
+    }
328
+
329
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
330
+        if ($this->updaterEnabled) {
331
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
332
+        }
333
+    }
334
+
335
+    /**
336
+     * @param string $path
337
+     * @return bool|mixed
338
+     */
339
+    public function rmdir($path) {
340
+        $absolutePath = $this->getAbsolutePath($path);
341
+        $mount = Filesystem::getMountManager()->find($absolutePath);
342
+        if ($mount->getInternalPath($absolutePath) === '') {
343
+            return $this->removeMount($mount, $absolutePath);
344
+        }
345
+        if ($this->is_dir($path)) {
346
+            $result = $this->basicOperation('rmdir', $path, array('delete'));
347
+        } else {
348
+            $result = false;
349
+        }
350
+
351
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
352
+            $storage = $mount->getStorage();
353
+            $internalPath = $mount->getInternalPath($absolutePath);
354
+            $storage->getUpdater()->remove($internalPath);
355
+        }
356
+        return $result;
357
+    }
358
+
359
+    /**
360
+     * @param string $path
361
+     * @return resource
362
+     */
363
+    public function opendir($path) {
364
+        return $this->basicOperation('opendir', $path, array('read'));
365
+    }
366
+
367
+    /**
368
+     * @param string $path
369
+     * @return bool|mixed
370
+     */
371
+    public function is_dir($path) {
372
+        if ($path == '/') {
373
+            return true;
374
+        }
375
+        return $this->basicOperation('is_dir', $path);
376
+    }
377
+
378
+    /**
379
+     * @param string $path
380
+     * @return bool|mixed
381
+     */
382
+    public function is_file($path) {
383
+        if ($path == '/') {
384
+            return false;
385
+        }
386
+        return $this->basicOperation('is_file', $path);
387
+    }
388
+
389
+    /**
390
+     * @param string $path
391
+     * @return mixed
392
+     */
393
+    public function stat($path) {
394
+        return $this->basicOperation('stat', $path);
395
+    }
396
+
397
+    /**
398
+     * @param string $path
399
+     * @return mixed
400
+     */
401
+    public function filetype($path) {
402
+        return $this->basicOperation('filetype', $path);
403
+    }
404
+
405
+    /**
406
+     * @param string $path
407
+     * @return mixed
408
+     */
409
+    public function filesize($path) {
410
+        return $this->basicOperation('filesize', $path);
411
+    }
412
+
413
+    /**
414
+     * @param string $path
415
+     * @return bool|mixed
416
+     * @throws \OCP\Files\InvalidPathException
417
+     */
418
+    public function readfile($path) {
419
+        $this->assertPathLength($path);
420
+        @ob_end_clean();
421
+        $handle = $this->fopen($path, 'rb');
422
+        if ($handle) {
423
+            $chunkSize = 8192; // 8 kB chunks
424
+            while (!feof($handle)) {
425
+                echo fread($handle, $chunkSize);
426
+                flush();
427
+            }
428
+            fclose($handle);
429
+            $size = $this->filesize($path);
430
+            return $size;
431
+        }
432
+        return false;
433
+    }
434
+
435
+    /**
436
+     * @param string $path
437
+     * @param int $from
438
+     * @param int $to
439
+     * @return bool|mixed
440
+     * @throws \OCP\Files\InvalidPathException
441
+     * @throws \OCP\Files\UnseekableException
442
+     */
443
+    public function readfilePart($path, $from, $to) {
444
+        $this->assertPathLength($path);
445
+        @ob_end_clean();
446
+        $handle = $this->fopen($path, 'rb');
447
+        if ($handle) {
448
+            $chunkSize = 8192; // 8 kB chunks
449
+            $startReading = true;
450
+
451
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
452
+                // forward file handle via chunked fread because fseek seem to have failed
453
+
454
+                $end = $from + 1;
455
+                while (!feof($handle) && ftell($handle) < $end) {
456
+                    $len = $from - ftell($handle);
457
+                    if ($len > $chunkSize) {
458
+                        $len = $chunkSize;
459
+                    }
460
+                    $result = fread($handle, $len);
461
+
462
+                    if ($result === false) {
463
+                        $startReading = false;
464
+                        break;
465
+                    }
466
+                }
467
+            }
468
+
469
+            if ($startReading) {
470
+                $end = $to + 1;
471
+                while (!feof($handle) && ftell($handle) < $end) {
472
+                    $len = $end - ftell($handle);
473
+                    if ($len > $chunkSize) {
474
+                        $len = $chunkSize;
475
+                    }
476
+                    echo fread($handle, $len);
477
+                    flush();
478
+                }
479
+                $size = ftell($handle) - $from;
480
+                return $size;
481
+            }
482
+
483
+            throw new \OCP\Files\UnseekableException('fseek error');
484
+        }
485
+        return false;
486
+    }
487
+
488
+    /**
489
+     * @param string $path
490
+     * @return mixed
491
+     */
492
+    public function isCreatable($path) {
493
+        return $this->basicOperation('isCreatable', $path);
494
+    }
495
+
496
+    /**
497
+     * @param string $path
498
+     * @return mixed
499
+     */
500
+    public function isReadable($path) {
501
+        return $this->basicOperation('isReadable', $path);
502
+    }
503
+
504
+    /**
505
+     * @param string $path
506
+     * @return mixed
507
+     */
508
+    public function isUpdatable($path) {
509
+        return $this->basicOperation('isUpdatable', $path);
510
+    }
511
+
512
+    /**
513
+     * @param string $path
514
+     * @return bool|mixed
515
+     */
516
+    public function isDeletable($path) {
517
+        $absolutePath = $this->getAbsolutePath($path);
518
+        $mount = Filesystem::getMountManager()->find($absolutePath);
519
+        if ($mount->getInternalPath($absolutePath) === '') {
520
+            return $mount instanceof MoveableMount;
521
+        }
522
+        return $this->basicOperation('isDeletable', $path);
523
+    }
524
+
525
+    /**
526
+     * @param string $path
527
+     * @return mixed
528
+     */
529
+    public function isSharable($path) {
530
+        return $this->basicOperation('isSharable', $path);
531
+    }
532
+
533
+    /**
534
+     * @param string $path
535
+     * @return bool|mixed
536
+     */
537
+    public function file_exists($path) {
538
+        if ($path == '/') {
539
+            return true;
540
+        }
541
+        return $this->basicOperation('file_exists', $path);
542
+    }
543
+
544
+    /**
545
+     * @param string $path
546
+     * @return mixed
547
+     */
548
+    public function filemtime($path) {
549
+        return $this->basicOperation('filemtime', $path);
550
+    }
551
+
552
+    /**
553
+     * @param string $path
554
+     * @param int|string $mtime
555
+     * @return bool
556
+     */
557
+    public function touch($path, $mtime = null) {
558
+        if (!is_null($mtime) and !is_numeric($mtime)) {
559
+            $mtime = strtotime($mtime);
560
+        }
561
+
562
+        $hooks = array('touch');
563
+
564
+        if (!$this->file_exists($path)) {
565
+            $hooks[] = 'create';
566
+            $hooks[] = 'write';
567
+        }
568
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
569
+        if (!$result) {
570
+            // If create file fails because of permissions on external storage like SMB folders,
571
+            // check file exists and return false if not.
572
+            if (!$this->file_exists($path)) {
573
+                return false;
574
+            }
575
+            if (is_null($mtime)) {
576
+                $mtime = time();
577
+            }
578
+            //if native touch fails, we emulate it by changing the mtime in the cache
579
+            $this->putFileInfo($path, array('mtime' => floor($mtime)));
580
+        }
581
+        return true;
582
+    }
583
+
584
+    /**
585
+     * @param string $path
586
+     * @return mixed
587
+     */
588
+    public function file_get_contents($path) {
589
+        return $this->basicOperation('file_get_contents', $path, array('read'));
590
+    }
591
+
592
+    /**
593
+     * @param bool $exists
594
+     * @param string $path
595
+     * @param bool $run
596
+     */
597
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
598
+        if (!$exists) {
599
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
600
+                Filesystem::signal_param_path => $this->getHookPath($path),
601
+                Filesystem::signal_param_run => &$run,
602
+            ));
603
+        } else {
604
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
605
+                Filesystem::signal_param_path => $this->getHookPath($path),
606
+                Filesystem::signal_param_run => &$run,
607
+            ));
608
+        }
609
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
610
+            Filesystem::signal_param_path => $this->getHookPath($path),
611
+            Filesystem::signal_param_run => &$run,
612
+        ));
613
+    }
614
+
615
+    /**
616
+     * @param bool $exists
617
+     * @param string $path
618
+     */
619
+    protected function emit_file_hooks_post($exists, $path) {
620
+        if (!$exists) {
621
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
622
+                Filesystem::signal_param_path => $this->getHookPath($path),
623
+            ));
624
+        } else {
625
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
626
+                Filesystem::signal_param_path => $this->getHookPath($path),
627
+            ));
628
+        }
629
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
630
+            Filesystem::signal_param_path => $this->getHookPath($path),
631
+        ));
632
+    }
633
+
634
+    /**
635
+     * @param string $path
636
+     * @param mixed $data
637
+     * @return bool|mixed
638
+     * @throws \Exception
639
+     */
640
+    public function file_put_contents($path, $data) {
641
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
642
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
643
+            if (Filesystem::isValidPath($path)
644
+                and !Filesystem::isFileBlacklisted($path)
645
+            ) {
646
+                $path = $this->getRelativePath($absolutePath);
647
+
648
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
649
+
650
+                $exists = $this->file_exists($path);
651
+                $run = true;
652
+                if ($this->shouldEmitHooks($path)) {
653
+                    $this->emit_file_hooks_pre($exists, $path, $run);
654
+                }
655
+                if (!$run) {
656
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
657
+                    return false;
658
+                }
659
+
660
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
661
+
662
+                /** @var \OC\Files\Storage\Storage $storage */
663
+                list($storage, $internalPath) = $this->resolvePath($path);
664
+                $target = $storage->fopen($internalPath, 'w');
665
+                if ($target) {
666
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
667
+                    fclose($target);
668
+                    fclose($data);
669
+
670
+                    $this->writeUpdate($storage, $internalPath);
671
+
672
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
673
+
674
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
675
+                        $this->emit_file_hooks_post($exists, $path);
676
+                    }
677
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
678
+                    return $result;
679
+                } else {
680
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
681
+                    return false;
682
+                }
683
+            } else {
684
+                return false;
685
+            }
686
+        } else {
687
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
688
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
689
+        }
690
+    }
691
+
692
+    /**
693
+     * @param string $path
694
+     * @return bool|mixed
695
+     */
696
+    public function unlink($path) {
697
+        if ($path === '' || $path === '/') {
698
+            // do not allow deleting the root
699
+            return false;
700
+        }
701
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
702
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
703
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
704
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
705
+            return $this->removeMount($mount, $absolutePath);
706
+        }
707
+        if ($this->is_dir($path)) {
708
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
709
+        } else {
710
+            $result = $this->basicOperation('unlink', $path, ['delete']);
711
+        }
712
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
713
+            $storage = $mount->getStorage();
714
+            $internalPath = $mount->getInternalPath($absolutePath);
715
+            $storage->getUpdater()->remove($internalPath);
716
+            return true;
717
+        } else {
718
+            return $result;
719
+        }
720
+    }
721
+
722
+    /**
723
+     * @param string $directory
724
+     * @return bool|mixed
725
+     */
726
+    public function deleteAll($directory) {
727
+        return $this->rmdir($directory);
728
+    }
729
+
730
+    /**
731
+     * Rename/move a file or folder from the source path to target path.
732
+     *
733
+     * @param string $path1 source path
734
+     * @param string $path2 target path
735
+     *
736
+     * @return bool|mixed
737
+     */
738
+    public function rename($path1, $path2) {
739
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
740
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
741
+        $result = false;
742
+        if (
743
+            Filesystem::isValidPath($path2)
744
+            and Filesystem::isValidPath($path1)
745
+            and !Filesystem::isFileBlacklisted($path2)
746
+        ) {
747
+            $path1 = $this->getRelativePath($absolutePath1);
748
+            $path2 = $this->getRelativePath($absolutePath2);
749
+            $exists = $this->file_exists($path2);
750
+
751
+            if ($path1 == null or $path2 == null) {
752
+                return false;
753
+            }
754
+
755
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
756
+            try {
757
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
758
+
759
+                $run = true;
760
+                if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
761
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
762
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
763
+                } elseif ($this->shouldEmitHooks($path1)) {
764
+                    \OC_Hook::emit(
765
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
766
+                        array(
767
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
768
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
769
+                            Filesystem::signal_param_run => &$run
770
+                        )
771
+                    );
772
+                }
773
+                if ($run) {
774
+                    $this->verifyPath(dirname($path2), basename($path2));
775
+
776
+                    $manager = Filesystem::getMountManager();
777
+                    $mount1 = $this->getMount($path1);
778
+                    $mount2 = $this->getMount($path2);
779
+                    $storage1 = $mount1->getStorage();
780
+                    $storage2 = $mount2->getStorage();
781
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
782
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
783
+
784
+                    $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
785
+                    try {
786
+                        $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
787
+
788
+                        if ($internalPath1 === '') {
789
+                            if ($mount1 instanceof MoveableMount) {
790
+                                if ($this->isTargetAllowed($absolutePath2)) {
791
+                                    /**
792
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
793
+                                     */
794
+                                    $sourceMountPoint = $mount1->getMountPoint();
795
+                                    $result = $mount1->moveMount($absolutePath2);
796
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
797
+                                } else {
798
+                                    $result = false;
799
+                                }
800
+                            } else {
801
+                                $result = false;
802
+                            }
803
+                            // moving a file/folder within the same mount point
804
+                        } elseif ($storage1 === $storage2) {
805
+                            if ($storage1) {
806
+                                $result = $storage1->rename($internalPath1, $internalPath2);
807
+                            } else {
808
+                                $result = false;
809
+                            }
810
+                            // moving a file/folder between storages (from $storage1 to $storage2)
811
+                        } else {
812
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
813
+                        }
814
+
815
+                        if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
816
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
817
+                            $this->writeUpdate($storage2, $internalPath2);
818
+                        } else if ($result) {
819
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
820
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
821
+                            }
822
+                        }
823
+                    } catch(\Exception $e) {
824
+                        throw $e;
825
+                    } finally {
826
+                        $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
827
+                        $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
828
+                    }
829
+
830
+                    if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
831
+                        if ($this->shouldEmitHooks()) {
832
+                            $this->emit_file_hooks_post($exists, $path2);
833
+                        }
834
+                    } elseif ($result) {
835
+                        if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
836
+                            \OC_Hook::emit(
837
+                                Filesystem::CLASSNAME,
838
+                                Filesystem::signal_post_rename,
839
+                                array(
840
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($path1),
841
+                                    Filesystem::signal_param_newpath => $this->getHookPath($path2)
842
+                                )
843
+                            );
844
+                        }
845
+                    }
846
+                }
847
+            } catch(\Exception $e) {
848
+                throw $e;
849
+            } finally {
850
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
851
+                $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
852
+            }
853
+        }
854
+        return $result;
855
+    }
856
+
857
+    /**
858
+     * Copy a file/folder from the source path to target path
859
+     *
860
+     * @param string $path1 source path
861
+     * @param string $path2 target path
862
+     * @param bool $preserveMtime whether to preserve mtime on the copy
863
+     *
864
+     * @return bool|mixed
865
+     */
866
+    public function copy($path1, $path2, $preserveMtime = false) {
867
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
868
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
869
+        $result = false;
870
+        if (
871
+            Filesystem::isValidPath($path2)
872
+            and Filesystem::isValidPath($path1)
873
+            and !Filesystem::isFileBlacklisted($path2)
874
+        ) {
875
+            $path1 = $this->getRelativePath($absolutePath1);
876
+            $path2 = $this->getRelativePath($absolutePath2);
877
+
878
+            if ($path1 == null or $path2 == null) {
879
+                return false;
880
+            }
881
+            $run = true;
882
+
883
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
884
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
885
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
886
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
887
+
888
+            try {
889
+
890
+                $exists = $this->file_exists($path2);
891
+                if ($this->shouldEmitHooks()) {
892
+                    \OC_Hook::emit(
893
+                        Filesystem::CLASSNAME,
894
+                        Filesystem::signal_copy,
895
+                        array(
896
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
897
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
898
+                            Filesystem::signal_param_run => &$run
899
+                        )
900
+                    );
901
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
902
+                }
903
+                if ($run) {
904
+                    $mount1 = $this->getMount($path1);
905
+                    $mount2 = $this->getMount($path2);
906
+                    $storage1 = $mount1->getStorage();
907
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
908
+                    $storage2 = $mount2->getStorage();
909
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
910
+
911
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
912
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
913
+
914
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
915
+                        if ($storage1) {
916
+                            $result = $storage1->copy($internalPath1, $internalPath2);
917
+                        } else {
918
+                            $result = false;
919
+                        }
920
+                    } else {
921
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
922
+                    }
923
+
924
+                    $this->writeUpdate($storage2, $internalPath2);
925
+
926
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
927
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
928
+
929
+                    if ($this->shouldEmitHooks() && $result !== false) {
930
+                        \OC_Hook::emit(
931
+                            Filesystem::CLASSNAME,
932
+                            Filesystem::signal_post_copy,
933
+                            array(
934
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
935
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
936
+                            )
937
+                        );
938
+                        $this->emit_file_hooks_post($exists, $path2);
939
+                    }
940
+
941
+                }
942
+            } catch (\Exception $e) {
943
+                $this->unlockFile($path2, $lockTypePath2);
944
+                $this->unlockFile($path1, $lockTypePath1);
945
+                throw $e;
946
+            }
947
+
948
+            $this->unlockFile($path2, $lockTypePath2);
949
+            $this->unlockFile($path1, $lockTypePath1);
950
+
951
+        }
952
+        return $result;
953
+    }
954
+
955
+    /**
956
+     * @param string $path
957
+     * @param string $mode 'r' or 'w'
958
+     * @return resource
959
+     */
960
+    public function fopen($path, $mode) {
961
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
962
+        $hooks = array();
963
+        switch ($mode) {
964
+            case 'r':
965
+                $hooks[] = 'read';
966
+                break;
967
+            case 'r+':
968
+            case 'w+':
969
+            case 'x+':
970
+            case 'a+':
971
+                $hooks[] = 'read';
972
+                $hooks[] = 'write';
973
+                break;
974
+            case 'w':
975
+            case 'x':
976
+            case 'a':
977
+                $hooks[] = 'write';
978
+                break;
979
+            default:
980
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
981
+        }
982
+
983
+        if ($mode !== 'r' && $mode !== 'w') {
984
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
985
+        }
986
+
987
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
988
+    }
989
+
990
+    /**
991
+     * @param string $path
992
+     * @return bool|string
993
+     * @throws \OCP\Files\InvalidPathException
994
+     */
995
+    public function toTmpFile($path) {
996
+        $this->assertPathLength($path);
997
+        if (Filesystem::isValidPath($path)) {
998
+            $source = $this->fopen($path, 'r');
999
+            if ($source) {
1000
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1001
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1002
+                file_put_contents($tmpFile, $source);
1003
+                return $tmpFile;
1004
+            } else {
1005
+                return false;
1006
+            }
1007
+        } else {
1008
+            return false;
1009
+        }
1010
+    }
1011
+
1012
+    /**
1013
+     * @param string $tmpFile
1014
+     * @param string $path
1015
+     * @return bool|mixed
1016
+     * @throws \OCP\Files\InvalidPathException
1017
+     */
1018
+    public function fromTmpFile($tmpFile, $path) {
1019
+        $this->assertPathLength($path);
1020
+        if (Filesystem::isValidPath($path)) {
1021
+
1022
+            // Get directory that the file is going into
1023
+            $filePath = dirname($path);
1024
+
1025
+            // Create the directories if any
1026
+            if (!$this->file_exists($filePath)) {
1027
+                $result = $this->createParentDirectories($filePath);
1028
+                if ($result === false) {
1029
+                    return false;
1030
+                }
1031
+            }
1032
+
1033
+            $source = fopen($tmpFile, 'r');
1034
+            if ($source) {
1035
+                $result = $this->file_put_contents($path, $source);
1036
+                // $this->file_put_contents() might have already closed
1037
+                // the resource, so we check it, before trying to close it
1038
+                // to avoid messages in the error log.
1039
+                if (is_resource($source)) {
1040
+                    fclose($source);
1041
+                }
1042
+                unlink($tmpFile);
1043
+                return $result;
1044
+            } else {
1045
+                return false;
1046
+            }
1047
+        } else {
1048
+            return false;
1049
+        }
1050
+    }
1051
+
1052
+
1053
+    /**
1054
+     * @param string $path
1055
+     * @return mixed
1056
+     * @throws \OCP\Files\InvalidPathException
1057
+     */
1058
+    public function getMimeType($path) {
1059
+        $this->assertPathLength($path);
1060
+        return $this->basicOperation('getMimeType', $path);
1061
+    }
1062
+
1063
+    /**
1064
+     * @param string $type
1065
+     * @param string $path
1066
+     * @param bool $raw
1067
+     * @return bool|null|string
1068
+     */
1069
+    public function hash($type, $path, $raw = false) {
1070
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1071
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1072
+        if (Filesystem::isValidPath($path)) {
1073
+            $path = $this->getRelativePath($absolutePath);
1074
+            if ($path == null) {
1075
+                return false;
1076
+            }
1077
+            if ($this->shouldEmitHooks($path)) {
1078
+                \OC_Hook::emit(
1079
+                    Filesystem::CLASSNAME,
1080
+                    Filesystem::signal_read,
1081
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1082
+                );
1083
+            }
1084
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1085
+            if ($storage) {
1086
+                $result = $storage->hash($type, $internalPath, $raw);
1087
+                return $result;
1088
+            }
1089
+        }
1090
+        return null;
1091
+    }
1092
+
1093
+    /**
1094
+     * @param string $path
1095
+     * @return mixed
1096
+     * @throws \OCP\Files\InvalidPathException
1097
+     */
1098
+    public function free_space($path = '/') {
1099
+        $this->assertPathLength($path);
1100
+        $result = $this->basicOperation('free_space', $path);
1101
+        if ($result === null) {
1102
+            throw new InvalidPathException();
1103
+        }
1104
+        return $result;
1105
+    }
1106
+
1107
+    /**
1108
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1109
+     *
1110
+     * @param string $operation
1111
+     * @param string $path
1112
+     * @param array $hooks (optional)
1113
+     * @param mixed $extraParam (optional)
1114
+     * @return mixed
1115
+     * @throws \Exception
1116
+     *
1117
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1118
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1119
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1120
+     */
1121
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1122
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1123
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1124
+        if (Filesystem::isValidPath($path)
1125
+            and !Filesystem::isFileBlacklisted($path)
1126
+        ) {
1127
+            $path = $this->getRelativePath($absolutePath);
1128
+            if ($path == null) {
1129
+                return false;
1130
+            }
1131
+
1132
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1133
+                // always a shared lock during pre-hooks so the hook can read the file
1134
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1135
+            }
1136
+
1137
+            $run = $this->runHooks($hooks, $path);
1138
+            /** @var \OC\Files\Storage\Storage $storage */
1139
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1140
+            if ($run and $storage) {
1141
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1142
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1143
+                }
1144
+                try {
1145
+                    if (!is_null($extraParam)) {
1146
+                        $result = $storage->$operation($internalPath, $extraParam);
1147
+                    } else {
1148
+                        $result = $storage->$operation($internalPath);
1149
+                    }
1150
+                } catch (\Exception $e) {
1151
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1152
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1153
+                    } else if (in_array('read', $hooks)) {
1154
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1155
+                    }
1156
+                    throw $e;
1157
+                }
1158
+
1159
+                if ($result && in_array('delete', $hooks) and $result) {
1160
+                    $this->removeUpdate($storage, $internalPath);
1161
+                }
1162
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1163
+                    $this->writeUpdate($storage, $internalPath);
1164
+                }
1165
+                if ($result && in_array('touch', $hooks)) {
1166
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1167
+                }
1168
+
1169
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1170
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1171
+                }
1172
+
1173
+                $unlockLater = false;
1174
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1175
+                    $unlockLater = true;
1176
+                    // make sure our unlocking callback will still be called if connection is aborted
1177
+                    ignore_user_abort(true);
1178
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1179
+                        if (in_array('write', $hooks)) {
1180
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1181
+                        } else if (in_array('read', $hooks)) {
1182
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1183
+                        }
1184
+                    });
1185
+                }
1186
+
1187
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1188
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1189
+                        $this->runHooks($hooks, $path, true);
1190
+                    }
1191
+                }
1192
+
1193
+                if (!$unlockLater
1194
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1195
+                ) {
1196
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1197
+                }
1198
+                return $result;
1199
+            } else {
1200
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1201
+            }
1202
+        }
1203
+        return null;
1204
+    }
1205
+
1206
+    /**
1207
+     * get the path relative to the default root for hook usage
1208
+     *
1209
+     * @param string $path
1210
+     * @return string
1211
+     */
1212
+    private function getHookPath($path) {
1213
+        if (!Filesystem::getView()) {
1214
+            return $path;
1215
+        }
1216
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1217
+    }
1218
+
1219
+    private function shouldEmitHooks($path = '') {
1220
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1221
+            return false;
1222
+        }
1223
+        if (!Filesystem::$loaded) {
1224
+            return false;
1225
+        }
1226
+        $defaultRoot = Filesystem::getRoot();
1227
+        if ($defaultRoot === null) {
1228
+            return false;
1229
+        }
1230
+        if ($this->fakeRoot === $defaultRoot) {
1231
+            return true;
1232
+        }
1233
+        $fullPath = $this->getAbsolutePath($path);
1234
+
1235
+        if ($fullPath === $defaultRoot) {
1236
+            return true;
1237
+        }
1238
+
1239
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1240
+    }
1241
+
1242
+    /**
1243
+     * @param string[] $hooks
1244
+     * @param string $path
1245
+     * @param bool $post
1246
+     * @return bool
1247
+     */
1248
+    private function runHooks($hooks, $path, $post = false) {
1249
+        $relativePath = $path;
1250
+        $path = $this->getHookPath($path);
1251
+        $prefix = ($post) ? 'post_' : '';
1252
+        $run = true;
1253
+        if ($this->shouldEmitHooks($relativePath)) {
1254
+            foreach ($hooks as $hook) {
1255
+                if ($hook != 'read') {
1256
+                    \OC_Hook::emit(
1257
+                        Filesystem::CLASSNAME,
1258
+                        $prefix . $hook,
1259
+                        array(
1260
+                            Filesystem::signal_param_run => &$run,
1261
+                            Filesystem::signal_param_path => $path
1262
+                        )
1263
+                    );
1264
+                } elseif (!$post) {
1265
+                    \OC_Hook::emit(
1266
+                        Filesystem::CLASSNAME,
1267
+                        $prefix . $hook,
1268
+                        array(
1269
+                            Filesystem::signal_param_path => $path
1270
+                        )
1271
+                    );
1272
+                }
1273
+            }
1274
+        }
1275
+        return $run;
1276
+    }
1277
+
1278
+    /**
1279
+     * check if a file or folder has been updated since $time
1280
+     *
1281
+     * @param string $path
1282
+     * @param int $time
1283
+     * @return bool
1284
+     */
1285
+    public function hasUpdated($path, $time) {
1286
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1287
+    }
1288
+
1289
+    /**
1290
+     * @param string $ownerId
1291
+     * @return \OC\User\User
1292
+     */
1293
+    private function getUserObjectForOwner($ownerId) {
1294
+        $owner = $this->userManager->get($ownerId);
1295
+        if ($owner instanceof IUser) {
1296
+            return $owner;
1297
+        } else {
1298
+            return new User($ownerId, null);
1299
+        }
1300
+    }
1301
+
1302
+    /**
1303
+     * Get file info from cache
1304
+     *
1305
+     * If the file is not in cached it will be scanned
1306
+     * If the file has changed on storage the cache will be updated
1307
+     *
1308
+     * @param \OC\Files\Storage\Storage $storage
1309
+     * @param string $internalPath
1310
+     * @param string $relativePath
1311
+     * @return ICacheEntry|bool
1312
+     */
1313
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1314
+        $cache = $storage->getCache($internalPath);
1315
+        $data = $cache->get($internalPath);
1316
+        $watcher = $storage->getWatcher($internalPath);
1317
+
1318
+        try {
1319
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1320
+            if (!$data || $data['size'] === -1) {
1321
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1322
+                if (!$storage->file_exists($internalPath)) {
1323
+                    $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1324
+                    return false;
1325
+                }
1326
+                $scanner = $storage->getScanner($internalPath);
1327
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1328
+                $data = $cache->get($internalPath);
1329
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1330
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1331
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1332
+                $watcher->update($internalPath, $data);
1333
+                $storage->getPropagator()->propagateChange($internalPath, time());
1334
+                $data = $cache->get($internalPath);
1335
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1336
+            }
1337
+        } catch (LockedException $e) {
1338
+            // if the file is locked we just use the old cache info
1339
+        }
1340
+
1341
+        return $data;
1342
+    }
1343
+
1344
+    /**
1345
+     * get the filesystem info
1346
+     *
1347
+     * @param string $path
1348
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1349
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1350
+     * defaults to true
1351
+     * @return \OC\Files\FileInfo|false False if file does not exist
1352
+     */
1353
+    public function getFileInfo($path, $includeMountPoints = true) {
1354
+        $this->assertPathLength($path);
1355
+        if (!Filesystem::isValidPath($path)) {
1356
+            return false;
1357
+        }
1358
+        if (Cache\Scanner::isPartialFile($path)) {
1359
+            return $this->getPartFileInfo($path);
1360
+        }
1361
+        $relativePath = $path;
1362
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1363
+
1364
+        $mount = Filesystem::getMountManager()->find($path);
1365
+        if (!$mount) {
1366
+            return false;
1367
+        }
1368
+        $storage = $mount->getStorage();
1369
+        $internalPath = $mount->getInternalPath($path);
1370
+        if ($storage) {
1371
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1372
+
1373
+            if (!$data instanceof ICacheEntry) {
1374
+                return false;
1375
+            }
1376
+
1377
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1378
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1379
+            }
1380
+
1381
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1382
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1383
+
1384
+            if ($data and isset($data['fileid'])) {
1385
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1386
+                    //add the sizes of other mount points to the folder
1387
+                    $extOnly = ($includeMountPoints === 'ext');
1388
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1389
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1390
+                        $subStorage = $mount->getStorage();
1391
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1392
+                    }));
1393
+                }
1394
+            }
1395
+
1396
+            return $info;
1397
+        }
1398
+
1399
+        return false;
1400
+    }
1401
+
1402
+    /**
1403
+     * get the content of a directory
1404
+     *
1405
+     * @param string $directory path under datadirectory
1406
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1407
+     * @return FileInfo[]
1408
+     */
1409
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1410
+        $this->assertPathLength($directory);
1411
+        if (!Filesystem::isValidPath($directory)) {
1412
+            return [];
1413
+        }
1414
+        $path = $this->getAbsolutePath($directory);
1415
+        $path = Filesystem::normalizePath($path);
1416
+        $mount = $this->getMount($directory);
1417
+        if (!$mount) {
1418
+            return [];
1419
+        }
1420
+        $storage = $mount->getStorage();
1421
+        $internalPath = $mount->getInternalPath($path);
1422
+        if ($storage) {
1423
+            $cache = $storage->getCache($internalPath);
1424
+            $user = \OC_User::getUser();
1425
+
1426
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1427
+
1428
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1429
+                return [];
1430
+            }
1431
+
1432
+            $folderId = $data['fileid'];
1433
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1434
+
1435
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1436
+            /**
1437
+             * @var \OC\Files\FileInfo[] $files
1438
+             */
1439
+            $files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1440
+                if ($sharingDisabled) {
1441
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1442
+                }
1443
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1444
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1445
+            }, $contents);
1446
+
1447
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1448
+            $mounts = Filesystem::getMountManager()->findIn($path);
1449
+            $dirLength = strlen($path);
1450
+            foreach ($mounts as $mount) {
1451
+                $mountPoint = $mount->getMountPoint();
1452
+                $subStorage = $mount->getStorage();
1453
+                if ($subStorage) {
1454
+                    $subCache = $subStorage->getCache('');
1455
+
1456
+                    $rootEntry = $subCache->get('');
1457
+                    if (!$rootEntry) {
1458
+                        $subScanner = $subStorage->getScanner('');
1459
+                        try {
1460
+                            $subScanner->scanFile('');
1461
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1462
+                            continue;
1463
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1464
+                            continue;
1465
+                        } catch (\Exception $e) {
1466
+                            // sometimes when the storage is not available it can be any exception
1467
+                            \OCP\Util::writeLog(
1468
+                                'core',
1469
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1470
+                                get_class($e) . ': ' . $e->getMessage(),
1471
+                                \OCP\Util::ERROR
1472
+                            );
1473
+                            continue;
1474
+                        }
1475
+                        $rootEntry = $subCache->get('');
1476
+                    }
1477
+
1478
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1479
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1480
+                        if ($pos = strpos($relativePath, '/')) {
1481
+                            //mountpoint inside subfolder add size to the correct folder
1482
+                            $entryName = substr($relativePath, 0, $pos);
1483
+                            foreach ($files as &$entry) {
1484
+                                if ($entry->getName() === $entryName) {
1485
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1486
+                                }
1487
+                            }
1488
+                        } else { //mountpoint in this folder, add an entry for it
1489
+                            $rootEntry['name'] = $relativePath;
1490
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1491
+                            $permissions = $rootEntry['permissions'];
1492
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1493
+                            // for shared files/folders we use the permissions given by the owner
1494
+                            if ($mount instanceof MoveableMount) {
1495
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1496
+                            } else {
1497
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1498
+                            }
1499
+
1500
+                            //remove any existing entry with the same name
1501
+                            foreach ($files as $i => $file) {
1502
+                                if ($file['name'] === $rootEntry['name']) {
1503
+                                    unset($files[$i]);
1504
+                                    break;
1505
+                                }
1506
+                            }
1507
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1508
+
1509
+                            // if sharing was disabled for the user we remove the share permissions
1510
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1511
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1512
+                            }
1513
+
1514
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1515
+                            $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1516
+                        }
1517
+                    }
1518
+                }
1519
+            }
1520
+
1521
+            if ($mimetype_filter) {
1522
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1523
+                    if (strpos($mimetype_filter, '/')) {
1524
+                        return $file->getMimetype() === $mimetype_filter;
1525
+                    } else {
1526
+                        return $file->getMimePart() === $mimetype_filter;
1527
+                    }
1528
+                });
1529
+            }
1530
+
1531
+            return $files;
1532
+        } else {
1533
+            return [];
1534
+        }
1535
+    }
1536
+
1537
+    /**
1538
+     * change file metadata
1539
+     *
1540
+     * @param string $path
1541
+     * @param array|\OCP\Files\FileInfo $data
1542
+     * @return int
1543
+     *
1544
+     * returns the fileid of the updated file
1545
+     */
1546
+    public function putFileInfo($path, $data) {
1547
+        $this->assertPathLength($path);
1548
+        if ($data instanceof FileInfo) {
1549
+            $data = $data->getData();
1550
+        }
1551
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1552
+        /**
1553
+         * @var \OC\Files\Storage\Storage $storage
1554
+         * @var string $internalPath
1555
+         */
1556
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1557
+        if ($storage) {
1558
+            $cache = $storage->getCache($path);
1559
+
1560
+            if (!$cache->inCache($internalPath)) {
1561
+                $scanner = $storage->getScanner($internalPath);
1562
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1563
+            }
1564
+
1565
+            return $cache->put($internalPath, $data);
1566
+        } else {
1567
+            return -1;
1568
+        }
1569
+    }
1570
+
1571
+    /**
1572
+     * search for files with the name matching $query
1573
+     *
1574
+     * @param string $query
1575
+     * @return FileInfo[]
1576
+     */
1577
+    public function search($query) {
1578
+        return $this->searchCommon('search', array('%' . $query . '%'));
1579
+    }
1580
+
1581
+    /**
1582
+     * search for files with the name matching $query
1583
+     *
1584
+     * @param string $query
1585
+     * @return FileInfo[]
1586
+     */
1587
+    public function searchRaw($query) {
1588
+        return $this->searchCommon('search', array($query));
1589
+    }
1590
+
1591
+    /**
1592
+     * search for files by mimetype
1593
+     *
1594
+     * @param string $mimetype
1595
+     * @return FileInfo[]
1596
+     */
1597
+    public function searchByMime($mimetype) {
1598
+        return $this->searchCommon('searchByMime', array($mimetype));
1599
+    }
1600
+
1601
+    /**
1602
+     * search for files by tag
1603
+     *
1604
+     * @param string|int $tag name or tag id
1605
+     * @param string $userId owner of the tags
1606
+     * @return FileInfo[]
1607
+     */
1608
+    public function searchByTag($tag, $userId) {
1609
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1610
+    }
1611
+
1612
+    /**
1613
+     * @param string $method cache method
1614
+     * @param array $args
1615
+     * @return FileInfo[]
1616
+     */
1617
+    private function searchCommon($method, $args) {
1618
+        $files = array();
1619
+        $rootLength = strlen($this->fakeRoot);
1620
+
1621
+        $mount = $this->getMount('');
1622
+        $mountPoint = $mount->getMountPoint();
1623
+        $storage = $mount->getStorage();
1624
+        if ($storage) {
1625
+            $cache = $storage->getCache('');
1626
+
1627
+            $results = call_user_func_array(array($cache, $method), $args);
1628
+            foreach ($results as $result) {
1629
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1630
+                    $internalPath = $result['path'];
1631
+                    $path = $mountPoint . $result['path'];
1632
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1633
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1634
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1635
+                }
1636
+            }
1637
+
1638
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1639
+            foreach ($mounts as $mount) {
1640
+                $mountPoint = $mount->getMountPoint();
1641
+                $storage = $mount->getStorage();
1642
+                if ($storage) {
1643
+                    $cache = $storage->getCache('');
1644
+
1645
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1646
+                    $results = call_user_func_array(array($cache, $method), $args);
1647
+                    if ($results) {
1648
+                        foreach ($results as $result) {
1649
+                            $internalPath = $result['path'];
1650
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1651
+                            $path = rtrim($mountPoint . $internalPath, '/');
1652
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1653
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1654
+                        }
1655
+                    }
1656
+                }
1657
+            }
1658
+        }
1659
+        return $files;
1660
+    }
1661
+
1662
+    /**
1663
+     * Get the owner for a file or folder
1664
+     *
1665
+     * @param string $path
1666
+     * @return string the user id of the owner
1667
+     * @throws NotFoundException
1668
+     */
1669
+    public function getOwner($path) {
1670
+        $info = $this->getFileInfo($path);
1671
+        if (!$info) {
1672
+            throw new NotFoundException($path . ' not found while trying to get owner');
1673
+        }
1674
+        return $info->getOwner()->getUID();
1675
+    }
1676
+
1677
+    /**
1678
+     * get the ETag for a file or folder
1679
+     *
1680
+     * @param string $path
1681
+     * @return string
1682
+     */
1683
+    public function getETag($path) {
1684
+        /**
1685
+         * @var Storage\Storage $storage
1686
+         * @var string $internalPath
1687
+         */
1688
+        list($storage, $internalPath) = $this->resolvePath($path);
1689
+        if ($storage) {
1690
+            return $storage->getETag($internalPath);
1691
+        } else {
1692
+            return null;
1693
+        }
1694
+    }
1695
+
1696
+    /**
1697
+     * Get the path of a file by id, relative to the view
1698
+     *
1699
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1700
+     *
1701
+     * @param int $id
1702
+     * @throws NotFoundException
1703
+     * @return string
1704
+     */
1705
+    public function getPath($id) {
1706
+        $id = (int)$id;
1707
+        $manager = Filesystem::getMountManager();
1708
+        $mounts = $manager->findIn($this->fakeRoot);
1709
+        $mounts[] = $manager->find($this->fakeRoot);
1710
+        // reverse the array so we start with the storage this view is in
1711
+        // which is the most likely to contain the file we're looking for
1712
+        $mounts = array_reverse($mounts);
1713
+        foreach ($mounts as $mount) {
1714
+            /**
1715
+             * @var \OC\Files\Mount\MountPoint $mount
1716
+             */
1717
+            if ($mount->getStorage()) {
1718
+                $cache = $mount->getStorage()->getCache();
1719
+                $internalPath = $cache->getPathById($id);
1720
+                if (is_string($internalPath)) {
1721
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1722
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1723
+                        return $path;
1724
+                    }
1725
+                }
1726
+            }
1727
+        }
1728
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1729
+    }
1730
+
1731
+    /**
1732
+     * @param string $path
1733
+     * @throws InvalidPathException
1734
+     */
1735
+    private function assertPathLength($path) {
1736
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1737
+        // Check for the string length - performed using isset() instead of strlen()
1738
+        // because isset() is about 5x-40x faster.
1739
+        if (isset($path[$maxLen])) {
1740
+            $pathLen = strlen($path);
1741
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1742
+        }
1743
+    }
1744
+
1745
+    /**
1746
+     * check if it is allowed to move a mount point to a given target.
1747
+     * It is not allowed to move a mount point into a different mount point or
1748
+     * into an already shared folder
1749
+     *
1750
+     * @param string $target path
1751
+     * @return boolean
1752
+     */
1753
+    private function isTargetAllowed($target) {
1754
+
1755
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1756
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1757
+            \OCP\Util::writeLog('files',
1758
+                'It is not allowed to move one mount point into another one',
1759
+                \OCP\Util::DEBUG);
1760
+            return false;
1761
+        }
1762
+
1763
+        // note: cannot use the view because the target is already locked
1764
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1765
+        if ($fileId === -1) {
1766
+            // target might not exist, need to check parent instead
1767
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1768
+        }
1769
+
1770
+        // check if any of the parents were shared by the current owner (include collections)
1771
+        $shares = \OCP\Share::getItemShared(
1772
+            'folder',
1773
+            $fileId,
1774
+            \OCP\Share::FORMAT_NONE,
1775
+            null,
1776
+            true
1777
+        );
1778
+
1779
+        if (count($shares) > 0) {
1780
+            \OCP\Util::writeLog('files',
1781
+                'It is not allowed to move one mount point into a shared folder',
1782
+                \OCP\Util::DEBUG);
1783
+            return false;
1784
+        }
1785
+
1786
+        return true;
1787
+    }
1788
+
1789
+    /**
1790
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1791
+     *
1792
+     * @param string $path
1793
+     * @return \OCP\Files\FileInfo
1794
+     */
1795
+    private function getPartFileInfo($path) {
1796
+        $mount = $this->getMount($path);
1797
+        $storage = $mount->getStorage();
1798
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1799
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1800
+        return new FileInfo(
1801
+            $this->getAbsolutePath($path),
1802
+            $storage,
1803
+            $internalPath,
1804
+            [
1805
+                'fileid' => null,
1806
+                'mimetype' => $storage->getMimeType($internalPath),
1807
+                'name' => basename($path),
1808
+                'etag' => null,
1809
+                'size' => $storage->filesize($internalPath),
1810
+                'mtime' => $storage->filemtime($internalPath),
1811
+                'encrypted' => false,
1812
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1813
+            ],
1814
+            $mount,
1815
+            $owner
1816
+        );
1817
+    }
1818
+
1819
+    /**
1820
+     * @param string $path
1821
+     * @param string $fileName
1822
+     * @throws InvalidPathException
1823
+     */
1824
+    public function verifyPath($path, $fileName) {
1825
+        try {
1826
+            /** @type \OCP\Files\Storage $storage */
1827
+            list($storage, $internalPath) = $this->resolvePath($path);
1828
+            $storage->verifyPath($internalPath, $fileName);
1829
+        } catch (ReservedWordException $ex) {
1830
+            $l = \OC::$server->getL10N('lib');
1831
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1832
+        } catch (InvalidCharacterInPathException $ex) {
1833
+            $l = \OC::$server->getL10N('lib');
1834
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1835
+        } catch (FileNameTooLongException $ex) {
1836
+            $l = \OC::$server->getL10N('lib');
1837
+            throw new InvalidPathException($l->t('File name is too long'));
1838
+        } catch (InvalidDirectoryException $ex) {
1839
+            $l = \OC::$server->getL10N('lib');
1840
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1841
+        } catch (EmptyFileNameException $ex) {
1842
+            $l = \OC::$server->getL10N('lib');
1843
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1844
+        }
1845
+    }
1846
+
1847
+    /**
1848
+     * get all parent folders of $path
1849
+     *
1850
+     * @param string $path
1851
+     * @return string[]
1852
+     */
1853
+    private function getParents($path) {
1854
+        $path = trim($path, '/');
1855
+        if (!$path) {
1856
+            return [];
1857
+        }
1858
+
1859
+        $parts = explode('/', $path);
1860
+
1861
+        // remove the single file
1862
+        array_pop($parts);
1863
+        $result = array('/');
1864
+        $resultPath = '';
1865
+        foreach ($parts as $part) {
1866
+            if ($part) {
1867
+                $resultPath .= '/' . $part;
1868
+                $result[] = $resultPath;
1869
+            }
1870
+        }
1871
+        return $result;
1872
+    }
1873
+
1874
+    /**
1875
+     * Returns the mount point for which to lock
1876
+     *
1877
+     * @param string $absolutePath absolute path
1878
+     * @param bool $useParentMount true to return parent mount instead of whatever
1879
+     * is mounted directly on the given path, false otherwise
1880
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1881
+     */
1882
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1883
+        $results = [];
1884
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1885
+        if (!$mount) {
1886
+            return $results;
1887
+        }
1888
+
1889
+        if ($useParentMount) {
1890
+            // find out if something is mounted directly on the path
1891
+            $internalPath = $mount->getInternalPath($absolutePath);
1892
+            if ($internalPath === '') {
1893
+                // resolve the parent mount instead
1894
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1895
+            }
1896
+        }
1897
+
1898
+        return $mount;
1899
+    }
1900
+
1901
+    /**
1902
+     * Lock the given path
1903
+     *
1904
+     * @param string $path the path of the file to lock, relative to the view
1905
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1906
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1907
+     *
1908
+     * @return bool False if the path is excluded from locking, true otherwise
1909
+     * @throws \OCP\Lock\LockedException if the path is already locked
1910
+     */
1911
+    private function lockPath($path, $type, $lockMountPoint = false) {
1912
+        $absolutePath = $this->getAbsolutePath($path);
1913
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1914
+        if (!$this->shouldLockFile($absolutePath)) {
1915
+            return false;
1916
+        }
1917
+
1918
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1919
+        if ($mount) {
1920
+            try {
1921
+                $storage = $mount->getStorage();
1922
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1923
+                    $storage->acquireLock(
1924
+                        $mount->getInternalPath($absolutePath),
1925
+                        $type,
1926
+                        $this->lockingProvider
1927
+                    );
1928
+                }
1929
+            } catch (\OCP\Lock\LockedException $e) {
1930
+                // rethrow with the a human-readable path
1931
+                throw new \OCP\Lock\LockedException(
1932
+                    $this->getPathRelativeToFiles($absolutePath),
1933
+                    $e
1934
+                );
1935
+            }
1936
+        }
1937
+
1938
+        return true;
1939
+    }
1940
+
1941
+    /**
1942
+     * Change the lock type
1943
+     *
1944
+     * @param string $path the path of the file to lock, relative to the view
1945
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1946
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1947
+     *
1948
+     * @return bool False if the path is excluded from locking, true otherwise
1949
+     * @throws \OCP\Lock\LockedException if the path is already locked
1950
+     */
1951
+    public function changeLock($path, $type, $lockMountPoint = false) {
1952
+        $path = Filesystem::normalizePath($path);
1953
+        $absolutePath = $this->getAbsolutePath($path);
1954
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1955
+        if (!$this->shouldLockFile($absolutePath)) {
1956
+            return false;
1957
+        }
1958
+
1959
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1960
+        if ($mount) {
1961
+            try {
1962
+                $storage = $mount->getStorage();
1963
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1964
+                    $storage->changeLock(
1965
+                        $mount->getInternalPath($absolutePath),
1966
+                        $type,
1967
+                        $this->lockingProvider
1968
+                    );
1969
+                }
1970
+            } catch (\OCP\Lock\LockedException $e) {
1971
+                try {
1972
+                    // rethrow with the a human-readable path
1973
+                    throw new \OCP\Lock\LockedException(
1974
+                        $this->getPathRelativeToFiles($absolutePath),
1975
+                        $e
1976
+                    );
1977
+                } catch (\InvalidArgumentException $e) {
1978
+                    throw new \OCP\Lock\LockedException(
1979
+                        $absolutePath,
1980
+                        $e
1981
+                    );
1982
+                }
1983
+            }
1984
+        }
1985
+
1986
+        return true;
1987
+    }
1988
+
1989
+    /**
1990
+     * Unlock the given path
1991
+     *
1992
+     * @param string $path the path of the file to unlock, relative to the view
1993
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1994
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1995
+     *
1996
+     * @return bool False if the path is excluded from locking, true otherwise
1997
+     */
1998
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1999
+        $absolutePath = $this->getAbsolutePath($path);
2000
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2001
+        if (!$this->shouldLockFile($absolutePath)) {
2002
+            return false;
2003
+        }
2004
+
2005
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2006
+        if ($mount) {
2007
+            $storage = $mount->getStorage();
2008
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2009
+                $storage->releaseLock(
2010
+                    $mount->getInternalPath($absolutePath),
2011
+                    $type,
2012
+                    $this->lockingProvider
2013
+                );
2014
+            }
2015
+        }
2016
+
2017
+        return true;
2018
+    }
2019
+
2020
+    /**
2021
+     * Lock a path and all its parents up to the root of the view
2022
+     *
2023
+     * @param string $path the path of the file to lock relative to the view
2024
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2025
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2026
+     *
2027
+     * @return bool False if the path is excluded from locking, true otherwise
2028
+     */
2029
+    public function lockFile($path, $type, $lockMountPoint = false) {
2030
+        $absolutePath = $this->getAbsolutePath($path);
2031
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2032
+        if (!$this->shouldLockFile($absolutePath)) {
2033
+            return false;
2034
+        }
2035
+
2036
+        $this->lockPath($path, $type, $lockMountPoint);
2037
+
2038
+        $parents = $this->getParents($path);
2039
+        foreach ($parents as $parent) {
2040
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2041
+        }
2042
+
2043
+        return true;
2044
+    }
2045
+
2046
+    /**
2047
+     * Unlock a path and all its parents up to the root of the view
2048
+     *
2049
+     * @param string $path the path of the file to lock relative to the view
2050
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
+     *
2053
+     * @return bool False if the path is excluded from locking, true otherwise
2054
+     */
2055
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2056
+        $absolutePath = $this->getAbsolutePath($path);
2057
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2058
+        if (!$this->shouldLockFile($absolutePath)) {
2059
+            return false;
2060
+        }
2061
+
2062
+        $this->unlockPath($path, $type, $lockMountPoint);
2063
+
2064
+        $parents = $this->getParents($path);
2065
+        foreach ($parents as $parent) {
2066
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2067
+        }
2068
+
2069
+        return true;
2070
+    }
2071
+
2072
+    /**
2073
+     * Only lock files in data/user/files/
2074
+     *
2075
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2076
+     * @return bool
2077
+     */
2078
+    protected function shouldLockFile($path) {
2079
+        $path = Filesystem::normalizePath($path);
2080
+
2081
+        $pathSegments = explode('/', $path);
2082
+        if (isset($pathSegments[2])) {
2083
+            // E.g.: /username/files/path-to-file
2084
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2085
+        }
2086
+
2087
+        return strpos($path, '/appdata_') !== 0;
2088
+    }
2089
+
2090
+    /**
2091
+     * Shortens the given absolute path to be relative to
2092
+     * "$user/files".
2093
+     *
2094
+     * @param string $absolutePath absolute path which is under "files"
2095
+     *
2096
+     * @return string path relative to "files" with trimmed slashes or null
2097
+     * if the path was NOT relative to files
2098
+     *
2099
+     * @throws \InvalidArgumentException if the given path was not under "files"
2100
+     * @since 8.1.0
2101
+     */
2102
+    public function getPathRelativeToFiles($absolutePath) {
2103
+        $path = Filesystem::normalizePath($absolutePath);
2104
+        $parts = explode('/', trim($path, '/'), 3);
2105
+        // "$user", "files", "path/to/dir"
2106
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2107
+            $this->logger->error(
2108
+                '$absolutePath must be relative to "files", value is "%s"',
2109
+                [
2110
+                    $absolutePath
2111
+                ]
2112
+            );
2113
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2114
+        }
2115
+        if (isset($parts[2])) {
2116
+            return $parts[2];
2117
+        }
2118
+        return '';
2119
+    }
2120
+
2121
+    /**
2122
+     * @param string $filename
2123
+     * @return array
2124
+     * @throws \OC\User\NoUserException
2125
+     * @throws NotFoundException
2126
+     */
2127
+    public function getUidAndFilename($filename) {
2128
+        $info = $this->getFileInfo($filename);
2129
+        if (!$info instanceof \OCP\Files\FileInfo) {
2130
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2131
+        }
2132
+        $uid = $info->getOwner()->getUID();
2133
+        if ($uid != \OCP\User::getUser()) {
2134
+            Filesystem::initMountPoints($uid);
2135
+            $ownerView = new View('/' . $uid . '/files');
2136
+            try {
2137
+                $filename = $ownerView->getPath($info['fileid']);
2138
+            } catch (NotFoundException $e) {
2139
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2140
+            }
2141
+        }
2142
+        return [$uid, $filename];
2143
+    }
2144
+
2145
+    /**
2146
+     * Creates parent non-existing folders
2147
+     *
2148
+     * @param string $filePath
2149
+     * @return bool
2150
+     */
2151
+    private function createParentDirectories($filePath) {
2152
+        $directoryParts = explode('/', $filePath);
2153
+        $directoryParts = array_filter($directoryParts);
2154
+        foreach ($directoryParts as $key => $part) {
2155
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2156
+            $currentPath = '/' . implode('/', $currentPathElements);
2157
+            if ($this->is_file($currentPath)) {
2158
+                return false;
2159
+            }
2160
+            if (!$this->file_exists($currentPath)) {
2161
+                $this->mkdir($currentPath);
2162
+            }
2163
+        }
2164
+
2165
+        return true;
2166
+    }
2167 2167
 }
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -126,9 +126,9 @@  discard block
 block discarded – undo
126 126
 			$path = '/';
127 127
 		}
128 128
 		if ($path[0] !== '/') {
129
-			$path = '/' . $path;
129
+			$path = '/'.$path;
130 130
 		}
131
-		return $this->fakeRoot . $path;
131
+		return $this->fakeRoot.$path;
132 132
 	}
133 133
 
134 134
 	/**
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 	public function chroot($fakeRoot) {
141 141
 		if (!$fakeRoot == '') {
142 142
 			if ($fakeRoot[0] !== '/') {
143
-				$fakeRoot = '/' . $fakeRoot;
143
+				$fakeRoot = '/'.$fakeRoot;
144 144
 			}
145 145
 		}
146 146
 		$this->fakeRoot = $fakeRoot;
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		}
173 173
 
174 174
 		// missing slashes can cause wrong matches!
175
-		$root = rtrim($this->fakeRoot, '/') . '/';
175
+		$root = rtrim($this->fakeRoot, '/').'/';
176 176
 
177 177
 		if (strpos($path, $root) !== 0) {
178 178
 			return null;
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 		if ($mount instanceof MoveableMount) {
279 279
 			// cut of /user/files to get the relative path to data/user/files
280 280
 			$pathParts = explode('/', $path, 4);
281
-			$relPath = '/' . $pathParts[3];
281
+			$relPath = '/'.$pathParts[3];
282 282
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
283 283
 			\OC_Hook::emit(
284 284
 				Filesystem::CLASSNAME, "umount",
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
 		}
701 701
 		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
702 702
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
703
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
703
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
704 704
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
705 705
 			return $this->removeMount($mount, $absolutePath);
706 706
 		}
@@ -820,7 +820,7 @@  discard block
 block discarded – undo
820 820
 								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
821 821
 							}
822 822
 						}
823
-					} catch(\Exception $e) {
823
+					} catch (\Exception $e) {
824 824
 						throw $e;
825 825
 					} finally {
826 826
 						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
 						}
845 845
 					}
846 846
 				}
847
-			} catch(\Exception $e) {
847
+			} catch (\Exception $e) {
848 848
 				throw $e;
849 849
 			} finally {
850 850
 				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
@@ -977,7 +977,7 @@  discard block
 block discarded – undo
977 977
 				$hooks[] = 'write';
978 978
 				break;
979 979
 			default:
980
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
980
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, \OCP\Util::ERROR);
981 981
 		}
982 982
 
983 983
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1081,7 +1081,7 @@  discard block
 block discarded – undo
1081 1081
 					array(Filesystem::signal_param_path => $this->getHookPath($path))
1082 1082
 				);
1083 1083
 			}
1084
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1084
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1085 1085
 			if ($storage) {
1086 1086
 				$result = $storage->hash($type, $internalPath, $raw);
1087 1087
 				return $result;
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 
1137 1137
 			$run = $this->runHooks($hooks, $path);
1138 1138
 			/** @var \OC\Files\Storage\Storage $storage */
1139
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1139
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1140 1140
 			if ($run and $storage) {
1141 1141
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1142 1142
 					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
@@ -1175,7 +1175,7 @@  discard block
 block discarded – undo
1175 1175
 					$unlockLater = true;
1176 1176
 					// make sure our unlocking callback will still be called if connection is aborted
1177 1177
 					ignore_user_abort(true);
1178
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1178
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1179 1179
 						if (in_array('write', $hooks)) {
1180 1180
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1181 1181
 						} else if (in_array('read', $hooks)) {
@@ -1236,7 +1236,7 @@  discard block
 block discarded – undo
1236 1236
 			return true;
1237 1237
 		}
1238 1238
 
1239
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1239
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1240 1240
 	}
1241 1241
 
1242 1242
 	/**
@@ -1255,7 +1255,7 @@  discard block
 block discarded – undo
1255 1255
 				if ($hook != 'read') {
1256 1256
 					\OC_Hook::emit(
1257 1257
 						Filesystem::CLASSNAME,
1258
-						$prefix . $hook,
1258
+						$prefix.$hook,
1259 1259
 						array(
1260 1260
 							Filesystem::signal_param_run => &$run,
1261 1261
 							Filesystem::signal_param_path => $path
@@ -1264,7 +1264,7 @@  discard block
 block discarded – undo
1264 1264
 				} elseif (!$post) {
1265 1265
 					\OC_Hook::emit(
1266 1266
 						Filesystem::CLASSNAME,
1267
-						$prefix . $hook,
1267
+						$prefix.$hook,
1268 1268
 						array(
1269 1269
 							Filesystem::signal_param_path => $path
1270 1270
 						)
@@ -1359,7 +1359,7 @@  discard block
 block discarded – undo
1359 1359
 			return $this->getPartFileInfo($path);
1360 1360
 		}
1361 1361
 		$relativePath = $path;
1362
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1362
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1363 1363
 
1364 1364
 		$mount = Filesystem::getMountManager()->find($path);
1365 1365
 		if (!$mount) {
@@ -1386,7 +1386,7 @@  discard block
 block discarded – undo
1386 1386
 					//add the sizes of other mount points to the folder
1387 1387
 					$extOnly = ($includeMountPoints === 'ext');
1388 1388
 					$mounts = Filesystem::getMountManager()->findIn($path);
1389
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1389
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1390 1390
 						$subStorage = $mount->getStorage();
1391 1391
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1392 1392
 					}));
@@ -1436,12 +1436,12 @@  discard block
 block discarded – undo
1436 1436
 			/**
1437 1437
 			 * @var \OC\Files\FileInfo[] $files
1438 1438
 			 */
1439
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1439
+			$files = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1440 1440
 				if ($sharingDisabled) {
1441 1441
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1442 1442
 				}
1443 1443
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1444
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1444
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1445 1445
 			}, $contents);
1446 1446
 
1447 1447
 			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
@@ -1466,8 +1466,8 @@  discard block
 block discarded – undo
1466 1466
 							// sometimes when the storage is not available it can be any exception
1467 1467
 							\OCP\Util::writeLog(
1468 1468
 								'core',
1469
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1470
-								get_class($e) . ': ' . $e->getMessage(),
1469
+								'Exception while scanning storage "'.$subStorage->getId().'": '.
1470
+								get_class($e).': '.$e->getMessage(),
1471 1471
 								\OCP\Util::ERROR
1472 1472
 							);
1473 1473
 							continue;
@@ -1504,7 +1504,7 @@  discard block
 block discarded – undo
1504 1504
 									break;
1505 1505
 								}
1506 1506
 							}
1507
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1507
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1508 1508
 
1509 1509
 							// if sharing was disabled for the user we remove the share permissions
1510 1510
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1512,14 +1512,14 @@  discard block
 block discarded – undo
1512 1512
 							}
1513 1513
 
1514 1514
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1515
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1515
+							$files[] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1516 1516
 						}
1517 1517
 					}
1518 1518
 				}
1519 1519
 			}
1520 1520
 
1521 1521
 			if ($mimetype_filter) {
1522
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1522
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1523 1523
 					if (strpos($mimetype_filter, '/')) {
1524 1524
 						return $file->getMimetype() === $mimetype_filter;
1525 1525
 					} else {
@@ -1548,7 +1548,7 @@  discard block
 block discarded – undo
1548 1548
 		if ($data instanceof FileInfo) {
1549 1549
 			$data = $data->getData();
1550 1550
 		}
1551
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1551
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1552 1552
 		/**
1553 1553
 		 * @var \OC\Files\Storage\Storage $storage
1554 1554
 		 * @var string $internalPath
@@ -1575,7 +1575,7 @@  discard block
 block discarded – undo
1575 1575
 	 * @return FileInfo[]
1576 1576
 	 */
1577 1577
 	public function search($query) {
1578
-		return $this->searchCommon('search', array('%' . $query . '%'));
1578
+		return $this->searchCommon('search', array('%'.$query.'%'));
1579 1579
 	}
1580 1580
 
1581 1581
 	/**
@@ -1626,10 +1626,10 @@  discard block
 block discarded – undo
1626 1626
 
1627 1627
 			$results = call_user_func_array(array($cache, $method), $args);
1628 1628
 			foreach ($results as $result) {
1629
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1629
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1630 1630
 					$internalPath = $result['path'];
1631
-					$path = $mountPoint . $result['path'];
1632
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1631
+					$path = $mountPoint.$result['path'];
1632
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1633 1633
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1634 1634
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1635 1635
 				}
@@ -1647,8 +1647,8 @@  discard block
 block discarded – undo
1647 1647
 					if ($results) {
1648 1648
 						foreach ($results as $result) {
1649 1649
 							$internalPath = $result['path'];
1650
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1651
-							$path = rtrim($mountPoint . $internalPath, '/');
1650
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1651
+							$path = rtrim($mountPoint.$internalPath, '/');
1652 1652
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1653 1653
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1654 1654
 						}
@@ -1669,7 +1669,7 @@  discard block
 block discarded – undo
1669 1669
 	public function getOwner($path) {
1670 1670
 		$info = $this->getFileInfo($path);
1671 1671
 		if (!$info) {
1672
-			throw new NotFoundException($path . ' not found while trying to get owner');
1672
+			throw new NotFoundException($path.' not found while trying to get owner');
1673 1673
 		}
1674 1674
 		return $info->getOwner()->getUID();
1675 1675
 	}
@@ -1703,7 +1703,7 @@  discard block
 block discarded – undo
1703 1703
 	 * @return string
1704 1704
 	 */
1705 1705
 	public function getPath($id) {
1706
-		$id = (int)$id;
1706
+		$id = (int) $id;
1707 1707
 		$manager = Filesystem::getMountManager();
1708 1708
 		$mounts = $manager->findIn($this->fakeRoot);
1709 1709
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1718,7 +1718,7 @@  discard block
 block discarded – undo
1718 1718
 				$cache = $mount->getStorage()->getCache();
1719 1719
 				$internalPath = $cache->getPathById($id);
1720 1720
 				if (is_string($internalPath)) {
1721
-					$fullPath = $mount->getMountPoint() . $internalPath;
1721
+					$fullPath = $mount->getMountPoint().$internalPath;
1722 1722
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1723 1723
 						return $path;
1724 1724
 					}
@@ -1761,10 +1761,10 @@  discard block
 block discarded – undo
1761 1761
 		}
1762 1762
 
1763 1763
 		// note: cannot use the view because the target is already locked
1764
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1764
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1765 1765
 		if ($fileId === -1) {
1766 1766
 			// target might not exist, need to check parent instead
1767
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1767
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1768 1768
 		}
1769 1769
 
1770 1770
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1864,7 +1864,7 @@  discard block
 block discarded – undo
1864 1864
 		$resultPath = '';
1865 1865
 		foreach ($parts as $part) {
1866 1866
 			if ($part) {
1867
-				$resultPath .= '/' . $part;
1867
+				$resultPath .= '/'.$part;
1868 1868
 				$result[] = $resultPath;
1869 1869
 			}
1870 1870
 		}
@@ -2127,16 +2127,16 @@  discard block
 block discarded – undo
2127 2127
 	public function getUidAndFilename($filename) {
2128 2128
 		$info = $this->getFileInfo($filename);
2129 2129
 		if (!$info instanceof \OCP\Files\FileInfo) {
2130
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2130
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2131 2131
 		}
2132 2132
 		$uid = $info->getOwner()->getUID();
2133 2133
 		if ($uid != \OCP\User::getUser()) {
2134 2134
 			Filesystem::initMountPoints($uid);
2135
-			$ownerView = new View('/' . $uid . '/files');
2135
+			$ownerView = new View('/'.$uid.'/files');
2136 2136
 			try {
2137 2137
 				$filename = $ownerView->getPath($info['fileid']);
2138 2138
 			} catch (NotFoundException $e) {
2139
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2139
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2140 2140
 			}
2141 2141
 		}
2142 2142
 		return [$uid, $filename];
@@ -2153,7 +2153,7 @@  discard block
 block discarded – undo
2153 2153
 		$directoryParts = array_filter($directoryParts);
2154 2154
 		foreach ($directoryParts as $key => $part) {
2155 2155
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2156
-			$currentPath = '/' . implode('/', $currentPathElements);
2156
+			$currentPath = '/'.implode('/', $currentPathElements);
2157 2157
 			if ($this->is_file($currentPath)) {
2158 2158
 				return false;
2159 2159
 			}
Please login to merge, or discard this patch.