Completed
Pull Request — master (#6779)
by Blizzz
11:42
created
lib/private/legacy/app.php 1 patch
Indentation   +1206 added lines, -1206 removed lines patch added patch discarded remove patch
@@ -61,1210 +61,1210 @@
 block discarded – undo
61 61
  * upgrading and removing apps.
62 62
  */
63 63
 class OC_App {
64
-	static private $appVersion = [];
65
-	static private $adminForms = array();
66
-	static private $personalForms = array();
67
-	static private $appInfo = array();
68
-	static private $appTypes = array();
69
-	static private $loadedApps = array();
70
-	static private $altLogin = array();
71
-	static private $alreadyRegistered = [];
72
-	const officialApp = 200;
73
-
74
-	/**
75
-	 * clean the appId
76
-	 *
77
-	 * @param string|boolean $app AppId that needs to be cleaned
78
-	 * @return string
79
-	 */
80
-	public static function cleanAppId($app) {
81
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
-	}
83
-
84
-	/**
85
-	 * Check if an app is loaded
86
-	 *
87
-	 * @param string $app
88
-	 * @return bool
89
-	 */
90
-	public static function isAppLoaded($app) {
91
-		return in_array($app, self::$loadedApps, true);
92
-	}
93
-
94
-	/**
95
-	 * loads all apps
96
-	 *
97
-	 * @param string[] | string | null $types
98
-	 * @return bool
99
-	 *
100
-	 * This function walks through the ownCloud directory and loads all apps
101
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
102
-	 * exists.
103
-	 *
104
-	 * if $types is set, only apps of those types will be loaded
105
-	 */
106
-	public static function loadApps($types = null) {
107
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
-			return false;
109
-		}
110
-		// Load the enabled apps here
111
-		$apps = self::getEnabledApps();
112
-
113
-		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
115
-			$path = self::getAppPath($app);
116
-			if($path !== false) {
117
-				self::registerAutoloading($app, $path);
118
-			}
119
-		}
120
-
121
-		// prevent app.php from printing output
122
-		ob_start();
123
-		foreach ($apps as $app) {
124
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
-				self::loadApp($app);
126
-			}
127
-		}
128
-		ob_end_clean();
129
-
130
-		return true;
131
-	}
132
-
133
-	/**
134
-	 * load a single app
135
-	 *
136
-	 * @param string $app
137
-	 */
138
-	public static function loadApp($app) {
139
-		self::$loadedApps[] = $app;
140
-		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
142
-			return;
143
-		}
144
-
145
-		// in case someone calls loadApp() directly
146
-		self::registerAutoloading($app, $appPath);
147
-
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
-			self::requireAppFile($app);
151
-			if (self::isType($app, array('authentication'))) {
152
-				// since authentication apps affect the "is app enabled for group" check,
153
-				// the enabled apps cache needs to be cleared to make sure that the
154
-				// next time getEnableApps() is called it will also include apps that were
155
-				// enabled for groups
156
-				self::$enabledAppsCache = array();
157
-			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
159
-		}
160
-
161
-		$info = self::getAppInfo($app);
162
-		if (!empty($info['activity']['filters'])) {
163
-			foreach ($info['activity']['filters'] as $filter) {
164
-				\OC::$server->getActivityManager()->registerFilter($filter);
165
-			}
166
-		}
167
-		if (!empty($info['activity']['settings'])) {
168
-			foreach ($info['activity']['settings'] as $setting) {
169
-				\OC::$server->getActivityManager()->registerSetting($setting);
170
-			}
171
-		}
172
-		if (!empty($info['activity']['providers'])) {
173
-			foreach ($info['activity']['providers'] as $provider) {
174
-				\OC::$server->getActivityManager()->registerProvider($provider);
175
-			}
176
-		}
177
-		if (!empty($info['collaboration']['plugins'])) {
178
-			// deal with one or many plugin entries
179
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
180
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
181
-			foreach ($plugins as $plugin) {
182
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
183
-					$pluginInfo = [
184
-						'shareType' => $plugin['@attributes']['share-type'],
185
-						'class' => $plugin['@value'],
186
-					];
187
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
188
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
189
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
190
-				}
191
-			}
192
-		}
193
-	}
194
-
195
-	/**
196
-	 * @internal
197
-	 * @param string $app
198
-	 * @param string $path
199
-	 */
200
-	public static function registerAutoloading($app, $path) {
201
-		$key = $app . '-' . $path;
202
-		if(isset(self::$alreadyRegistered[$key])) {
203
-			return;
204
-		}
205
-
206
-		self::$alreadyRegistered[$key] = true;
207
-
208
-		// Register on PSR-4 composer autoloader
209
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
210
-		\OC::$server->registerNamespace($app, $appNamespace);
211
-
212
-		if (file_exists($path . '/composer/autoload.php')) {
213
-			require_once $path . '/composer/autoload.php';
214
-		} else {
215
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
216
-			// Register on legacy autoloader
217
-			\OC::$loader->addValidRoot($path);
218
-		}
219
-
220
-		// Register Test namespace only when testing
221
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
222
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
223
-		}
224
-	}
225
-
226
-	/**
227
-	 * Load app.php from the given app
228
-	 *
229
-	 * @param string $app app name
230
-	 */
231
-	private static function requireAppFile($app) {
232
-		try {
233
-			// encapsulated here to avoid variable scope conflicts
234
-			require_once $app . '/appinfo/app.php';
235
-		} catch (Error $ex) {
236
-			\OC::$server->getLogger()->logException($ex);
237
-			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
238
-			if (!in_array($app, $blacklist)) {
239
-				self::disable($app);
240
-			}
241
-		}
242
-	}
243
-
244
-	/**
245
-	 * check if an app is of a specific type
246
-	 *
247
-	 * @param string $app
248
-	 * @param string|array $types
249
-	 * @return bool
250
-	 */
251
-	public static function isType($app, $types) {
252
-		if (is_string($types)) {
253
-			$types = array($types);
254
-		}
255
-		$appTypes = self::getAppTypes($app);
256
-		foreach ($types as $type) {
257
-			if (array_search($type, $appTypes) !== false) {
258
-				return true;
259
-			}
260
-		}
261
-		return false;
262
-	}
263
-
264
-	/**
265
-	 * get the types of an app
266
-	 *
267
-	 * @param string $app
268
-	 * @return array
269
-	 */
270
-	private static function getAppTypes($app) {
271
-		//load the cache
272
-		if (count(self::$appTypes) == 0) {
273
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
274
-		}
275
-
276
-		if (isset(self::$appTypes[$app])) {
277
-			return explode(',', self::$appTypes[$app]);
278
-		} else {
279
-			return array();
280
-		}
281
-	}
282
-
283
-	/**
284
-	 * read app types from info.xml and cache them in the database
285
-	 */
286
-	public static function setAppTypes($app) {
287
-		$appData = self::getAppInfo($app);
288
-		if(!is_array($appData)) {
289
-			return;
290
-		}
291
-
292
-		if (isset($appData['types'])) {
293
-			$appTypes = implode(',', $appData['types']);
294
-		} else {
295
-			$appTypes = '';
296
-			$appData['types'] = [];
297
-		}
298
-
299
-		\OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
300
-
301
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
302
-			$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
303
-			if ($enabled !== 'yes' && $enabled !== 'no') {
304
-				\OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
305
-			}
306
-		}
307
-	}
308
-
309
-	/**
310
-	 * get all enabled apps
311
-	 */
312
-	protected static $enabledAppsCache = array();
313
-
314
-	/**
315
-	 * Returns apps enabled for the current user.
316
-	 *
317
-	 * @param bool $forceRefresh whether to refresh the cache
318
-	 * @param bool $all whether to return apps for all users, not only the
319
-	 * currently logged in one
320
-	 * @return string[]
321
-	 */
322
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
323
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
-			return array();
325
-		}
326
-		// in incognito mode or when logged out, $user will be false,
327
-		// which is also the case during an upgrade
328
-		$appManager = \OC::$server->getAppManager();
329
-		if ($all) {
330
-			$user = null;
331
-		} else {
332
-			$user = \OC::$server->getUserSession()->getUser();
333
-		}
334
-
335
-		if (is_null($user)) {
336
-			$apps = $appManager->getInstalledApps();
337
-		} else {
338
-			$apps = $appManager->getEnabledAppsForUser($user);
339
-		}
340
-		$apps = array_filter($apps, function ($app) {
341
-			return $app !== 'files';//we add this manually
342
-		});
343
-		sort($apps);
344
-		array_unshift($apps, 'files');
345
-		return $apps;
346
-	}
347
-
348
-	/**
349
-	 * checks whether or not an app is enabled
350
-	 *
351
-	 * @param string $app app
352
-	 * @return bool
353
-	 *
354
-	 * This function checks whether or not an app is enabled.
355
-	 */
356
-	public static function isEnabled($app) {
357
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
358
-	}
359
-
360
-	/**
361
-	 * enables an app
362
-	 *
363
-	 * @param string $appId
364
-	 * @param array $groups (optional) when set, only these groups will have access to the app
365
-	 * @throws \Exception
366
-	 * @return void
367
-	 *
368
-	 * This function set an app as enabled in appconfig.
369
-	 */
370
-	public function enable($appId,
371
-						   $groups = null) {
372
-		self::$enabledAppsCache = []; // flush
373
-
374
-		// Check if app is already downloaded
375
-		$installer = new Installer(
376
-			\OC::$server->getAppFetcher(),
377
-			\OC::$server->getHTTPClientService(),
378
-			\OC::$server->getTempManager(),
379
-			\OC::$server->getLogger(),
380
-			\OC::$server->getConfig()
381
-		);
382
-		$isDownloaded = $installer->isDownloaded($appId);
383
-
384
-		if(!$isDownloaded) {
385
-			$installer->downloadApp($appId);
386
-		}
387
-
388
-		$installer->installApp($appId);
389
-
390
-		$appManager = \OC::$server->getAppManager();
391
-		if (!is_null($groups)) {
392
-			$groupManager = \OC::$server->getGroupManager();
393
-			$groupsList = [];
394
-			foreach ($groups as $group) {
395
-				$groupItem = $groupManager->get($group);
396
-				if ($groupItem instanceof \OCP\IGroup) {
397
-					$groupsList[] = $groupManager->get($group);
398
-				}
399
-			}
400
-			$appManager->enableAppForGroups($appId, $groupsList);
401
-		} else {
402
-			$appManager->enableApp($appId);
403
-		}
404
-	}
405
-
406
-	/**
407
-	 * @param string $app
408
-	 * @return bool
409
-	 */
410
-	public static function removeApp($app) {
411
-		if (\OC::$server->getAppManager()->isShipped($app)) {
412
-			return false;
413
-		}
414
-
415
-		$installer = new Installer(
416
-			\OC::$server->getAppFetcher(),
417
-			\OC::$server->getHTTPClientService(),
418
-			\OC::$server->getTempManager(),
419
-			\OC::$server->getLogger(),
420
-			\OC::$server->getConfig()
421
-		);
422
-		return $installer->removeApp($app);
423
-	}
424
-
425
-	/**
426
-	 * This function set an app as disabled in appconfig.
427
-	 *
428
-	 * @param string $app app
429
-	 * @throws Exception
430
-	 */
431
-	public static function disable($app) {
432
-		// flush
433
-		self::$enabledAppsCache = array();
434
-
435
-		// run uninstall steps
436
-		$appData = OC_App::getAppInfo($app);
437
-		if (!is_null($appData)) {
438
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
439
-		}
440
-
441
-		// emit disable hook - needed anymore ?
442
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
443
-
444
-		// finally disable it
445
-		$appManager = \OC::$server->getAppManager();
446
-		$appManager->disableApp($app);
447
-	}
448
-
449
-	// This is private as well. It simply works, so don't ask for more details
450
-	private static function proceedNavigation($list) {
451
-		usort($list, function($a, $b) {
452
-			if (isset($a['order']) && isset($b['order'])) {
453
-				return ($a['order'] < $b['order']) ? -1 : 1;
454
-			} else if (isset($a['order']) || isset($b['order'])) {
455
-				return isset($a['order']) ? -1 : 1;
456
-			} else {
457
-				return ($a['name'] < $b['name']) ? -1 : 1;
458
-			}
459
-		});
460
-
461
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
462
-		foreach ($list as $index => &$navEntry) {
463
-			if ($navEntry['id'] == $activeApp) {
464
-				$navEntry['active'] = true;
465
-			} else {
466
-				$navEntry['active'] = false;
467
-			}
468
-		}
469
-		unset($navEntry);
470
-
471
-		return $list;
472
-	}
473
-
474
-	/**
475
-	 * Get the path where to install apps
476
-	 *
477
-	 * @return string|false
478
-	 */
479
-	public static function getInstallPath() {
480
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
481
-			return false;
482
-		}
483
-
484
-		foreach (OC::$APPSROOTS as $dir) {
485
-			if (isset($dir['writable']) && $dir['writable'] === true) {
486
-				return $dir['path'];
487
-			}
488
-		}
489
-
490
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
491
-		return null;
492
-	}
493
-
494
-
495
-	/**
496
-	 * search for an app in all app-directories
497
-	 *
498
-	 * @param string $appId
499
-	 * @return false|string
500
-	 */
501
-	public static function findAppInDirectories($appId) {
502
-		$sanitizedAppId = self::cleanAppId($appId);
503
-		if($sanitizedAppId !== $appId) {
504
-			return false;
505
-		}
506
-		static $app_dir = array();
507
-
508
-		if (isset($app_dir[$appId])) {
509
-			return $app_dir[$appId];
510
-		}
511
-
512
-		$possibleApps = array();
513
-		foreach (OC::$APPSROOTS as $dir) {
514
-			if (file_exists($dir['path'] . '/' . $appId)) {
515
-				$possibleApps[] = $dir;
516
-			}
517
-		}
518
-
519
-		if (empty($possibleApps)) {
520
-			return false;
521
-		} elseif (count($possibleApps) === 1) {
522
-			$dir = array_shift($possibleApps);
523
-			$app_dir[$appId] = $dir;
524
-			return $dir;
525
-		} else {
526
-			$versionToLoad = array();
527
-			foreach ($possibleApps as $possibleApp) {
528
-				$version = self::getAppVersionByPath($possibleApp['path']);
529
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
530
-					$versionToLoad = array(
531
-						'dir' => $possibleApp,
532
-						'version' => $version,
533
-					);
534
-				}
535
-			}
536
-			$app_dir[$appId] = $versionToLoad['dir'];
537
-			return $versionToLoad['dir'];
538
-			//TODO - write test
539
-		}
540
-	}
541
-
542
-	/**
543
-	 * Get the directory for the given app.
544
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
545
-	 *
546
-	 * @param string $appId
547
-	 * @return string|false
548
-	 */
549
-	public static function getAppPath($appId) {
550
-		if ($appId === null || trim($appId) === '') {
551
-			return false;
552
-		}
553
-
554
-		if (($dir = self::findAppInDirectories($appId)) != false) {
555
-			return $dir['path'] . '/' . $appId;
556
-		}
557
-		return false;
558
-	}
559
-
560
-	/**
561
-	 * Get the path for the given app on the access
562
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
563
-	 *
564
-	 * @param string $appId
565
-	 * @return string|false
566
-	 */
567
-	public static function getAppWebPath($appId) {
568
-		if (($dir = self::findAppInDirectories($appId)) != false) {
569
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
570
-		}
571
-		return false;
572
-	}
573
-
574
-	/**
575
-	 * get the last version of the app from appinfo/info.xml
576
-	 *
577
-	 * @param string $appId
578
-	 * @param bool $useCache
579
-	 * @return string
580
-	 */
581
-	public static function getAppVersion($appId, $useCache = true) {
582
-		if($useCache && isset(self::$appVersion[$appId])) {
583
-			return self::$appVersion[$appId];
584
-		}
585
-
586
-		$file = self::getAppPath($appId);
587
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
588
-		return self::$appVersion[$appId];
589
-	}
590
-
591
-	/**
592
-	 * get app's version based on it's path
593
-	 *
594
-	 * @param string $path
595
-	 * @return string
596
-	 */
597
-	public static function getAppVersionByPath($path) {
598
-		$infoFile = $path . '/appinfo/info.xml';
599
-		$appData = self::getAppInfo($infoFile, true);
600
-		return isset($appData['version']) ? $appData['version'] : '';
601
-	}
602
-
603
-
604
-	/**
605
-	 * Read all app metadata from the info.xml file
606
-	 *
607
-	 * @param string $appId id of the app or the path of the info.xml file
608
-	 * @param bool $path
609
-	 * @param string $lang
610
-	 * @return array|null
611
-	 * @note all data is read from info.xml, not just pre-defined fields
612
-	 */
613
-	public static function getAppInfo($appId, $path = false, $lang = null) {
614
-		if ($path) {
615
-			$file = $appId;
616
-		} else {
617
-			if ($lang === null && isset(self::$appInfo[$appId])) {
618
-				return self::$appInfo[$appId];
619
-			}
620
-			$appPath = self::getAppPath($appId);
621
-			if($appPath === false) {
622
-				return null;
623
-			}
624
-			$file = $appPath . '/appinfo/info.xml';
625
-		}
626
-
627
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
628
-		$data = $parser->parse($file);
629
-
630
-		if (is_array($data)) {
631
-			$data = OC_App::parseAppInfo($data, $lang);
632
-		}
633
-		if(isset($data['ocsid'])) {
634
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
635
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
636
-				$data['ocsid'] = $storedId;
637
-			}
638
-		}
639
-
640
-		if ($lang === null) {
641
-			self::$appInfo[$appId] = $data;
642
-		}
643
-
644
-		return $data;
645
-	}
646
-
647
-	/**
648
-	 * Returns the navigation
649
-	 *
650
-	 * @return array
651
-	 *
652
-	 * This function returns an array containing all entries added. The
653
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
654
-	 * given for each app the following keys exist:
655
-	 *   - active: boolean, signals if the user is on this navigation entry
656
-	 */
657
-	public static function getNavigation() {
658
-		$entries = OC::$server->getNavigationManager()->getAll();
659
-		return self::proceedNavigation($entries);
660
-	}
661
-
662
-	/**
663
-	 * Returns the Settings Navigation
664
-	 *
665
-	 * @return string[]
666
-	 *
667
-	 * This function returns an array containing all settings pages added. The
668
-	 * entries are sorted by the key 'order' ascending.
669
-	 */
670
-	public static function getSettingsNavigation() {
671
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
672
-		return self::proceedNavigation($entries);
673
-	}
674
-
675
-	/**
676
-	 * get the id of loaded app
677
-	 *
678
-	 * @return string
679
-	 */
680
-	public static function getCurrentApp() {
681
-		$request = \OC::$server->getRequest();
682
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
683
-		$topFolder = substr($script, 0, strpos($script, '/'));
684
-		if (empty($topFolder)) {
685
-			$path_info = $request->getPathInfo();
686
-			if ($path_info) {
687
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
688
-			}
689
-		}
690
-		if ($topFolder == 'apps') {
691
-			$length = strlen($topFolder);
692
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
693
-		} else {
694
-			return $topFolder;
695
-		}
696
-	}
697
-
698
-	/**
699
-	 * @param string $type
700
-	 * @return array
701
-	 */
702
-	public static function getForms($type) {
703
-		$forms = array();
704
-		switch ($type) {
705
-			case 'admin':
706
-				$source = self::$adminForms;
707
-				break;
708
-			case 'personal':
709
-				$source = self::$personalForms;
710
-				break;
711
-			default:
712
-				return array();
713
-		}
714
-		foreach ($source as $form) {
715
-			$forms[] = include $form;
716
-		}
717
-		return $forms;
718
-	}
719
-
720
-	/**
721
-	 * register an admin form to be shown
722
-	 *
723
-	 * @param string $app
724
-	 * @param string $page
725
-	 */
726
-	public static function registerAdmin($app, $page) {
727
-		self::$adminForms[] = $app . '/' . $page . '.php';
728
-	}
729
-
730
-	/**
731
-	 * register a personal form to be shown
732
-	 * @param string $app
733
-	 * @param string $page
734
-	 */
735
-	public static function registerPersonal($app, $page) {
736
-		self::$personalForms[] = $app . '/' . $page . '.php';
737
-	}
738
-
739
-	/**
740
-	 * @param array $entry
741
-	 */
742
-	public static function registerLogIn(array $entry) {
743
-		self::$altLogin[] = $entry;
744
-	}
745
-
746
-	/**
747
-	 * @return array
748
-	 */
749
-	public static function getAlternativeLogIns() {
750
-		return self::$altLogin;
751
-	}
752
-
753
-	/**
754
-	 * get a list of all apps in the apps folder
755
-	 *
756
-	 * @return array an array of app names (string IDs)
757
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
758
-	 */
759
-	public static function getAllApps() {
760
-
761
-		$apps = array();
762
-
763
-		foreach (OC::$APPSROOTS as $apps_dir) {
764
-			if (!is_readable($apps_dir['path'])) {
765
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
766
-				continue;
767
-			}
768
-			$dh = opendir($apps_dir['path']);
769
-
770
-			if (is_resource($dh)) {
771
-				while (($file = readdir($dh)) !== false) {
772
-
773
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
774
-
775
-						$apps[] = $file;
776
-					}
777
-				}
778
-			}
779
-		}
780
-
781
-		$apps = array_unique($apps);
782
-
783
-		return $apps;
784
-	}
785
-
786
-	/**
787
-	 * List all apps, this is used in apps.php
788
-	 *
789
-	 * @return array
790
-	 */
791
-	public function listAllApps() {
792
-		$installedApps = OC_App::getAllApps();
793
-
794
-		$appManager = \OC::$server->getAppManager();
795
-		//we don't want to show configuration for these
796
-		$blacklist = $appManager->getAlwaysEnabledApps();
797
-		$appList = array();
798
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
799
-		$urlGenerator = \OC::$server->getURLGenerator();
800
-
801
-		foreach ($installedApps as $app) {
802
-			if (array_search($app, $blacklist) === false) {
803
-
804
-				$info = OC_App::getAppInfo($app, false, $langCode);
805
-				if (!is_array($info)) {
806
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
807
-					continue;
808
-				}
809
-
810
-				if (!isset($info['name'])) {
811
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
812
-					continue;
813
-				}
814
-
815
-				$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
816
-				$info['groups'] = null;
817
-				if ($enabled === 'yes') {
818
-					$active = true;
819
-				} else if ($enabled === 'no') {
820
-					$active = false;
821
-				} else {
822
-					$active = true;
823
-					$info['groups'] = $enabled;
824
-				}
825
-
826
-				$info['active'] = $active;
827
-
828
-				if ($appManager->isShipped($app)) {
829
-					$info['internal'] = true;
830
-					$info['level'] = self::officialApp;
831
-					$info['removable'] = false;
832
-				} else {
833
-					$info['internal'] = false;
834
-					$info['removable'] = true;
835
-				}
836
-
837
-				$appPath = self::getAppPath($app);
838
-				if($appPath !== false) {
839
-					$appIcon = $appPath . '/img/' . $app . '.svg';
840
-					if (file_exists($appIcon)) {
841
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
842
-						$info['previewAsIcon'] = true;
843
-					} else {
844
-						$appIcon = $appPath . '/img/app.svg';
845
-						if (file_exists($appIcon)) {
846
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
847
-							$info['previewAsIcon'] = true;
848
-						}
849
-					}
850
-				}
851
-				// fix documentation
852
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
853
-					foreach ($info['documentation'] as $key => $url) {
854
-						// If it is not an absolute URL we assume it is a key
855
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
856
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
857
-							$url = $urlGenerator->linkToDocs($url);
858
-						}
859
-
860
-						$info['documentation'][$key] = $url;
861
-					}
862
-				}
863
-
864
-				$info['version'] = OC_App::getAppVersion($app);
865
-				$appList[] = $info;
866
-			}
867
-		}
868
-
869
-		return $appList;
870
-	}
871
-
872
-	/**
873
-	 * Returns the internal app ID or false
874
-	 * @param string $ocsID
875
-	 * @return string|false
876
-	 */
877
-	public static function getInternalAppIdByOcs($ocsID) {
878
-		if(is_numeric($ocsID)) {
879
-			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
880
-			if(array_search($ocsID, $idArray)) {
881
-				return array_search($ocsID, $idArray);
882
-			}
883
-		}
884
-		return false;
885
-	}
886
-
887
-	public static function shouldUpgrade($app) {
888
-		$versions = self::getAppVersions();
889
-		$currentVersion = OC_App::getAppVersion($app);
890
-		if ($currentVersion && isset($versions[$app])) {
891
-			$installedVersion = $versions[$app];
892
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
893
-				return true;
894
-			}
895
-		}
896
-		return false;
897
-	}
898
-
899
-	/**
900
-	 * Adjust the number of version parts of $version1 to match
901
-	 * the number of version parts of $version2.
902
-	 *
903
-	 * @param string $version1 version to adjust
904
-	 * @param string $version2 version to take the number of parts from
905
-	 * @return string shortened $version1
906
-	 */
907
-	private static function adjustVersionParts($version1, $version2) {
908
-		$version1 = explode('.', $version1);
909
-		$version2 = explode('.', $version2);
910
-		// reduce $version1 to match the number of parts in $version2
911
-		while (count($version1) > count($version2)) {
912
-			array_pop($version1);
913
-		}
914
-		// if $version1 does not have enough parts, add some
915
-		while (count($version1) < count($version2)) {
916
-			$version1[] = '0';
917
-		}
918
-		return implode('.', $version1);
919
-	}
920
-
921
-	/**
922
-	 * Check whether the current ownCloud version matches the given
923
-	 * application's version requirements.
924
-	 *
925
-	 * The comparison is made based on the number of parts that the
926
-	 * app info version has. For example for ownCloud 6.0.3 if the
927
-	 * app info version is expecting version 6.0, the comparison is
928
-	 * made on the first two parts of the ownCloud version.
929
-	 * This means that it's possible to specify "requiremin" => 6
930
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
931
-	 *
932
-	 * @param string $ocVersion ownCloud version to check against
933
-	 * @param array $appInfo app info (from xml)
934
-	 *
935
-	 * @return boolean true if compatible, otherwise false
936
-	 */
937
-	public static function isAppCompatible($ocVersion, $appInfo) {
938
-		$requireMin = '';
939
-		$requireMax = '';
940
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
941
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
942
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
943
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
944
-		} else if (isset($appInfo['requiremin'])) {
945
-			$requireMin = $appInfo['requiremin'];
946
-		} else if (isset($appInfo['require'])) {
947
-			$requireMin = $appInfo['require'];
948
-		}
949
-
950
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
951
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
952
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
953
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
954
-		} else if (isset($appInfo['requiremax'])) {
955
-			$requireMax = $appInfo['requiremax'];
956
-		}
957
-
958
-		if (is_array($ocVersion)) {
959
-			$ocVersion = implode('.', $ocVersion);
960
-		}
961
-
962
-		if (!empty($requireMin)
963
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
964
-		) {
965
-
966
-			return false;
967
-		}
968
-
969
-		if (!empty($requireMax)
970
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
971
-		) {
972
-			return false;
973
-		}
974
-
975
-		return true;
976
-	}
977
-
978
-	/**
979
-	 * get the installed version of all apps
980
-	 */
981
-	public static function getAppVersions() {
982
-		static $versions;
983
-
984
-		if(!$versions) {
985
-			$appConfig = \OC::$server->getAppConfig();
986
-			$versions = $appConfig->getValues(false, 'installed_version');
987
-		}
988
-		return $versions;
989
-	}
990
-
991
-	/**
992
-	 * @param string $app
993
-	 * @param \OCP\IConfig $config
994
-	 * @param \OCP\IL10N $l
995
-	 * @return bool
996
-	 *
997
-	 * @throws Exception if app is not compatible with this version of ownCloud
998
-	 * @throws Exception if no app-name was specified
999
-	 */
1000
-	public function installApp($app,
1001
-							   \OCP\IConfig $config,
1002
-							   \OCP\IL10N $l) {
1003
-		if ($app !== false) {
1004
-			// check if the app is compatible with this version of ownCloud
1005
-			$info = self::getAppInfo($app);
1006
-			if(!is_array($info)) {
1007
-				throw new \Exception(
1008
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1009
-						[$info['name']]
1010
-					)
1011
-				);
1012
-			}
1013
-
1014
-			$version = \OCP\Util::getVersion();
1015
-			if (!self::isAppCompatible($version, $info)) {
1016
-				throw new \Exception(
1017
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1018
-						array($info['name'])
1019
-					)
1020
-				);
1021
-			}
1022
-
1023
-			// check for required dependencies
1024
-			self::checkAppDependencies($config, $l, $info);
1025
-
1026
-			$config->setAppValue($app, 'enabled', 'yes');
1027
-			if (isset($appData['id'])) {
1028
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1029
-			}
1030
-
1031
-			if(isset($info['settings']) && is_array($info['settings'])) {
1032
-				$appPath = self::getAppPath($app);
1033
-				self::registerAutoloading($app, $appPath);
1034
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1035
-			}
1036
-
1037
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1038
-		} else {
1039
-			if(empty($appName) ) {
1040
-				throw new \Exception($l->t("No app name specified"));
1041
-			} else {
1042
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1043
-			}
1044
-		}
1045
-
1046
-		return $app;
1047
-	}
1048
-
1049
-	/**
1050
-	 * update the database for the app and call the update script
1051
-	 *
1052
-	 * @param string $appId
1053
-	 * @return bool
1054
-	 */
1055
-	public static function updateApp($appId) {
1056
-		$appPath = self::getAppPath($appId);
1057
-		if($appPath === false) {
1058
-			return false;
1059
-		}
1060
-		self::registerAutoloading($appId, $appPath);
1061
-
1062
-		$appData = self::getAppInfo($appId);
1063
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1064
-
1065
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1066
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1067
-		} else {
1068
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1069
-			$ms->migrate();
1070
-		}
1071
-
1072
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1073
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1074
-		unset(self::$appVersion[$appId]);
1075
-
1076
-		// run upgrade code
1077
-		if (file_exists($appPath . '/appinfo/update.php')) {
1078
-			self::loadApp($appId);
1079
-			include $appPath . '/appinfo/update.php';
1080
-		}
1081
-		self::setupBackgroundJobs($appData['background-jobs']);
1082
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1083
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1084
-		}
1085
-
1086
-		//set remote/public handlers
1087
-		if (array_key_exists('ocsid', $appData)) {
1088
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1089
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1090
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1091
-		}
1092
-		foreach ($appData['remote'] as $name => $path) {
1093
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1094
-		}
1095
-		foreach ($appData['public'] as $name => $path) {
1096
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1097
-		}
1098
-
1099
-		self::setAppTypes($appId);
1100
-
1101
-		$version = \OC_App::getAppVersion($appId);
1102
-		\OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1103
-
1104
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1105
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1106
-		));
1107
-
1108
-		return true;
1109
-	}
1110
-
1111
-	/**
1112
-	 * @param string $appId
1113
-	 * @param string[] $steps
1114
-	 * @throws \OC\NeedsUpdateException
1115
-	 */
1116
-	public static function executeRepairSteps($appId, array $steps) {
1117
-		if (empty($steps)) {
1118
-			return;
1119
-		}
1120
-		// load the app
1121
-		self::loadApp($appId);
1122
-
1123
-		$dispatcher = OC::$server->getEventDispatcher();
1124
-
1125
-		// load the steps
1126
-		$r = new Repair([], $dispatcher);
1127
-		foreach ($steps as $step) {
1128
-			try {
1129
-				$r->addStep($step);
1130
-			} catch (Exception $ex) {
1131
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1132
-				\OC::$server->getLogger()->logException($ex);
1133
-			}
1134
-		}
1135
-		// run the steps
1136
-		$r->run();
1137
-	}
1138
-
1139
-	public static function setupBackgroundJobs(array $jobs) {
1140
-		$queue = \OC::$server->getJobList();
1141
-		foreach ($jobs as $job) {
1142
-			$queue->add($job);
1143
-		}
1144
-	}
1145
-
1146
-	/**
1147
-	 * @param string $appId
1148
-	 * @param string[] $steps
1149
-	 */
1150
-	private static function setupLiveMigrations($appId, array $steps) {
1151
-		$queue = \OC::$server->getJobList();
1152
-		foreach ($steps as $step) {
1153
-			$queue->add('OC\Migration\BackgroundRepair', [
1154
-				'app' => $appId,
1155
-				'step' => $step]);
1156
-		}
1157
-	}
1158
-
1159
-	/**
1160
-	 * @param string $appId
1161
-	 * @return \OC\Files\View|false
1162
-	 */
1163
-	public static function getStorage($appId) {
1164
-		if (OC_App::isEnabled($appId)) { //sanity check
1165
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1166
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1167
-				if (!$view->file_exists($appId)) {
1168
-					$view->mkdir($appId);
1169
-				}
1170
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1171
-			} else {
1172
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1173
-				return false;
1174
-			}
1175
-		} else {
1176
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1177
-			return false;
1178
-		}
1179
-	}
1180
-
1181
-	protected static function findBestL10NOption($options, $lang) {
1182
-		$fallback = $similarLangFallback = $englishFallback = false;
1183
-
1184
-		$lang = strtolower($lang);
1185
-		$similarLang = $lang;
1186
-		if (strpos($similarLang, '_')) {
1187
-			// For "de_DE" we want to find "de" and the other way around
1188
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1189
-		}
1190
-
1191
-		foreach ($options as $option) {
1192
-			if (is_array($option)) {
1193
-				if ($fallback === false) {
1194
-					$fallback = $option['@value'];
1195
-				}
1196
-
1197
-				if (!isset($option['@attributes']['lang'])) {
1198
-					continue;
1199
-				}
1200
-
1201
-				$attributeLang = strtolower($option['@attributes']['lang']);
1202
-				if ($attributeLang === $lang) {
1203
-					return $option['@value'];
1204
-				}
1205
-
1206
-				if ($attributeLang === $similarLang) {
1207
-					$similarLangFallback = $option['@value'];
1208
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1209
-					if ($similarLangFallback === false) {
1210
-						$similarLangFallback =  $option['@value'];
1211
-					}
1212
-				}
1213
-			} else {
1214
-				$englishFallback = $option;
1215
-			}
1216
-		}
1217
-
1218
-		if ($similarLangFallback !== false) {
1219
-			return $similarLangFallback;
1220
-		} else if ($englishFallback !== false) {
1221
-			return $englishFallback;
1222
-		}
1223
-		return (string) $fallback;
1224
-	}
1225
-
1226
-	/**
1227
-	 * parses the app data array and enhanced the 'description' value
1228
-	 *
1229
-	 * @param array $data the app data
1230
-	 * @param string $lang
1231
-	 * @return array improved app data
1232
-	 */
1233
-	public static function parseAppInfo(array $data, $lang = null) {
1234
-
1235
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1236
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1237
-		}
1238
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1239
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1240
-		}
1241
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1242
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1243
-		} else if (isset($data['description']) && is_string($data['description'])) {
1244
-			$data['description'] = trim($data['description']);
1245
-		} else  {
1246
-			$data['description'] = '';
1247
-		}
1248
-
1249
-		return $data;
1250
-	}
1251
-
1252
-	/**
1253
-	 * @param \OCP\IConfig $config
1254
-	 * @param \OCP\IL10N $l
1255
-	 * @param array $info
1256
-	 * @throws \Exception
1257
-	 */
1258
-	public static function checkAppDependencies($config, $l, $info) {
1259
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1260
-		$missing = $dependencyAnalyzer->analyze($info);
1261
-		if (!empty($missing)) {
1262
-			$missingMsg = implode(PHP_EOL, $missing);
1263
-			throw new \Exception(
1264
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1265
-					[$info['name'], $missingMsg]
1266
-				)
1267
-			);
1268
-		}
1269
-	}
64
+    static private $appVersion = [];
65
+    static private $adminForms = array();
66
+    static private $personalForms = array();
67
+    static private $appInfo = array();
68
+    static private $appTypes = array();
69
+    static private $loadedApps = array();
70
+    static private $altLogin = array();
71
+    static private $alreadyRegistered = [];
72
+    const officialApp = 200;
73
+
74
+    /**
75
+     * clean the appId
76
+     *
77
+     * @param string|boolean $app AppId that needs to be cleaned
78
+     * @return string
79
+     */
80
+    public static function cleanAppId($app) {
81
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
+    }
83
+
84
+    /**
85
+     * Check if an app is loaded
86
+     *
87
+     * @param string $app
88
+     * @return bool
89
+     */
90
+    public static function isAppLoaded($app) {
91
+        return in_array($app, self::$loadedApps, true);
92
+    }
93
+
94
+    /**
95
+     * loads all apps
96
+     *
97
+     * @param string[] | string | null $types
98
+     * @return bool
99
+     *
100
+     * This function walks through the ownCloud directory and loads all apps
101
+     * it can find. A directory contains an app if the file /appinfo/info.xml
102
+     * exists.
103
+     *
104
+     * if $types is set, only apps of those types will be loaded
105
+     */
106
+    public static function loadApps($types = null) {
107
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
+            return false;
109
+        }
110
+        // Load the enabled apps here
111
+        $apps = self::getEnabledApps();
112
+
113
+        // Add each apps' folder as allowed class path
114
+        foreach($apps as $app) {
115
+            $path = self::getAppPath($app);
116
+            if($path !== false) {
117
+                self::registerAutoloading($app, $path);
118
+            }
119
+        }
120
+
121
+        // prevent app.php from printing output
122
+        ob_start();
123
+        foreach ($apps as $app) {
124
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
+                self::loadApp($app);
126
+            }
127
+        }
128
+        ob_end_clean();
129
+
130
+        return true;
131
+    }
132
+
133
+    /**
134
+     * load a single app
135
+     *
136
+     * @param string $app
137
+     */
138
+    public static function loadApp($app) {
139
+        self::$loadedApps[] = $app;
140
+        $appPath = self::getAppPath($app);
141
+        if($appPath === false) {
142
+            return;
143
+        }
144
+
145
+        // in case someone calls loadApp() directly
146
+        self::registerAutoloading($app, $appPath);
147
+
148
+        if (is_file($appPath . '/appinfo/app.php')) {
149
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+            self::requireAppFile($app);
151
+            if (self::isType($app, array('authentication'))) {
152
+                // since authentication apps affect the "is app enabled for group" check,
153
+                // the enabled apps cache needs to be cleared to make sure that the
154
+                // next time getEnableApps() is called it will also include apps that were
155
+                // enabled for groups
156
+                self::$enabledAppsCache = array();
157
+            }
158
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
159
+        }
160
+
161
+        $info = self::getAppInfo($app);
162
+        if (!empty($info['activity']['filters'])) {
163
+            foreach ($info['activity']['filters'] as $filter) {
164
+                \OC::$server->getActivityManager()->registerFilter($filter);
165
+            }
166
+        }
167
+        if (!empty($info['activity']['settings'])) {
168
+            foreach ($info['activity']['settings'] as $setting) {
169
+                \OC::$server->getActivityManager()->registerSetting($setting);
170
+            }
171
+        }
172
+        if (!empty($info['activity']['providers'])) {
173
+            foreach ($info['activity']['providers'] as $provider) {
174
+                \OC::$server->getActivityManager()->registerProvider($provider);
175
+            }
176
+        }
177
+        if (!empty($info['collaboration']['plugins'])) {
178
+            // deal with one or many plugin entries
179
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
180
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
181
+            foreach ($plugins as $plugin) {
182
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
183
+                    $pluginInfo = [
184
+                        'shareType' => $plugin['@attributes']['share-type'],
185
+                        'class' => $plugin['@value'],
186
+                    ];
187
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
188
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
189
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
190
+                }
191
+            }
192
+        }
193
+    }
194
+
195
+    /**
196
+     * @internal
197
+     * @param string $app
198
+     * @param string $path
199
+     */
200
+    public static function registerAutoloading($app, $path) {
201
+        $key = $app . '-' . $path;
202
+        if(isset(self::$alreadyRegistered[$key])) {
203
+            return;
204
+        }
205
+
206
+        self::$alreadyRegistered[$key] = true;
207
+
208
+        // Register on PSR-4 composer autoloader
209
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
210
+        \OC::$server->registerNamespace($app, $appNamespace);
211
+
212
+        if (file_exists($path . '/composer/autoload.php')) {
213
+            require_once $path . '/composer/autoload.php';
214
+        } else {
215
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
216
+            // Register on legacy autoloader
217
+            \OC::$loader->addValidRoot($path);
218
+        }
219
+
220
+        // Register Test namespace only when testing
221
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
222
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
223
+        }
224
+    }
225
+
226
+    /**
227
+     * Load app.php from the given app
228
+     *
229
+     * @param string $app app name
230
+     */
231
+    private static function requireAppFile($app) {
232
+        try {
233
+            // encapsulated here to avoid variable scope conflicts
234
+            require_once $app . '/appinfo/app.php';
235
+        } catch (Error $ex) {
236
+            \OC::$server->getLogger()->logException($ex);
237
+            $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
238
+            if (!in_array($app, $blacklist)) {
239
+                self::disable($app);
240
+            }
241
+        }
242
+    }
243
+
244
+    /**
245
+     * check if an app is of a specific type
246
+     *
247
+     * @param string $app
248
+     * @param string|array $types
249
+     * @return bool
250
+     */
251
+    public static function isType($app, $types) {
252
+        if (is_string($types)) {
253
+            $types = array($types);
254
+        }
255
+        $appTypes = self::getAppTypes($app);
256
+        foreach ($types as $type) {
257
+            if (array_search($type, $appTypes) !== false) {
258
+                return true;
259
+            }
260
+        }
261
+        return false;
262
+    }
263
+
264
+    /**
265
+     * get the types of an app
266
+     *
267
+     * @param string $app
268
+     * @return array
269
+     */
270
+    private static function getAppTypes($app) {
271
+        //load the cache
272
+        if (count(self::$appTypes) == 0) {
273
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
274
+        }
275
+
276
+        if (isset(self::$appTypes[$app])) {
277
+            return explode(',', self::$appTypes[$app]);
278
+        } else {
279
+            return array();
280
+        }
281
+    }
282
+
283
+    /**
284
+     * read app types from info.xml and cache them in the database
285
+     */
286
+    public static function setAppTypes($app) {
287
+        $appData = self::getAppInfo($app);
288
+        if(!is_array($appData)) {
289
+            return;
290
+        }
291
+
292
+        if (isset($appData['types'])) {
293
+            $appTypes = implode(',', $appData['types']);
294
+        } else {
295
+            $appTypes = '';
296
+            $appData['types'] = [];
297
+        }
298
+
299
+        \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
300
+
301
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
302
+            $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
303
+            if ($enabled !== 'yes' && $enabled !== 'no') {
304
+                \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
305
+            }
306
+        }
307
+    }
308
+
309
+    /**
310
+     * get all enabled apps
311
+     */
312
+    protected static $enabledAppsCache = array();
313
+
314
+    /**
315
+     * Returns apps enabled for the current user.
316
+     *
317
+     * @param bool $forceRefresh whether to refresh the cache
318
+     * @param bool $all whether to return apps for all users, not only the
319
+     * currently logged in one
320
+     * @return string[]
321
+     */
322
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
323
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
+            return array();
325
+        }
326
+        // in incognito mode or when logged out, $user will be false,
327
+        // which is also the case during an upgrade
328
+        $appManager = \OC::$server->getAppManager();
329
+        if ($all) {
330
+            $user = null;
331
+        } else {
332
+            $user = \OC::$server->getUserSession()->getUser();
333
+        }
334
+
335
+        if (is_null($user)) {
336
+            $apps = $appManager->getInstalledApps();
337
+        } else {
338
+            $apps = $appManager->getEnabledAppsForUser($user);
339
+        }
340
+        $apps = array_filter($apps, function ($app) {
341
+            return $app !== 'files';//we add this manually
342
+        });
343
+        sort($apps);
344
+        array_unshift($apps, 'files');
345
+        return $apps;
346
+    }
347
+
348
+    /**
349
+     * checks whether or not an app is enabled
350
+     *
351
+     * @param string $app app
352
+     * @return bool
353
+     *
354
+     * This function checks whether or not an app is enabled.
355
+     */
356
+    public static function isEnabled($app) {
357
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
358
+    }
359
+
360
+    /**
361
+     * enables an app
362
+     *
363
+     * @param string $appId
364
+     * @param array $groups (optional) when set, only these groups will have access to the app
365
+     * @throws \Exception
366
+     * @return void
367
+     *
368
+     * This function set an app as enabled in appconfig.
369
+     */
370
+    public function enable($appId,
371
+                            $groups = null) {
372
+        self::$enabledAppsCache = []; // flush
373
+
374
+        // Check if app is already downloaded
375
+        $installer = new Installer(
376
+            \OC::$server->getAppFetcher(),
377
+            \OC::$server->getHTTPClientService(),
378
+            \OC::$server->getTempManager(),
379
+            \OC::$server->getLogger(),
380
+            \OC::$server->getConfig()
381
+        );
382
+        $isDownloaded = $installer->isDownloaded($appId);
383
+
384
+        if(!$isDownloaded) {
385
+            $installer->downloadApp($appId);
386
+        }
387
+
388
+        $installer->installApp($appId);
389
+
390
+        $appManager = \OC::$server->getAppManager();
391
+        if (!is_null($groups)) {
392
+            $groupManager = \OC::$server->getGroupManager();
393
+            $groupsList = [];
394
+            foreach ($groups as $group) {
395
+                $groupItem = $groupManager->get($group);
396
+                if ($groupItem instanceof \OCP\IGroup) {
397
+                    $groupsList[] = $groupManager->get($group);
398
+                }
399
+            }
400
+            $appManager->enableAppForGroups($appId, $groupsList);
401
+        } else {
402
+            $appManager->enableApp($appId);
403
+        }
404
+    }
405
+
406
+    /**
407
+     * @param string $app
408
+     * @return bool
409
+     */
410
+    public static function removeApp($app) {
411
+        if (\OC::$server->getAppManager()->isShipped($app)) {
412
+            return false;
413
+        }
414
+
415
+        $installer = new Installer(
416
+            \OC::$server->getAppFetcher(),
417
+            \OC::$server->getHTTPClientService(),
418
+            \OC::$server->getTempManager(),
419
+            \OC::$server->getLogger(),
420
+            \OC::$server->getConfig()
421
+        );
422
+        return $installer->removeApp($app);
423
+    }
424
+
425
+    /**
426
+     * This function set an app as disabled in appconfig.
427
+     *
428
+     * @param string $app app
429
+     * @throws Exception
430
+     */
431
+    public static function disable($app) {
432
+        // flush
433
+        self::$enabledAppsCache = array();
434
+
435
+        // run uninstall steps
436
+        $appData = OC_App::getAppInfo($app);
437
+        if (!is_null($appData)) {
438
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
439
+        }
440
+
441
+        // emit disable hook - needed anymore ?
442
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
443
+
444
+        // finally disable it
445
+        $appManager = \OC::$server->getAppManager();
446
+        $appManager->disableApp($app);
447
+    }
448
+
449
+    // This is private as well. It simply works, so don't ask for more details
450
+    private static function proceedNavigation($list) {
451
+        usort($list, function($a, $b) {
452
+            if (isset($a['order']) && isset($b['order'])) {
453
+                return ($a['order'] < $b['order']) ? -1 : 1;
454
+            } else if (isset($a['order']) || isset($b['order'])) {
455
+                return isset($a['order']) ? -1 : 1;
456
+            } else {
457
+                return ($a['name'] < $b['name']) ? -1 : 1;
458
+            }
459
+        });
460
+
461
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
462
+        foreach ($list as $index => &$navEntry) {
463
+            if ($navEntry['id'] == $activeApp) {
464
+                $navEntry['active'] = true;
465
+            } else {
466
+                $navEntry['active'] = false;
467
+            }
468
+        }
469
+        unset($navEntry);
470
+
471
+        return $list;
472
+    }
473
+
474
+    /**
475
+     * Get the path where to install apps
476
+     *
477
+     * @return string|false
478
+     */
479
+    public static function getInstallPath() {
480
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
481
+            return false;
482
+        }
483
+
484
+        foreach (OC::$APPSROOTS as $dir) {
485
+            if (isset($dir['writable']) && $dir['writable'] === true) {
486
+                return $dir['path'];
487
+            }
488
+        }
489
+
490
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
491
+        return null;
492
+    }
493
+
494
+
495
+    /**
496
+     * search for an app in all app-directories
497
+     *
498
+     * @param string $appId
499
+     * @return false|string
500
+     */
501
+    public static function findAppInDirectories($appId) {
502
+        $sanitizedAppId = self::cleanAppId($appId);
503
+        if($sanitizedAppId !== $appId) {
504
+            return false;
505
+        }
506
+        static $app_dir = array();
507
+
508
+        if (isset($app_dir[$appId])) {
509
+            return $app_dir[$appId];
510
+        }
511
+
512
+        $possibleApps = array();
513
+        foreach (OC::$APPSROOTS as $dir) {
514
+            if (file_exists($dir['path'] . '/' . $appId)) {
515
+                $possibleApps[] = $dir;
516
+            }
517
+        }
518
+
519
+        if (empty($possibleApps)) {
520
+            return false;
521
+        } elseif (count($possibleApps) === 1) {
522
+            $dir = array_shift($possibleApps);
523
+            $app_dir[$appId] = $dir;
524
+            return $dir;
525
+        } else {
526
+            $versionToLoad = array();
527
+            foreach ($possibleApps as $possibleApp) {
528
+                $version = self::getAppVersionByPath($possibleApp['path']);
529
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
530
+                    $versionToLoad = array(
531
+                        'dir' => $possibleApp,
532
+                        'version' => $version,
533
+                    );
534
+                }
535
+            }
536
+            $app_dir[$appId] = $versionToLoad['dir'];
537
+            return $versionToLoad['dir'];
538
+            //TODO - write test
539
+        }
540
+    }
541
+
542
+    /**
543
+     * Get the directory for the given app.
544
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
545
+     *
546
+     * @param string $appId
547
+     * @return string|false
548
+     */
549
+    public static function getAppPath($appId) {
550
+        if ($appId === null || trim($appId) === '') {
551
+            return false;
552
+        }
553
+
554
+        if (($dir = self::findAppInDirectories($appId)) != false) {
555
+            return $dir['path'] . '/' . $appId;
556
+        }
557
+        return false;
558
+    }
559
+
560
+    /**
561
+     * Get the path for the given app on the access
562
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
563
+     *
564
+     * @param string $appId
565
+     * @return string|false
566
+     */
567
+    public static function getAppWebPath($appId) {
568
+        if (($dir = self::findAppInDirectories($appId)) != false) {
569
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
570
+        }
571
+        return false;
572
+    }
573
+
574
+    /**
575
+     * get the last version of the app from appinfo/info.xml
576
+     *
577
+     * @param string $appId
578
+     * @param bool $useCache
579
+     * @return string
580
+     */
581
+    public static function getAppVersion($appId, $useCache = true) {
582
+        if($useCache && isset(self::$appVersion[$appId])) {
583
+            return self::$appVersion[$appId];
584
+        }
585
+
586
+        $file = self::getAppPath($appId);
587
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
588
+        return self::$appVersion[$appId];
589
+    }
590
+
591
+    /**
592
+     * get app's version based on it's path
593
+     *
594
+     * @param string $path
595
+     * @return string
596
+     */
597
+    public static function getAppVersionByPath($path) {
598
+        $infoFile = $path . '/appinfo/info.xml';
599
+        $appData = self::getAppInfo($infoFile, true);
600
+        return isset($appData['version']) ? $appData['version'] : '';
601
+    }
602
+
603
+
604
+    /**
605
+     * Read all app metadata from the info.xml file
606
+     *
607
+     * @param string $appId id of the app or the path of the info.xml file
608
+     * @param bool $path
609
+     * @param string $lang
610
+     * @return array|null
611
+     * @note all data is read from info.xml, not just pre-defined fields
612
+     */
613
+    public static function getAppInfo($appId, $path = false, $lang = null) {
614
+        if ($path) {
615
+            $file = $appId;
616
+        } else {
617
+            if ($lang === null && isset(self::$appInfo[$appId])) {
618
+                return self::$appInfo[$appId];
619
+            }
620
+            $appPath = self::getAppPath($appId);
621
+            if($appPath === false) {
622
+                return null;
623
+            }
624
+            $file = $appPath . '/appinfo/info.xml';
625
+        }
626
+
627
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
628
+        $data = $parser->parse($file);
629
+
630
+        if (is_array($data)) {
631
+            $data = OC_App::parseAppInfo($data, $lang);
632
+        }
633
+        if(isset($data['ocsid'])) {
634
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
635
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
636
+                $data['ocsid'] = $storedId;
637
+            }
638
+        }
639
+
640
+        if ($lang === null) {
641
+            self::$appInfo[$appId] = $data;
642
+        }
643
+
644
+        return $data;
645
+    }
646
+
647
+    /**
648
+     * Returns the navigation
649
+     *
650
+     * @return array
651
+     *
652
+     * This function returns an array containing all entries added. The
653
+     * entries are sorted by the key 'order' ascending. Additional to the keys
654
+     * given for each app the following keys exist:
655
+     *   - active: boolean, signals if the user is on this navigation entry
656
+     */
657
+    public static function getNavigation() {
658
+        $entries = OC::$server->getNavigationManager()->getAll();
659
+        return self::proceedNavigation($entries);
660
+    }
661
+
662
+    /**
663
+     * Returns the Settings Navigation
664
+     *
665
+     * @return string[]
666
+     *
667
+     * This function returns an array containing all settings pages added. The
668
+     * entries are sorted by the key 'order' ascending.
669
+     */
670
+    public static function getSettingsNavigation() {
671
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
672
+        return self::proceedNavigation($entries);
673
+    }
674
+
675
+    /**
676
+     * get the id of loaded app
677
+     *
678
+     * @return string
679
+     */
680
+    public static function getCurrentApp() {
681
+        $request = \OC::$server->getRequest();
682
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
683
+        $topFolder = substr($script, 0, strpos($script, '/'));
684
+        if (empty($topFolder)) {
685
+            $path_info = $request->getPathInfo();
686
+            if ($path_info) {
687
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
688
+            }
689
+        }
690
+        if ($topFolder == 'apps') {
691
+            $length = strlen($topFolder);
692
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
693
+        } else {
694
+            return $topFolder;
695
+        }
696
+    }
697
+
698
+    /**
699
+     * @param string $type
700
+     * @return array
701
+     */
702
+    public static function getForms($type) {
703
+        $forms = array();
704
+        switch ($type) {
705
+            case 'admin':
706
+                $source = self::$adminForms;
707
+                break;
708
+            case 'personal':
709
+                $source = self::$personalForms;
710
+                break;
711
+            default:
712
+                return array();
713
+        }
714
+        foreach ($source as $form) {
715
+            $forms[] = include $form;
716
+        }
717
+        return $forms;
718
+    }
719
+
720
+    /**
721
+     * register an admin form to be shown
722
+     *
723
+     * @param string $app
724
+     * @param string $page
725
+     */
726
+    public static function registerAdmin($app, $page) {
727
+        self::$adminForms[] = $app . '/' . $page . '.php';
728
+    }
729
+
730
+    /**
731
+     * register a personal form to be shown
732
+     * @param string $app
733
+     * @param string $page
734
+     */
735
+    public static function registerPersonal($app, $page) {
736
+        self::$personalForms[] = $app . '/' . $page . '.php';
737
+    }
738
+
739
+    /**
740
+     * @param array $entry
741
+     */
742
+    public static function registerLogIn(array $entry) {
743
+        self::$altLogin[] = $entry;
744
+    }
745
+
746
+    /**
747
+     * @return array
748
+     */
749
+    public static function getAlternativeLogIns() {
750
+        return self::$altLogin;
751
+    }
752
+
753
+    /**
754
+     * get a list of all apps in the apps folder
755
+     *
756
+     * @return array an array of app names (string IDs)
757
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
758
+     */
759
+    public static function getAllApps() {
760
+
761
+        $apps = array();
762
+
763
+        foreach (OC::$APPSROOTS as $apps_dir) {
764
+            if (!is_readable($apps_dir['path'])) {
765
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
766
+                continue;
767
+            }
768
+            $dh = opendir($apps_dir['path']);
769
+
770
+            if (is_resource($dh)) {
771
+                while (($file = readdir($dh)) !== false) {
772
+
773
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
774
+
775
+                        $apps[] = $file;
776
+                    }
777
+                }
778
+            }
779
+        }
780
+
781
+        $apps = array_unique($apps);
782
+
783
+        return $apps;
784
+    }
785
+
786
+    /**
787
+     * List all apps, this is used in apps.php
788
+     *
789
+     * @return array
790
+     */
791
+    public function listAllApps() {
792
+        $installedApps = OC_App::getAllApps();
793
+
794
+        $appManager = \OC::$server->getAppManager();
795
+        //we don't want to show configuration for these
796
+        $blacklist = $appManager->getAlwaysEnabledApps();
797
+        $appList = array();
798
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
799
+        $urlGenerator = \OC::$server->getURLGenerator();
800
+
801
+        foreach ($installedApps as $app) {
802
+            if (array_search($app, $blacklist) === false) {
803
+
804
+                $info = OC_App::getAppInfo($app, false, $langCode);
805
+                if (!is_array($info)) {
806
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
807
+                    continue;
808
+                }
809
+
810
+                if (!isset($info['name'])) {
811
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
812
+                    continue;
813
+                }
814
+
815
+                $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
816
+                $info['groups'] = null;
817
+                if ($enabled === 'yes') {
818
+                    $active = true;
819
+                } else if ($enabled === 'no') {
820
+                    $active = false;
821
+                } else {
822
+                    $active = true;
823
+                    $info['groups'] = $enabled;
824
+                }
825
+
826
+                $info['active'] = $active;
827
+
828
+                if ($appManager->isShipped($app)) {
829
+                    $info['internal'] = true;
830
+                    $info['level'] = self::officialApp;
831
+                    $info['removable'] = false;
832
+                } else {
833
+                    $info['internal'] = false;
834
+                    $info['removable'] = true;
835
+                }
836
+
837
+                $appPath = self::getAppPath($app);
838
+                if($appPath !== false) {
839
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
840
+                    if (file_exists($appIcon)) {
841
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
842
+                        $info['previewAsIcon'] = true;
843
+                    } else {
844
+                        $appIcon = $appPath . '/img/app.svg';
845
+                        if (file_exists($appIcon)) {
846
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
847
+                            $info['previewAsIcon'] = true;
848
+                        }
849
+                    }
850
+                }
851
+                // fix documentation
852
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
853
+                    foreach ($info['documentation'] as $key => $url) {
854
+                        // If it is not an absolute URL we assume it is a key
855
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
856
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
857
+                            $url = $urlGenerator->linkToDocs($url);
858
+                        }
859
+
860
+                        $info['documentation'][$key] = $url;
861
+                    }
862
+                }
863
+
864
+                $info['version'] = OC_App::getAppVersion($app);
865
+                $appList[] = $info;
866
+            }
867
+        }
868
+
869
+        return $appList;
870
+    }
871
+
872
+    /**
873
+     * Returns the internal app ID or false
874
+     * @param string $ocsID
875
+     * @return string|false
876
+     */
877
+    public static function getInternalAppIdByOcs($ocsID) {
878
+        if(is_numeric($ocsID)) {
879
+            $idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
880
+            if(array_search($ocsID, $idArray)) {
881
+                return array_search($ocsID, $idArray);
882
+            }
883
+        }
884
+        return false;
885
+    }
886
+
887
+    public static function shouldUpgrade($app) {
888
+        $versions = self::getAppVersions();
889
+        $currentVersion = OC_App::getAppVersion($app);
890
+        if ($currentVersion && isset($versions[$app])) {
891
+            $installedVersion = $versions[$app];
892
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
893
+                return true;
894
+            }
895
+        }
896
+        return false;
897
+    }
898
+
899
+    /**
900
+     * Adjust the number of version parts of $version1 to match
901
+     * the number of version parts of $version2.
902
+     *
903
+     * @param string $version1 version to adjust
904
+     * @param string $version2 version to take the number of parts from
905
+     * @return string shortened $version1
906
+     */
907
+    private static function adjustVersionParts($version1, $version2) {
908
+        $version1 = explode('.', $version1);
909
+        $version2 = explode('.', $version2);
910
+        // reduce $version1 to match the number of parts in $version2
911
+        while (count($version1) > count($version2)) {
912
+            array_pop($version1);
913
+        }
914
+        // if $version1 does not have enough parts, add some
915
+        while (count($version1) < count($version2)) {
916
+            $version1[] = '0';
917
+        }
918
+        return implode('.', $version1);
919
+    }
920
+
921
+    /**
922
+     * Check whether the current ownCloud version matches the given
923
+     * application's version requirements.
924
+     *
925
+     * The comparison is made based on the number of parts that the
926
+     * app info version has. For example for ownCloud 6.0.3 if the
927
+     * app info version is expecting version 6.0, the comparison is
928
+     * made on the first two parts of the ownCloud version.
929
+     * This means that it's possible to specify "requiremin" => 6
930
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
931
+     *
932
+     * @param string $ocVersion ownCloud version to check against
933
+     * @param array $appInfo app info (from xml)
934
+     *
935
+     * @return boolean true if compatible, otherwise false
936
+     */
937
+    public static function isAppCompatible($ocVersion, $appInfo) {
938
+        $requireMin = '';
939
+        $requireMax = '';
940
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
941
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
942
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
943
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
944
+        } else if (isset($appInfo['requiremin'])) {
945
+            $requireMin = $appInfo['requiremin'];
946
+        } else if (isset($appInfo['require'])) {
947
+            $requireMin = $appInfo['require'];
948
+        }
949
+
950
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
951
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
952
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
953
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
954
+        } else if (isset($appInfo['requiremax'])) {
955
+            $requireMax = $appInfo['requiremax'];
956
+        }
957
+
958
+        if (is_array($ocVersion)) {
959
+            $ocVersion = implode('.', $ocVersion);
960
+        }
961
+
962
+        if (!empty($requireMin)
963
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
964
+        ) {
965
+
966
+            return false;
967
+        }
968
+
969
+        if (!empty($requireMax)
970
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
971
+        ) {
972
+            return false;
973
+        }
974
+
975
+        return true;
976
+    }
977
+
978
+    /**
979
+     * get the installed version of all apps
980
+     */
981
+    public static function getAppVersions() {
982
+        static $versions;
983
+
984
+        if(!$versions) {
985
+            $appConfig = \OC::$server->getAppConfig();
986
+            $versions = $appConfig->getValues(false, 'installed_version');
987
+        }
988
+        return $versions;
989
+    }
990
+
991
+    /**
992
+     * @param string $app
993
+     * @param \OCP\IConfig $config
994
+     * @param \OCP\IL10N $l
995
+     * @return bool
996
+     *
997
+     * @throws Exception if app is not compatible with this version of ownCloud
998
+     * @throws Exception if no app-name was specified
999
+     */
1000
+    public function installApp($app,
1001
+                                \OCP\IConfig $config,
1002
+                                \OCP\IL10N $l) {
1003
+        if ($app !== false) {
1004
+            // check if the app is compatible with this version of ownCloud
1005
+            $info = self::getAppInfo($app);
1006
+            if(!is_array($info)) {
1007
+                throw new \Exception(
1008
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1009
+                        [$info['name']]
1010
+                    )
1011
+                );
1012
+            }
1013
+
1014
+            $version = \OCP\Util::getVersion();
1015
+            if (!self::isAppCompatible($version, $info)) {
1016
+                throw new \Exception(
1017
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1018
+                        array($info['name'])
1019
+                    )
1020
+                );
1021
+            }
1022
+
1023
+            // check for required dependencies
1024
+            self::checkAppDependencies($config, $l, $info);
1025
+
1026
+            $config->setAppValue($app, 'enabled', 'yes');
1027
+            if (isset($appData['id'])) {
1028
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1029
+            }
1030
+
1031
+            if(isset($info['settings']) && is_array($info['settings'])) {
1032
+                $appPath = self::getAppPath($app);
1033
+                self::registerAutoloading($app, $appPath);
1034
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1035
+            }
1036
+
1037
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1038
+        } else {
1039
+            if(empty($appName) ) {
1040
+                throw new \Exception($l->t("No app name specified"));
1041
+            } else {
1042
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1043
+            }
1044
+        }
1045
+
1046
+        return $app;
1047
+    }
1048
+
1049
+    /**
1050
+     * update the database for the app and call the update script
1051
+     *
1052
+     * @param string $appId
1053
+     * @return bool
1054
+     */
1055
+    public static function updateApp($appId) {
1056
+        $appPath = self::getAppPath($appId);
1057
+        if($appPath === false) {
1058
+            return false;
1059
+        }
1060
+        self::registerAutoloading($appId, $appPath);
1061
+
1062
+        $appData = self::getAppInfo($appId);
1063
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1064
+
1065
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1066
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1067
+        } else {
1068
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1069
+            $ms->migrate();
1070
+        }
1071
+
1072
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1073
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1074
+        unset(self::$appVersion[$appId]);
1075
+
1076
+        // run upgrade code
1077
+        if (file_exists($appPath . '/appinfo/update.php')) {
1078
+            self::loadApp($appId);
1079
+            include $appPath . '/appinfo/update.php';
1080
+        }
1081
+        self::setupBackgroundJobs($appData['background-jobs']);
1082
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1083
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1084
+        }
1085
+
1086
+        //set remote/public handlers
1087
+        if (array_key_exists('ocsid', $appData)) {
1088
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1089
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1090
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1091
+        }
1092
+        foreach ($appData['remote'] as $name => $path) {
1093
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1094
+        }
1095
+        foreach ($appData['public'] as $name => $path) {
1096
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1097
+        }
1098
+
1099
+        self::setAppTypes($appId);
1100
+
1101
+        $version = \OC_App::getAppVersion($appId);
1102
+        \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1103
+
1104
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1105
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1106
+        ));
1107
+
1108
+        return true;
1109
+    }
1110
+
1111
+    /**
1112
+     * @param string $appId
1113
+     * @param string[] $steps
1114
+     * @throws \OC\NeedsUpdateException
1115
+     */
1116
+    public static function executeRepairSteps($appId, array $steps) {
1117
+        if (empty($steps)) {
1118
+            return;
1119
+        }
1120
+        // load the app
1121
+        self::loadApp($appId);
1122
+
1123
+        $dispatcher = OC::$server->getEventDispatcher();
1124
+
1125
+        // load the steps
1126
+        $r = new Repair([], $dispatcher);
1127
+        foreach ($steps as $step) {
1128
+            try {
1129
+                $r->addStep($step);
1130
+            } catch (Exception $ex) {
1131
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1132
+                \OC::$server->getLogger()->logException($ex);
1133
+            }
1134
+        }
1135
+        // run the steps
1136
+        $r->run();
1137
+    }
1138
+
1139
+    public static function setupBackgroundJobs(array $jobs) {
1140
+        $queue = \OC::$server->getJobList();
1141
+        foreach ($jobs as $job) {
1142
+            $queue->add($job);
1143
+        }
1144
+    }
1145
+
1146
+    /**
1147
+     * @param string $appId
1148
+     * @param string[] $steps
1149
+     */
1150
+    private static function setupLiveMigrations($appId, array $steps) {
1151
+        $queue = \OC::$server->getJobList();
1152
+        foreach ($steps as $step) {
1153
+            $queue->add('OC\Migration\BackgroundRepair', [
1154
+                'app' => $appId,
1155
+                'step' => $step]);
1156
+        }
1157
+    }
1158
+
1159
+    /**
1160
+     * @param string $appId
1161
+     * @return \OC\Files\View|false
1162
+     */
1163
+    public static function getStorage($appId) {
1164
+        if (OC_App::isEnabled($appId)) { //sanity check
1165
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1166
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1167
+                if (!$view->file_exists($appId)) {
1168
+                    $view->mkdir($appId);
1169
+                }
1170
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1171
+            } else {
1172
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1173
+                return false;
1174
+            }
1175
+        } else {
1176
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1177
+            return false;
1178
+        }
1179
+    }
1180
+
1181
+    protected static function findBestL10NOption($options, $lang) {
1182
+        $fallback = $similarLangFallback = $englishFallback = false;
1183
+
1184
+        $lang = strtolower($lang);
1185
+        $similarLang = $lang;
1186
+        if (strpos($similarLang, '_')) {
1187
+            // For "de_DE" we want to find "de" and the other way around
1188
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1189
+        }
1190
+
1191
+        foreach ($options as $option) {
1192
+            if (is_array($option)) {
1193
+                if ($fallback === false) {
1194
+                    $fallback = $option['@value'];
1195
+                }
1196
+
1197
+                if (!isset($option['@attributes']['lang'])) {
1198
+                    continue;
1199
+                }
1200
+
1201
+                $attributeLang = strtolower($option['@attributes']['lang']);
1202
+                if ($attributeLang === $lang) {
1203
+                    return $option['@value'];
1204
+                }
1205
+
1206
+                if ($attributeLang === $similarLang) {
1207
+                    $similarLangFallback = $option['@value'];
1208
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1209
+                    if ($similarLangFallback === false) {
1210
+                        $similarLangFallback =  $option['@value'];
1211
+                    }
1212
+                }
1213
+            } else {
1214
+                $englishFallback = $option;
1215
+            }
1216
+        }
1217
+
1218
+        if ($similarLangFallback !== false) {
1219
+            return $similarLangFallback;
1220
+        } else if ($englishFallback !== false) {
1221
+            return $englishFallback;
1222
+        }
1223
+        return (string) $fallback;
1224
+    }
1225
+
1226
+    /**
1227
+     * parses the app data array and enhanced the 'description' value
1228
+     *
1229
+     * @param array $data the app data
1230
+     * @param string $lang
1231
+     * @return array improved app data
1232
+     */
1233
+    public static function parseAppInfo(array $data, $lang = null) {
1234
+
1235
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1236
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1237
+        }
1238
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1239
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1240
+        }
1241
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1242
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1243
+        } else if (isset($data['description']) && is_string($data['description'])) {
1244
+            $data['description'] = trim($data['description']);
1245
+        } else  {
1246
+            $data['description'] = '';
1247
+        }
1248
+
1249
+        return $data;
1250
+    }
1251
+
1252
+    /**
1253
+     * @param \OCP\IConfig $config
1254
+     * @param \OCP\IL10N $l
1255
+     * @param array $info
1256
+     * @throws \Exception
1257
+     */
1258
+    public static function checkAppDependencies($config, $l, $info) {
1259
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1260
+        $missing = $dependencyAnalyzer->analyze($info);
1261
+        if (!empty($missing)) {
1262
+            $missingMsg = implode(PHP_EOL, $missing);
1263
+            throw new \Exception(
1264
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1265
+                    [$info['name'], $missingMsg]
1266
+                )
1267
+            );
1268
+        }
1269
+    }
1270 1270
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 1 patch
Indentation   +1459 added lines, -1459 removed lines patch added patch discarded remove patch
@@ -60,1487 +60,1487 @@
 block discarded – undo
60 60
  */
61 61
 class Manager implements IManager {
62 62
 
63
-	/** @var IProviderFactory */
64
-	private $factory;
65
-	/** @var ILogger */
66
-	private $logger;
67
-	/** @var IConfig */
68
-	private $config;
69
-	/** @var ISecureRandom */
70
-	private $secureRandom;
71
-	/** @var IHasher */
72
-	private $hasher;
73
-	/** @var IMountManager */
74
-	private $mountManager;
75
-	/** @var IGroupManager */
76
-	private $groupManager;
77
-	/** @var IL10N */
78
-	private $l;
79
-	/** @var IFactory */
80
-	private $l10nFactory;
81
-	/** @var IUserManager */
82
-	private $userManager;
83
-	/** @var IRootFolder */
84
-	private $rootFolder;
85
-	/** @var CappedMemoryCache */
86
-	private $sharingDisabledForUsersCache;
87
-	/** @var EventDispatcher */
88
-	private $eventDispatcher;
89
-	/** @var LegacyHooks */
90
-	private $legacyHooks;
91
-	/** @var IMailer */
92
-	private $mailer;
93
-	/** @var IURLGenerator */
94
-	private $urlGenerator;
95
-	/** @var \OC_Defaults */
96
-	private $defaults;
97
-
98
-
99
-	/**
100
-	 * Manager constructor.
101
-	 *
102
-	 * @param ILogger $logger
103
-	 * @param IConfig $config
104
-	 * @param ISecureRandom $secureRandom
105
-	 * @param IHasher $hasher
106
-	 * @param IMountManager $mountManager
107
-	 * @param IGroupManager $groupManager
108
-	 * @param IL10N $l
109
-	 * @param IFactory $l10nFactory
110
-	 * @param IProviderFactory $factory
111
-	 * @param IUserManager $userManager
112
-	 * @param IRootFolder $rootFolder
113
-	 * @param EventDispatcher $eventDispatcher
114
-	 * @param IMailer $mailer
115
-	 * @param IURLGenerator $urlGenerator
116
-	 * @param \OC_Defaults $defaults
117
-	 */
118
-	public function __construct(
119
-			ILogger $logger,
120
-			IConfig $config,
121
-			ISecureRandom $secureRandom,
122
-			IHasher $hasher,
123
-			IMountManager $mountManager,
124
-			IGroupManager $groupManager,
125
-			IL10N $l,
126
-			IFactory $l10nFactory,
127
-			IProviderFactory $factory,
128
-			IUserManager $userManager,
129
-			IRootFolder $rootFolder,
130
-			EventDispatcher $eventDispatcher,
131
-			IMailer $mailer,
132
-			IURLGenerator $urlGenerator,
133
-			\OC_Defaults $defaults
134
-	) {
135
-		$this->logger = $logger;
136
-		$this->config = $config;
137
-		$this->secureRandom = $secureRandom;
138
-		$this->hasher = $hasher;
139
-		$this->mountManager = $mountManager;
140
-		$this->groupManager = $groupManager;
141
-		$this->l = $l;
142
-		$this->l10nFactory = $l10nFactory;
143
-		$this->factory = $factory;
144
-		$this->userManager = $userManager;
145
-		$this->rootFolder = $rootFolder;
146
-		$this->eventDispatcher = $eventDispatcher;
147
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
148
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
149
-		$this->mailer = $mailer;
150
-		$this->urlGenerator = $urlGenerator;
151
-		$this->defaults = $defaults;
152
-	}
153
-
154
-	/**
155
-	 * Convert from a full share id to a tuple (providerId, shareId)
156
-	 *
157
-	 * @param string $id
158
-	 * @return string[]
159
-	 */
160
-	private function splitFullId($id) {
161
-		return explode(':', $id, 2);
162
-	}
163
-
164
-	/**
165
-	 * Verify if a password meets all requirements
166
-	 *
167
-	 * @param string $password
168
-	 * @throws \Exception
169
-	 */
170
-	protected function verifyPassword($password) {
171
-		if ($password === null) {
172
-			// No password is set, check if this is allowed.
173
-			if ($this->shareApiLinkEnforcePassword()) {
174
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
175
-			}
176
-
177
-			return;
178
-		}
179
-
180
-		// Let others verify the password
181
-		try {
182
-			$event = new GenericEvent($password);
183
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
184
-		} catch (HintException $e) {
185
-			throw new \Exception($e->getHint());
186
-		}
187
-	}
188
-
189
-	/**
190
-	 * Check for generic requirements before creating a share
191
-	 *
192
-	 * @param \OCP\Share\IShare $share
193
-	 * @throws \InvalidArgumentException
194
-	 * @throws GenericShareException
195
-	 *
196
-	 * @suppress PhanUndeclaredClassMethod
197
-	 */
198
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
199
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
200
-			// We expect a valid user as sharedWith for user shares
201
-			if (!$this->userManager->userExists($share->getSharedWith())) {
202
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
203
-			}
204
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
205
-			// We expect a valid group as sharedWith for group shares
206
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
207
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
208
-			}
209
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
210
-			if ($share->getSharedWith() !== null) {
211
-				throw new \InvalidArgumentException('SharedWith should be empty');
212
-			}
213
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
214
-			if ($share->getSharedWith() === null) {
215
-				throw new \InvalidArgumentException('SharedWith should not be empty');
216
-			}
217
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
218
-			if ($share->getSharedWith() === null) {
219
-				throw new \InvalidArgumentException('SharedWith should not be empty');
220
-			}
221
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
222
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
223
-			if ($circle === null) {
224
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
225
-			}
226
-		} else {
227
-			// We can't handle other types yet
228
-			throw new \InvalidArgumentException('unknown share type');
229
-		}
230
-
231
-		// Verify the initiator of the share is set
232
-		if ($share->getSharedBy() === null) {
233
-			throw new \InvalidArgumentException('SharedBy should be set');
234
-		}
235
-
236
-		// Cannot share with yourself
237
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
238
-			$share->getSharedWith() === $share->getSharedBy()) {
239
-			throw new \InvalidArgumentException('Can’t share with yourself');
240
-		}
241
-
242
-		// The path should be set
243
-		if ($share->getNode() === null) {
244
-			throw new \InvalidArgumentException('Path should be set');
245
-		}
246
-
247
-		// And it should be a file or a folder
248
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
249
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
250
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
251
-		}
252
-
253
-		// And you can't share your rootfolder
254
-		if ($this->userManager->userExists($share->getSharedBy())) {
255
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
256
-		} else {
257
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
258
-		}
259
-		if ($sharedPath === $share->getNode()->getPath()) {
260
-			throw new \InvalidArgumentException('You can’t share your root folder');
261
-		}
262
-
263
-		// Check if we actually have share permissions
264
-		if (!$share->getNode()->isShareable()) {
265
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
266
-			throw new GenericShareException($message_t, $message_t, 404);
267
-		}
268
-
269
-		// Permissions should be set
270
-		if ($share->getPermissions() === null) {
271
-			throw new \InvalidArgumentException('A share requires permissions');
272
-		}
273
-
274
-		/*
63
+    /** @var IProviderFactory */
64
+    private $factory;
65
+    /** @var ILogger */
66
+    private $logger;
67
+    /** @var IConfig */
68
+    private $config;
69
+    /** @var ISecureRandom */
70
+    private $secureRandom;
71
+    /** @var IHasher */
72
+    private $hasher;
73
+    /** @var IMountManager */
74
+    private $mountManager;
75
+    /** @var IGroupManager */
76
+    private $groupManager;
77
+    /** @var IL10N */
78
+    private $l;
79
+    /** @var IFactory */
80
+    private $l10nFactory;
81
+    /** @var IUserManager */
82
+    private $userManager;
83
+    /** @var IRootFolder */
84
+    private $rootFolder;
85
+    /** @var CappedMemoryCache */
86
+    private $sharingDisabledForUsersCache;
87
+    /** @var EventDispatcher */
88
+    private $eventDispatcher;
89
+    /** @var LegacyHooks */
90
+    private $legacyHooks;
91
+    /** @var IMailer */
92
+    private $mailer;
93
+    /** @var IURLGenerator */
94
+    private $urlGenerator;
95
+    /** @var \OC_Defaults */
96
+    private $defaults;
97
+
98
+
99
+    /**
100
+     * Manager constructor.
101
+     *
102
+     * @param ILogger $logger
103
+     * @param IConfig $config
104
+     * @param ISecureRandom $secureRandom
105
+     * @param IHasher $hasher
106
+     * @param IMountManager $mountManager
107
+     * @param IGroupManager $groupManager
108
+     * @param IL10N $l
109
+     * @param IFactory $l10nFactory
110
+     * @param IProviderFactory $factory
111
+     * @param IUserManager $userManager
112
+     * @param IRootFolder $rootFolder
113
+     * @param EventDispatcher $eventDispatcher
114
+     * @param IMailer $mailer
115
+     * @param IURLGenerator $urlGenerator
116
+     * @param \OC_Defaults $defaults
117
+     */
118
+    public function __construct(
119
+            ILogger $logger,
120
+            IConfig $config,
121
+            ISecureRandom $secureRandom,
122
+            IHasher $hasher,
123
+            IMountManager $mountManager,
124
+            IGroupManager $groupManager,
125
+            IL10N $l,
126
+            IFactory $l10nFactory,
127
+            IProviderFactory $factory,
128
+            IUserManager $userManager,
129
+            IRootFolder $rootFolder,
130
+            EventDispatcher $eventDispatcher,
131
+            IMailer $mailer,
132
+            IURLGenerator $urlGenerator,
133
+            \OC_Defaults $defaults
134
+    ) {
135
+        $this->logger = $logger;
136
+        $this->config = $config;
137
+        $this->secureRandom = $secureRandom;
138
+        $this->hasher = $hasher;
139
+        $this->mountManager = $mountManager;
140
+        $this->groupManager = $groupManager;
141
+        $this->l = $l;
142
+        $this->l10nFactory = $l10nFactory;
143
+        $this->factory = $factory;
144
+        $this->userManager = $userManager;
145
+        $this->rootFolder = $rootFolder;
146
+        $this->eventDispatcher = $eventDispatcher;
147
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
148
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
149
+        $this->mailer = $mailer;
150
+        $this->urlGenerator = $urlGenerator;
151
+        $this->defaults = $defaults;
152
+    }
153
+
154
+    /**
155
+     * Convert from a full share id to a tuple (providerId, shareId)
156
+     *
157
+     * @param string $id
158
+     * @return string[]
159
+     */
160
+    private function splitFullId($id) {
161
+        return explode(':', $id, 2);
162
+    }
163
+
164
+    /**
165
+     * Verify if a password meets all requirements
166
+     *
167
+     * @param string $password
168
+     * @throws \Exception
169
+     */
170
+    protected function verifyPassword($password) {
171
+        if ($password === null) {
172
+            // No password is set, check if this is allowed.
173
+            if ($this->shareApiLinkEnforcePassword()) {
174
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
175
+            }
176
+
177
+            return;
178
+        }
179
+
180
+        // Let others verify the password
181
+        try {
182
+            $event = new GenericEvent($password);
183
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
184
+        } catch (HintException $e) {
185
+            throw new \Exception($e->getHint());
186
+        }
187
+    }
188
+
189
+    /**
190
+     * Check for generic requirements before creating a share
191
+     *
192
+     * @param \OCP\Share\IShare $share
193
+     * @throws \InvalidArgumentException
194
+     * @throws GenericShareException
195
+     *
196
+     * @suppress PhanUndeclaredClassMethod
197
+     */
198
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
199
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
200
+            // We expect a valid user as sharedWith for user shares
201
+            if (!$this->userManager->userExists($share->getSharedWith())) {
202
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
203
+            }
204
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
205
+            // We expect a valid group as sharedWith for group shares
206
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
207
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
208
+            }
209
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
210
+            if ($share->getSharedWith() !== null) {
211
+                throw new \InvalidArgumentException('SharedWith should be empty');
212
+            }
213
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
214
+            if ($share->getSharedWith() === null) {
215
+                throw new \InvalidArgumentException('SharedWith should not be empty');
216
+            }
217
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
218
+            if ($share->getSharedWith() === null) {
219
+                throw new \InvalidArgumentException('SharedWith should not be empty');
220
+            }
221
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
222
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
223
+            if ($circle === null) {
224
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
225
+            }
226
+        } else {
227
+            // We can't handle other types yet
228
+            throw new \InvalidArgumentException('unknown share type');
229
+        }
230
+
231
+        // Verify the initiator of the share is set
232
+        if ($share->getSharedBy() === null) {
233
+            throw new \InvalidArgumentException('SharedBy should be set');
234
+        }
235
+
236
+        // Cannot share with yourself
237
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
238
+            $share->getSharedWith() === $share->getSharedBy()) {
239
+            throw new \InvalidArgumentException('Can’t share with yourself');
240
+        }
241
+
242
+        // The path should be set
243
+        if ($share->getNode() === null) {
244
+            throw new \InvalidArgumentException('Path should be set');
245
+        }
246
+
247
+        // And it should be a file or a folder
248
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
249
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
250
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
251
+        }
252
+
253
+        // And you can't share your rootfolder
254
+        if ($this->userManager->userExists($share->getSharedBy())) {
255
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
256
+        } else {
257
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
258
+        }
259
+        if ($sharedPath === $share->getNode()->getPath()) {
260
+            throw new \InvalidArgumentException('You can’t share your root folder');
261
+        }
262
+
263
+        // Check if we actually have share permissions
264
+        if (!$share->getNode()->isShareable()) {
265
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
266
+            throw new GenericShareException($message_t, $message_t, 404);
267
+        }
268
+
269
+        // Permissions should be set
270
+        if ($share->getPermissions() === null) {
271
+            throw new \InvalidArgumentException('A share requires permissions');
272
+        }
273
+
274
+        /*
275 275
 		 * Quick fix for #23536
276 276
 		 * Non moveable mount points do not have update and delete permissions
277 277
 		 * while we 'most likely' do have that on the storage.
278 278
 		 */
279
-		$permissions = $share->getNode()->getPermissions();
280
-		$mount = $share->getNode()->getMountPoint();
281
-		if (!($mount instanceof MoveableMount)) {
282
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
283
-		}
284
-
285
-		// Check that we do not share with more permissions than we have
286
-		if ($share->getPermissions() & ~$permissions) {
287
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
288
-			throw new GenericShareException($message_t, $message_t, 404);
289
-		}
290
-
291
-
292
-		// Check that read permissions are always set
293
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
294
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
295
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
296
-		if (!$noReadPermissionRequired &&
297
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
298
-			throw new \InvalidArgumentException('Shares need at least read permissions');
299
-		}
300
-
301
-		if ($share->getNode() instanceof \OCP\Files\File) {
302
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
303
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
304
-				throw new GenericShareException($message_t);
305
-			}
306
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
307
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
308
-				throw new GenericShareException($message_t);
309
-			}
310
-		}
311
-	}
312
-
313
-	/**
314
-	 * Validate if the expiration date fits the system settings
315
-	 *
316
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
317
-	 * @return \OCP\Share\IShare The modified share object
318
-	 * @throws GenericShareException
319
-	 * @throws \InvalidArgumentException
320
-	 * @throws \Exception
321
-	 */
322
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
323
-
324
-		$expirationDate = $share->getExpirationDate();
325
-
326
-		if ($expirationDate !== null) {
327
-			//Make sure the expiration date is a date
328
-			$expirationDate->setTime(0, 0, 0);
329
-
330
-			$date = new \DateTime();
331
-			$date->setTime(0, 0, 0);
332
-			if ($date >= $expirationDate) {
333
-				$message = $this->l->t('Expiration date is in the past');
334
-				throw new GenericShareException($message, $message, 404);
335
-			}
336
-		}
337
-
338
-		// If expiredate is empty set a default one if there is a default
339
-		$fullId = null;
340
-		try {
341
-			$fullId = $share->getFullId();
342
-		} catch (\UnexpectedValueException $e) {
343
-			// This is a new share
344
-		}
345
-
346
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347
-			$expirationDate = new \DateTime();
348
-			$expirationDate->setTime(0,0,0);
349
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350
-		}
351
-
352
-		// If we enforce the expiration date check that is does not exceed
353
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
354
-			if ($expirationDate === null) {
355
-				throw new \InvalidArgumentException('Expiration date is enforced');
356
-			}
357
-
358
-			$date = new \DateTime();
359
-			$date->setTime(0, 0, 0);
360
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
361
-			if ($date < $expirationDate) {
362
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363
-				throw new GenericShareException($message, $message, 404);
364
-			}
365
-		}
366
-
367
-		$accepted = true;
368
-		$message = '';
369
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
370
-			'expirationDate' => &$expirationDate,
371
-			'accepted' => &$accepted,
372
-			'message' => &$message,
373
-			'passwordSet' => $share->getPassword() !== null,
374
-		]);
375
-
376
-		if (!$accepted) {
377
-			throw new \Exception($message);
378
-		}
379
-
380
-		$share->setExpirationDate($expirationDate);
381
-
382
-		return $share;
383
-	}
384
-
385
-	/**
386
-	 * Check for pre share requirements for user shares
387
-	 *
388
-	 * @param \OCP\Share\IShare $share
389
-	 * @throws \Exception
390
-	 */
391
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
392
-		// Check if we can share with group members only
393
-		if ($this->shareWithGroupMembersOnly()) {
394
-			$sharedBy = $this->userManager->get($share->getSharedBy());
395
-			$sharedWith = $this->userManager->get($share->getSharedWith());
396
-			// Verify we can share with this user
397
-			$groups = array_intersect(
398
-					$this->groupManager->getUserGroupIds($sharedBy),
399
-					$this->groupManager->getUserGroupIds($sharedWith)
400
-			);
401
-			if (empty($groups)) {
402
-				throw new \Exception('Sharing is only allowed with group members');
403
-			}
404
-		}
405
-
406
-		/*
279
+        $permissions = $share->getNode()->getPermissions();
280
+        $mount = $share->getNode()->getMountPoint();
281
+        if (!($mount instanceof MoveableMount)) {
282
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
283
+        }
284
+
285
+        // Check that we do not share with more permissions than we have
286
+        if ($share->getPermissions() & ~$permissions) {
287
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
288
+            throw new GenericShareException($message_t, $message_t, 404);
289
+        }
290
+
291
+
292
+        // Check that read permissions are always set
293
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
294
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
295
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
296
+        if (!$noReadPermissionRequired &&
297
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
298
+            throw new \InvalidArgumentException('Shares need at least read permissions');
299
+        }
300
+
301
+        if ($share->getNode() instanceof \OCP\Files\File) {
302
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
303
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
304
+                throw new GenericShareException($message_t);
305
+            }
306
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
307
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
308
+                throw new GenericShareException($message_t);
309
+            }
310
+        }
311
+    }
312
+
313
+    /**
314
+     * Validate if the expiration date fits the system settings
315
+     *
316
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
317
+     * @return \OCP\Share\IShare The modified share object
318
+     * @throws GenericShareException
319
+     * @throws \InvalidArgumentException
320
+     * @throws \Exception
321
+     */
322
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
323
+
324
+        $expirationDate = $share->getExpirationDate();
325
+
326
+        if ($expirationDate !== null) {
327
+            //Make sure the expiration date is a date
328
+            $expirationDate->setTime(0, 0, 0);
329
+
330
+            $date = new \DateTime();
331
+            $date->setTime(0, 0, 0);
332
+            if ($date >= $expirationDate) {
333
+                $message = $this->l->t('Expiration date is in the past');
334
+                throw new GenericShareException($message, $message, 404);
335
+            }
336
+        }
337
+
338
+        // If expiredate is empty set a default one if there is a default
339
+        $fullId = null;
340
+        try {
341
+            $fullId = $share->getFullId();
342
+        } catch (\UnexpectedValueException $e) {
343
+            // This is a new share
344
+        }
345
+
346
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347
+            $expirationDate = new \DateTime();
348
+            $expirationDate->setTime(0,0,0);
349
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350
+        }
351
+
352
+        // If we enforce the expiration date check that is does not exceed
353
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
354
+            if ($expirationDate === null) {
355
+                throw new \InvalidArgumentException('Expiration date is enforced');
356
+            }
357
+
358
+            $date = new \DateTime();
359
+            $date->setTime(0, 0, 0);
360
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
361
+            if ($date < $expirationDate) {
362
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363
+                throw new GenericShareException($message, $message, 404);
364
+            }
365
+        }
366
+
367
+        $accepted = true;
368
+        $message = '';
369
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
370
+            'expirationDate' => &$expirationDate,
371
+            'accepted' => &$accepted,
372
+            'message' => &$message,
373
+            'passwordSet' => $share->getPassword() !== null,
374
+        ]);
375
+
376
+        if (!$accepted) {
377
+            throw new \Exception($message);
378
+        }
379
+
380
+        $share->setExpirationDate($expirationDate);
381
+
382
+        return $share;
383
+    }
384
+
385
+    /**
386
+     * Check for pre share requirements for user shares
387
+     *
388
+     * @param \OCP\Share\IShare $share
389
+     * @throws \Exception
390
+     */
391
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
392
+        // Check if we can share with group members only
393
+        if ($this->shareWithGroupMembersOnly()) {
394
+            $sharedBy = $this->userManager->get($share->getSharedBy());
395
+            $sharedWith = $this->userManager->get($share->getSharedWith());
396
+            // Verify we can share with this user
397
+            $groups = array_intersect(
398
+                    $this->groupManager->getUserGroupIds($sharedBy),
399
+                    $this->groupManager->getUserGroupIds($sharedWith)
400
+            );
401
+            if (empty($groups)) {
402
+                throw new \Exception('Sharing is only allowed with group members');
403
+            }
404
+        }
405
+
406
+        /*
407 407
 		 * TODO: Could be costly, fix
408 408
 		 *
409 409
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
410 410
 		 */
411
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412
-		$existingShares = $provider->getSharesByPath($share->getNode());
413
-		foreach($existingShares as $existingShare) {
414
-			// Ignore if it is the same share
415
-			try {
416
-				if ($existingShare->getFullId() === $share->getFullId()) {
417
-					continue;
418
-				}
419
-			} catch (\UnexpectedValueException $e) {
420
-				//Shares are not identical
421
-			}
422
-
423
-			// Identical share already existst
424
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
425
-				throw new \Exception('Path is already shared with this user');
426
-			}
427
-
428
-			// The share is already shared with this user via a group share
429
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
430
-				$group = $this->groupManager->get($existingShare->getSharedWith());
431
-				if (!is_null($group)) {
432
-					$user = $this->userManager->get($share->getSharedWith());
433
-
434
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
435
-						throw new \Exception('Path is already shared with this user');
436
-					}
437
-				}
438
-			}
439
-		}
440
-	}
441
-
442
-	/**
443
-	 * Check for pre share requirements for group shares
444
-	 *
445
-	 * @param \OCP\Share\IShare $share
446
-	 * @throws \Exception
447
-	 */
448
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
449
-		// Verify group shares are allowed
450
-		if (!$this->allowGroupSharing()) {
451
-			throw new \Exception('Group sharing is now allowed');
452
-		}
453
-
454
-		// Verify if the user can share with this group
455
-		if ($this->shareWithGroupMembersOnly()) {
456
-			$sharedBy = $this->userManager->get($share->getSharedBy());
457
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
458
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
459
-				throw new \Exception('Sharing is only allowed within your own groups');
460
-			}
461
-		}
462
-
463
-		/*
411
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412
+        $existingShares = $provider->getSharesByPath($share->getNode());
413
+        foreach($existingShares as $existingShare) {
414
+            // Ignore if it is the same share
415
+            try {
416
+                if ($existingShare->getFullId() === $share->getFullId()) {
417
+                    continue;
418
+                }
419
+            } catch (\UnexpectedValueException $e) {
420
+                //Shares are not identical
421
+            }
422
+
423
+            // Identical share already existst
424
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
425
+                throw new \Exception('Path is already shared with this user');
426
+            }
427
+
428
+            // The share is already shared with this user via a group share
429
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
430
+                $group = $this->groupManager->get($existingShare->getSharedWith());
431
+                if (!is_null($group)) {
432
+                    $user = $this->userManager->get($share->getSharedWith());
433
+
434
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
435
+                        throw new \Exception('Path is already shared with this user');
436
+                    }
437
+                }
438
+            }
439
+        }
440
+    }
441
+
442
+    /**
443
+     * Check for pre share requirements for group shares
444
+     *
445
+     * @param \OCP\Share\IShare $share
446
+     * @throws \Exception
447
+     */
448
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
449
+        // Verify group shares are allowed
450
+        if (!$this->allowGroupSharing()) {
451
+            throw new \Exception('Group sharing is now allowed');
452
+        }
453
+
454
+        // Verify if the user can share with this group
455
+        if ($this->shareWithGroupMembersOnly()) {
456
+            $sharedBy = $this->userManager->get($share->getSharedBy());
457
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
458
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
459
+                throw new \Exception('Sharing is only allowed within your own groups');
460
+            }
461
+        }
462
+
463
+        /*
464 464
 		 * TODO: Could be costly, fix
465 465
 		 *
466 466
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
467 467
 		 */
468
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469
-		$existingShares = $provider->getSharesByPath($share->getNode());
470
-		foreach($existingShares as $existingShare) {
471
-			try {
472
-				if ($existingShare->getFullId() === $share->getFullId()) {
473
-					continue;
474
-				}
475
-			} catch (\UnexpectedValueException $e) {
476
-				//It is a new share so just continue
477
-			}
478
-
479
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
480
-				throw new \Exception('Path is already shared with this group');
481
-			}
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * Check for pre share requirements for link shares
487
-	 *
488
-	 * @param \OCP\Share\IShare $share
489
-	 * @throws \Exception
490
-	 */
491
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
492
-		// Are link shares allowed?
493
-		if (!$this->shareApiAllowLinks()) {
494
-			throw new \Exception('Link sharing is not allowed');
495
-		}
496
-
497
-		// Link shares by definition can't have share permissions
498
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
499
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
500
-		}
501
-
502
-		// Check if public upload is allowed
503
-		if (!$this->shareApiLinkAllowPublicUpload() &&
504
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
505
-			throw new \InvalidArgumentException('Public upload is not allowed');
506
-		}
507
-	}
508
-
509
-	/**
510
-	 * To make sure we don't get invisible link shares we set the parent
511
-	 * of a link if it is a reshare. This is a quick word around
512
-	 * until we can properly display multiple link shares in the UI
513
-	 *
514
-	 * See: https://github.com/owncloud/core/issues/22295
515
-	 *
516
-	 * FIXME: Remove once multiple link shares can be properly displayed
517
-	 *
518
-	 * @param \OCP\Share\IShare $share
519
-	 */
520
-	protected function setLinkParent(\OCP\Share\IShare $share) {
521
-
522
-		// No sense in checking if the method is not there.
523
-		if (method_exists($share, 'setParent')) {
524
-			$storage = $share->getNode()->getStorage();
525
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
526
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
527
-				$share->setParent($storage->getShareId());
528
-			}
529
-		};
530
-	}
531
-
532
-	/**
533
-	 * @param File|Folder $path
534
-	 */
535
-	protected function pathCreateChecks($path) {
536
-		// Make sure that we do not share a path that contains a shared mountpoint
537
-		if ($path instanceof \OCP\Files\Folder) {
538
-			$mounts = $this->mountManager->findIn($path->getPath());
539
-			foreach($mounts as $mount) {
540
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541
-					throw new \InvalidArgumentException('Path contains files shared with you');
542
-				}
543
-			}
544
-		}
545
-	}
546
-
547
-	/**
548
-	 * Check if the user that is sharing can actually share
549
-	 *
550
-	 * @param \OCP\Share\IShare $share
551
-	 * @throws \Exception
552
-	 */
553
-	protected function canShare(\OCP\Share\IShare $share) {
554
-		if (!$this->shareApiEnabled()) {
555
-			throw new \Exception('Sharing is disabled');
556
-		}
557
-
558
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
559
-			throw new \Exception('Sharing is disabled for you');
560
-		}
561
-	}
562
-
563
-	/**
564
-	 * Share a path
565
-	 *
566
-	 * @param \OCP\Share\IShare $share
567
-	 * @return Share The share object
568
-	 * @throws \Exception
569
-	 *
570
-	 * TODO: handle link share permissions or check them
571
-	 */
572
-	public function createShare(\OCP\Share\IShare $share) {
573
-		$this->canShare($share);
574
-
575
-		$this->generalCreateChecks($share);
576
-
577
-		// Verify if there are any issues with the path
578
-		$this->pathCreateChecks($share->getNode());
579
-
580
-		/*
468
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469
+        $existingShares = $provider->getSharesByPath($share->getNode());
470
+        foreach($existingShares as $existingShare) {
471
+            try {
472
+                if ($existingShare->getFullId() === $share->getFullId()) {
473
+                    continue;
474
+                }
475
+            } catch (\UnexpectedValueException $e) {
476
+                //It is a new share so just continue
477
+            }
478
+
479
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
480
+                throw new \Exception('Path is already shared with this group');
481
+            }
482
+        }
483
+    }
484
+
485
+    /**
486
+     * Check for pre share requirements for link shares
487
+     *
488
+     * @param \OCP\Share\IShare $share
489
+     * @throws \Exception
490
+     */
491
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
492
+        // Are link shares allowed?
493
+        if (!$this->shareApiAllowLinks()) {
494
+            throw new \Exception('Link sharing is not allowed');
495
+        }
496
+
497
+        // Link shares by definition can't have share permissions
498
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
499
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
500
+        }
501
+
502
+        // Check if public upload is allowed
503
+        if (!$this->shareApiLinkAllowPublicUpload() &&
504
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
505
+            throw new \InvalidArgumentException('Public upload is not allowed');
506
+        }
507
+    }
508
+
509
+    /**
510
+     * To make sure we don't get invisible link shares we set the parent
511
+     * of a link if it is a reshare. This is a quick word around
512
+     * until we can properly display multiple link shares in the UI
513
+     *
514
+     * See: https://github.com/owncloud/core/issues/22295
515
+     *
516
+     * FIXME: Remove once multiple link shares can be properly displayed
517
+     *
518
+     * @param \OCP\Share\IShare $share
519
+     */
520
+    protected function setLinkParent(\OCP\Share\IShare $share) {
521
+
522
+        // No sense in checking if the method is not there.
523
+        if (method_exists($share, 'setParent')) {
524
+            $storage = $share->getNode()->getStorage();
525
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
526
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
527
+                $share->setParent($storage->getShareId());
528
+            }
529
+        };
530
+    }
531
+
532
+    /**
533
+     * @param File|Folder $path
534
+     */
535
+    protected function pathCreateChecks($path) {
536
+        // Make sure that we do not share a path that contains a shared mountpoint
537
+        if ($path instanceof \OCP\Files\Folder) {
538
+            $mounts = $this->mountManager->findIn($path->getPath());
539
+            foreach($mounts as $mount) {
540
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541
+                    throw new \InvalidArgumentException('Path contains files shared with you');
542
+                }
543
+            }
544
+        }
545
+    }
546
+
547
+    /**
548
+     * Check if the user that is sharing can actually share
549
+     *
550
+     * @param \OCP\Share\IShare $share
551
+     * @throws \Exception
552
+     */
553
+    protected function canShare(\OCP\Share\IShare $share) {
554
+        if (!$this->shareApiEnabled()) {
555
+            throw new \Exception('Sharing is disabled');
556
+        }
557
+
558
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
559
+            throw new \Exception('Sharing is disabled for you');
560
+        }
561
+    }
562
+
563
+    /**
564
+     * Share a path
565
+     *
566
+     * @param \OCP\Share\IShare $share
567
+     * @return Share The share object
568
+     * @throws \Exception
569
+     *
570
+     * TODO: handle link share permissions or check them
571
+     */
572
+    public function createShare(\OCP\Share\IShare $share) {
573
+        $this->canShare($share);
574
+
575
+        $this->generalCreateChecks($share);
576
+
577
+        // Verify if there are any issues with the path
578
+        $this->pathCreateChecks($share->getNode());
579
+
580
+        /*
581 581
 		 * On creation of a share the owner is always the owner of the path
582 582
 		 * Except for mounted federated shares.
583 583
 		 */
584
-		$storage = $share->getNode()->getStorage();
585
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586
-			$parent = $share->getNode()->getParent();
587
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588
-				$parent = $parent->getParent();
589
-			}
590
-			$share->setShareOwner($parent->getOwner()->getUID());
591
-		} else {
592
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
593
-		}
594
-
595
-		//Verify share type
596
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
-			$this->userCreateChecks($share);
598
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
-			$this->groupCreateChecks($share);
600
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
601
-			$this->linkCreateChecks($share);
602
-			$this->setLinkParent($share);
603
-
604
-			/*
584
+        $storage = $share->getNode()->getStorage();
585
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586
+            $parent = $share->getNode()->getParent();
587
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588
+                $parent = $parent->getParent();
589
+            }
590
+            $share->setShareOwner($parent->getOwner()->getUID());
591
+        } else {
592
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
593
+        }
594
+
595
+        //Verify share type
596
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
+            $this->userCreateChecks($share);
598
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
+            $this->groupCreateChecks($share);
600
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
601
+            $this->linkCreateChecks($share);
602
+            $this->setLinkParent($share);
603
+
604
+            /*
605 605
 			 * For now ignore a set token.
606 606
 			 */
607
-			$share->setToken(
608
-				$this->secureRandom->generate(
609
-					\OC\Share\Constants::TOKEN_LENGTH,
610
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
611
-				)
612
-			);
613
-
614
-			//Verify the expiration date
615
-			$this->validateExpirationDate($share);
616
-
617
-			//Verify the password
618
-			$this->verifyPassword($share->getPassword());
619
-
620
-			// If a password is set. Hash it!
621
-			if ($share->getPassword() !== null) {
622
-				$share->setPassword($this->hasher->hash($share->getPassword()));
623
-			}
624
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
-			$share->setToken(
626
-				$this->secureRandom->generate(
627
-					\OC\Share\Constants::TOKEN_LENGTH,
628
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
629
-				)
630
-			);
631
-		}
632
-
633
-		// Cannot share with the owner
634
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
635
-			$share->getSharedWith() === $share->getShareOwner()) {
636
-			throw new \InvalidArgumentException('Can’t share with the share owner');
637
-		}
638
-
639
-		// Generate the target
640
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
641
-		$target = \OC\Files\Filesystem::normalizePath($target);
642
-		$share->setTarget($target);
643
-
644
-		// Pre share event
645
-		$event = new GenericEvent($share);
646
-		$a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
647
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
648
-			throw new \Exception($event->getArgument('error'));
649
-		}
650
-
651
-		$oldShare = $share;
652
-		$provider = $this->factory->getProviderForType($share->getShareType());
653
-		$share = $provider->create($share);
654
-		//reuse the node we already have
655
-		$share->setNode($oldShare->getNode());
656
-
657
-		// Post share event
658
-		$event = new GenericEvent($share);
659
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
660
-
661
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662
-			$user = $this->userManager->get($share->getSharedWith());
663
-			if ($user !== null) {
664
-				$emailAddress = $user->getEMailAddress();
665
-				if ($emailAddress !== null && $emailAddress !== '') {
666
-					$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
667
-					$l = $this->l10nFactory->get('lib', $userLang);
668
-					$this->sendMailNotification(
669
-						$l,
670
-						$share->getNode()->getName(),
671
-						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
672
-						$share->getSharedBy(),
673
-						$emailAddress,
674
-						$share->getExpirationDate()
675
-					);
676
-					$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
677
-				} else {
678
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
679
-				}
680
-			} else {
681
-				$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
682
-			}
683
-		}
684
-
685
-		return $share;
686
-	}
687
-
688
-	/**
689
-	 * @param IL10N $l Language of the recipient
690
-	 * @param string $filename file/folder name
691
-	 * @param string $link link to the file/folder
692
-	 * @param string $initiator user ID of share sender
693
-	 * @param string $shareWith email address of share receiver
694
-	 * @param \DateTime|null $expiration
695
-	 * @throws \Exception If mail couldn't be sent
696
-	 */
697
-	protected function sendMailNotification(IL10N $l,
698
-											$filename,
699
-											$link,
700
-											$initiator,
701
-											$shareWith,
702
-											\DateTime $expiration = null) {
703
-		$initiatorUser = $this->userManager->get($initiator);
704
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
705
-
706
-		$message = $this->mailer->createMessage();
707
-
708
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
709
-			'filename' => $filename,
710
-			'link' => $link,
711
-			'initiator' => $initiatorDisplayName,
712
-			'expiration' => $expiration,
713
-			'shareWith' => $shareWith,
714
-		]);
715
-
716
-		$emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
717
-		$emailTemplate->addHeader();
718
-		$emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
719
-		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
720
-
721
-		$emailTemplate->addBodyText(
722
-			$text . ' ' . $l->t('Click the button below to open it.'),
723
-			$text
724
-		);
725
-		$emailTemplate->addBodyButton(
726
-			$l->t('Open »%s«', [$filename]),
727
-			$link
728
-		);
729
-
730
-		$message->setTo([$shareWith]);
731
-
732
-		// The "From" contains the sharers name
733
-		$instanceName = $this->defaults->getName();
734
-		$senderName = $l->t(
735
-			'%s via %s',
736
-			[
737
-				$initiatorDisplayName,
738
-				$instanceName
739
-			]
740
-		);
741
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
742
-
743
-		// The "Reply-To" is set to the sharer if an mail address is configured
744
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
745
-		$initiatorEmail = $initiatorUser->getEMailAddress();
746
-		if($initiatorEmail !== null) {
747
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
748
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
749
-		} else {
750
-			$emailTemplate->addFooter();
751
-		}
752
-
753
-		$message->useTemplate($emailTemplate);
754
-		$this->mailer->send($message);
755
-	}
756
-
757
-	/**
758
-	 * Update a share
759
-	 *
760
-	 * @param \OCP\Share\IShare $share
761
-	 * @return \OCP\Share\IShare The share object
762
-	 * @throws \InvalidArgumentException
763
-	 */
764
-	public function updateShare(\OCP\Share\IShare $share) {
765
-		$expirationDateUpdated = false;
766
-
767
-		$this->canShare($share);
768
-
769
-		try {
770
-			$originalShare = $this->getShareById($share->getFullId());
771
-		} catch (\UnexpectedValueException $e) {
772
-			throw new \InvalidArgumentException('Share does not have a full id');
773
-		}
774
-
775
-		// We can't change the share type!
776
-		if ($share->getShareType() !== $originalShare->getShareType()) {
777
-			throw new \InvalidArgumentException('Can’t change share type');
778
-		}
779
-
780
-		// We can only change the recipient on user shares
781
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
782
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
783
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
784
-		}
785
-
786
-		// Cannot share with the owner
787
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
788
-			$share->getSharedWith() === $share->getShareOwner()) {
789
-			throw new \InvalidArgumentException('Can’t share with the share owner');
790
-		}
791
-
792
-		$this->generalCreateChecks($share);
793
-
794
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
795
-			$this->userCreateChecks($share);
796
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
797
-			$this->groupCreateChecks($share);
798
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
799
-			$this->linkCreateChecks($share);
800
-
801
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
802
-
803
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
804
-				//Verify the expiration date
805
-				$this->validateExpirationDate($share);
806
-				$expirationDateUpdated = true;
807
-			}
808
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
809
-			$plainTextPassword = $share->getPassword();
810
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
811
-				$plainTextPassword = null;
812
-			}
813
-		}
814
-
815
-		$this->pathCreateChecks($share->getNode());
816
-
817
-		// Now update the share!
818
-		$provider = $this->factory->getProviderForType($share->getShareType());
819
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
820
-			$share = $provider->update($share, $plainTextPassword);
821
-		} else {
822
-			$share = $provider->update($share);
823
-		}
824
-
825
-		if ($expirationDateUpdated === true) {
826
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
827
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
828
-				'itemSource' => $share->getNode()->getId(),
829
-				'date' => $share->getExpirationDate(),
830
-				'uidOwner' => $share->getSharedBy(),
831
-			]);
832
-		}
833
-
834
-		if ($share->getPassword() !== $originalShare->getPassword()) {
835
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
836
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
837
-				'itemSource' => $share->getNode()->getId(),
838
-				'uidOwner' => $share->getSharedBy(),
839
-				'token' => $share->getToken(),
840
-				'disabled' => is_null($share->getPassword()),
841
-			]);
842
-		}
843
-
844
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
845
-			if ($this->userManager->userExists($share->getShareOwner())) {
846
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
847
-			} else {
848
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
849
-			}
850
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
851
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
852
-				'itemSource' => $share->getNode()->getId(),
853
-				'shareType' => $share->getShareType(),
854
-				'shareWith' => $share->getSharedWith(),
855
-				'uidOwner' => $share->getSharedBy(),
856
-				'permissions' => $share->getPermissions(),
857
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
858
-			));
859
-		}
860
-
861
-		return $share;
862
-	}
863
-
864
-	/**
865
-	 * Updates the password of the given share if it is not the same as the
866
-	 * password of the original share.
867
-	 *
868
-	 * @param \OCP\Share\IShare $share the share to update its password.
869
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
870
-	 *        password with.
871
-	 * @return boolean whether the password was updated or not.
872
-	 */
873
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
874
-		// Password updated.
875
-		if ($share->getPassword() !== $originalShare->getPassword()) {
876
-			//Verify the password
877
-			$this->verifyPassword($share->getPassword());
878
-
879
-			// If a password is set. Hash it!
880
-			if ($share->getPassword() !== null) {
881
-				$share->setPassword($this->hasher->hash($share->getPassword()));
882
-
883
-				return true;
884
-			}
885
-		}
886
-
887
-		return false;
888
-	}
889
-
890
-	/**
891
-	 * Delete all the children of this share
892
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
893
-	 *
894
-	 * @param \OCP\Share\IShare $share
895
-	 * @return \OCP\Share\IShare[] List of deleted shares
896
-	 */
897
-	protected function deleteChildren(\OCP\Share\IShare $share) {
898
-		$deletedShares = [];
899
-
900
-		$provider = $this->factory->getProviderForType($share->getShareType());
901
-
902
-		foreach ($provider->getChildren($share) as $child) {
903
-			$deletedChildren = $this->deleteChildren($child);
904
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
905
-
906
-			$provider->delete($child);
907
-			$deletedShares[] = $child;
908
-		}
909
-
910
-		return $deletedShares;
911
-	}
912
-
913
-	/**
914
-	 * Delete a share
915
-	 *
916
-	 * @param \OCP\Share\IShare $share
917
-	 * @throws ShareNotFound
918
-	 * @throws \InvalidArgumentException
919
-	 */
920
-	public function deleteShare(\OCP\Share\IShare $share) {
921
-
922
-		try {
923
-			$share->getFullId();
924
-		} catch (\UnexpectedValueException $e) {
925
-			throw new \InvalidArgumentException('Share does not have a full id');
926
-		}
927
-
928
-		$event = new GenericEvent($share);
929
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
930
-
931
-		// Get all children and delete them as well
932
-		$deletedShares = $this->deleteChildren($share);
933
-
934
-		// Do the actual delete
935
-		$provider = $this->factory->getProviderForType($share->getShareType());
936
-		$provider->delete($share);
937
-
938
-		// All the deleted shares caused by this delete
939
-		$deletedShares[] = $share;
940
-
941
-		// Emit post hook
942
-		$event->setArgument('deletedShares', $deletedShares);
943
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
944
-	}
945
-
946
-
947
-	/**
948
-	 * Unshare a file as the recipient.
949
-	 * This can be different from a regular delete for example when one of
950
-	 * the users in a groups deletes that share. But the provider should
951
-	 * handle this.
952
-	 *
953
-	 * @param \OCP\Share\IShare $share
954
-	 * @param string $recipientId
955
-	 */
956
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
957
-		list($providerId, ) = $this->splitFullId($share->getFullId());
958
-		$provider = $this->factory->getProvider($providerId);
959
-
960
-		$provider->deleteFromSelf($share, $recipientId);
961
-		$event = new GenericEvent($share);
962
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
963
-	}
964
-
965
-	/**
966
-	 * @inheritdoc
967
-	 */
968
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
969
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
970
-			throw new \InvalidArgumentException('Can’t change target of link share');
971
-		}
972
-
973
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
974
-			throw new \InvalidArgumentException('Invalid recipient');
975
-		}
976
-
977
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
978
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
979
-			if (is_null($sharedWith)) {
980
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
981
-			}
982
-			$recipient = $this->userManager->get($recipientId);
983
-			if (!$sharedWith->inGroup($recipient)) {
984
-				throw new \InvalidArgumentException('Invalid recipient');
985
-			}
986
-		}
987
-
988
-		list($providerId, ) = $this->splitFullId($share->getFullId());
989
-		$provider = $this->factory->getProvider($providerId);
990
-
991
-		$provider->move($share, $recipientId);
992
-	}
993
-
994
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
995
-		$providers = $this->factory->getAllProviders();
996
-
997
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
998
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
999
-			foreach ($newShares as $fid => $data) {
1000
-				if (!isset($shares[$fid])) {
1001
-					$shares[$fid] = [];
1002
-				}
1003
-
1004
-				$shares[$fid] = array_merge($shares[$fid], $data);
1005
-			}
1006
-			return $shares;
1007
-		}, []);
1008
-	}
1009
-
1010
-	/**
1011
-	 * @inheritdoc
1012
-	 */
1013
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1014
-		if ($path !== null &&
1015
-				!($path instanceof \OCP\Files\File) &&
1016
-				!($path instanceof \OCP\Files\Folder)) {
1017
-			throw new \InvalidArgumentException('invalid path');
1018
-		}
1019
-
1020
-		try {
1021
-			$provider = $this->factory->getProviderForType($shareType);
1022
-		} catch (ProviderException $e) {
1023
-			return [];
1024
-		}
1025
-
1026
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1027
-
1028
-		/*
607
+            $share->setToken(
608
+                $this->secureRandom->generate(
609
+                    \OC\Share\Constants::TOKEN_LENGTH,
610
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
611
+                )
612
+            );
613
+
614
+            //Verify the expiration date
615
+            $this->validateExpirationDate($share);
616
+
617
+            //Verify the password
618
+            $this->verifyPassword($share->getPassword());
619
+
620
+            // If a password is set. Hash it!
621
+            if ($share->getPassword() !== null) {
622
+                $share->setPassword($this->hasher->hash($share->getPassword()));
623
+            }
624
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
+            $share->setToken(
626
+                $this->secureRandom->generate(
627
+                    \OC\Share\Constants::TOKEN_LENGTH,
628
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
629
+                )
630
+            );
631
+        }
632
+
633
+        // Cannot share with the owner
634
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
635
+            $share->getSharedWith() === $share->getShareOwner()) {
636
+            throw new \InvalidArgumentException('Can’t share with the share owner');
637
+        }
638
+
639
+        // Generate the target
640
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
641
+        $target = \OC\Files\Filesystem::normalizePath($target);
642
+        $share->setTarget($target);
643
+
644
+        // Pre share event
645
+        $event = new GenericEvent($share);
646
+        $a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
647
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
648
+            throw new \Exception($event->getArgument('error'));
649
+        }
650
+
651
+        $oldShare = $share;
652
+        $provider = $this->factory->getProviderForType($share->getShareType());
653
+        $share = $provider->create($share);
654
+        //reuse the node we already have
655
+        $share->setNode($oldShare->getNode());
656
+
657
+        // Post share event
658
+        $event = new GenericEvent($share);
659
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
660
+
661
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662
+            $user = $this->userManager->get($share->getSharedWith());
663
+            if ($user !== null) {
664
+                $emailAddress = $user->getEMailAddress();
665
+                if ($emailAddress !== null && $emailAddress !== '') {
666
+                    $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
667
+                    $l = $this->l10nFactory->get('lib', $userLang);
668
+                    $this->sendMailNotification(
669
+                        $l,
670
+                        $share->getNode()->getName(),
671
+                        $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
672
+                        $share->getSharedBy(),
673
+                        $emailAddress,
674
+                        $share->getExpirationDate()
675
+                    );
676
+                    $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
677
+                } else {
678
+                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
679
+                }
680
+            } else {
681
+                $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
682
+            }
683
+        }
684
+
685
+        return $share;
686
+    }
687
+
688
+    /**
689
+     * @param IL10N $l Language of the recipient
690
+     * @param string $filename file/folder name
691
+     * @param string $link link to the file/folder
692
+     * @param string $initiator user ID of share sender
693
+     * @param string $shareWith email address of share receiver
694
+     * @param \DateTime|null $expiration
695
+     * @throws \Exception If mail couldn't be sent
696
+     */
697
+    protected function sendMailNotification(IL10N $l,
698
+                                            $filename,
699
+                                            $link,
700
+                                            $initiator,
701
+                                            $shareWith,
702
+                                            \DateTime $expiration = null) {
703
+        $initiatorUser = $this->userManager->get($initiator);
704
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
705
+
706
+        $message = $this->mailer->createMessage();
707
+
708
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
709
+            'filename' => $filename,
710
+            'link' => $link,
711
+            'initiator' => $initiatorDisplayName,
712
+            'expiration' => $expiration,
713
+            'shareWith' => $shareWith,
714
+        ]);
715
+
716
+        $emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
717
+        $emailTemplate->addHeader();
718
+        $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
719
+        $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
720
+
721
+        $emailTemplate->addBodyText(
722
+            $text . ' ' . $l->t('Click the button below to open it.'),
723
+            $text
724
+        );
725
+        $emailTemplate->addBodyButton(
726
+            $l->t('Open »%s«', [$filename]),
727
+            $link
728
+        );
729
+
730
+        $message->setTo([$shareWith]);
731
+
732
+        // The "From" contains the sharers name
733
+        $instanceName = $this->defaults->getName();
734
+        $senderName = $l->t(
735
+            '%s via %s',
736
+            [
737
+                $initiatorDisplayName,
738
+                $instanceName
739
+            ]
740
+        );
741
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
742
+
743
+        // The "Reply-To" is set to the sharer if an mail address is configured
744
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
745
+        $initiatorEmail = $initiatorUser->getEMailAddress();
746
+        if($initiatorEmail !== null) {
747
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
748
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
749
+        } else {
750
+            $emailTemplate->addFooter();
751
+        }
752
+
753
+        $message->useTemplate($emailTemplate);
754
+        $this->mailer->send($message);
755
+    }
756
+
757
+    /**
758
+     * Update a share
759
+     *
760
+     * @param \OCP\Share\IShare $share
761
+     * @return \OCP\Share\IShare The share object
762
+     * @throws \InvalidArgumentException
763
+     */
764
+    public function updateShare(\OCP\Share\IShare $share) {
765
+        $expirationDateUpdated = false;
766
+
767
+        $this->canShare($share);
768
+
769
+        try {
770
+            $originalShare = $this->getShareById($share->getFullId());
771
+        } catch (\UnexpectedValueException $e) {
772
+            throw new \InvalidArgumentException('Share does not have a full id');
773
+        }
774
+
775
+        // We can't change the share type!
776
+        if ($share->getShareType() !== $originalShare->getShareType()) {
777
+            throw new \InvalidArgumentException('Can’t change share type');
778
+        }
779
+
780
+        // We can only change the recipient on user shares
781
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
782
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
783
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
784
+        }
785
+
786
+        // Cannot share with the owner
787
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
788
+            $share->getSharedWith() === $share->getShareOwner()) {
789
+            throw new \InvalidArgumentException('Can’t share with the share owner');
790
+        }
791
+
792
+        $this->generalCreateChecks($share);
793
+
794
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
795
+            $this->userCreateChecks($share);
796
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
797
+            $this->groupCreateChecks($share);
798
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
799
+            $this->linkCreateChecks($share);
800
+
801
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
802
+
803
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
804
+                //Verify the expiration date
805
+                $this->validateExpirationDate($share);
806
+                $expirationDateUpdated = true;
807
+            }
808
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
809
+            $plainTextPassword = $share->getPassword();
810
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
811
+                $plainTextPassword = null;
812
+            }
813
+        }
814
+
815
+        $this->pathCreateChecks($share->getNode());
816
+
817
+        // Now update the share!
818
+        $provider = $this->factory->getProviderForType($share->getShareType());
819
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
820
+            $share = $provider->update($share, $plainTextPassword);
821
+        } else {
822
+            $share = $provider->update($share);
823
+        }
824
+
825
+        if ($expirationDateUpdated === true) {
826
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
827
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
828
+                'itemSource' => $share->getNode()->getId(),
829
+                'date' => $share->getExpirationDate(),
830
+                'uidOwner' => $share->getSharedBy(),
831
+            ]);
832
+        }
833
+
834
+        if ($share->getPassword() !== $originalShare->getPassword()) {
835
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
836
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
837
+                'itemSource' => $share->getNode()->getId(),
838
+                'uidOwner' => $share->getSharedBy(),
839
+                'token' => $share->getToken(),
840
+                'disabled' => is_null($share->getPassword()),
841
+            ]);
842
+        }
843
+
844
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
845
+            if ($this->userManager->userExists($share->getShareOwner())) {
846
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
847
+            } else {
848
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
849
+            }
850
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
851
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
852
+                'itemSource' => $share->getNode()->getId(),
853
+                'shareType' => $share->getShareType(),
854
+                'shareWith' => $share->getSharedWith(),
855
+                'uidOwner' => $share->getSharedBy(),
856
+                'permissions' => $share->getPermissions(),
857
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
858
+            ));
859
+        }
860
+
861
+        return $share;
862
+    }
863
+
864
+    /**
865
+     * Updates the password of the given share if it is not the same as the
866
+     * password of the original share.
867
+     *
868
+     * @param \OCP\Share\IShare $share the share to update its password.
869
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
870
+     *        password with.
871
+     * @return boolean whether the password was updated or not.
872
+     */
873
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
874
+        // Password updated.
875
+        if ($share->getPassword() !== $originalShare->getPassword()) {
876
+            //Verify the password
877
+            $this->verifyPassword($share->getPassword());
878
+
879
+            // If a password is set. Hash it!
880
+            if ($share->getPassword() !== null) {
881
+                $share->setPassword($this->hasher->hash($share->getPassword()));
882
+
883
+                return true;
884
+            }
885
+        }
886
+
887
+        return false;
888
+    }
889
+
890
+    /**
891
+     * Delete all the children of this share
892
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
893
+     *
894
+     * @param \OCP\Share\IShare $share
895
+     * @return \OCP\Share\IShare[] List of deleted shares
896
+     */
897
+    protected function deleteChildren(\OCP\Share\IShare $share) {
898
+        $deletedShares = [];
899
+
900
+        $provider = $this->factory->getProviderForType($share->getShareType());
901
+
902
+        foreach ($provider->getChildren($share) as $child) {
903
+            $deletedChildren = $this->deleteChildren($child);
904
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
905
+
906
+            $provider->delete($child);
907
+            $deletedShares[] = $child;
908
+        }
909
+
910
+        return $deletedShares;
911
+    }
912
+
913
+    /**
914
+     * Delete a share
915
+     *
916
+     * @param \OCP\Share\IShare $share
917
+     * @throws ShareNotFound
918
+     * @throws \InvalidArgumentException
919
+     */
920
+    public function deleteShare(\OCP\Share\IShare $share) {
921
+
922
+        try {
923
+            $share->getFullId();
924
+        } catch (\UnexpectedValueException $e) {
925
+            throw new \InvalidArgumentException('Share does not have a full id');
926
+        }
927
+
928
+        $event = new GenericEvent($share);
929
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
930
+
931
+        // Get all children and delete them as well
932
+        $deletedShares = $this->deleteChildren($share);
933
+
934
+        // Do the actual delete
935
+        $provider = $this->factory->getProviderForType($share->getShareType());
936
+        $provider->delete($share);
937
+
938
+        // All the deleted shares caused by this delete
939
+        $deletedShares[] = $share;
940
+
941
+        // Emit post hook
942
+        $event->setArgument('deletedShares', $deletedShares);
943
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
944
+    }
945
+
946
+
947
+    /**
948
+     * Unshare a file as the recipient.
949
+     * This can be different from a regular delete for example when one of
950
+     * the users in a groups deletes that share. But the provider should
951
+     * handle this.
952
+     *
953
+     * @param \OCP\Share\IShare $share
954
+     * @param string $recipientId
955
+     */
956
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
957
+        list($providerId, ) = $this->splitFullId($share->getFullId());
958
+        $provider = $this->factory->getProvider($providerId);
959
+
960
+        $provider->deleteFromSelf($share, $recipientId);
961
+        $event = new GenericEvent($share);
962
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
963
+    }
964
+
965
+    /**
966
+     * @inheritdoc
967
+     */
968
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
969
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
970
+            throw new \InvalidArgumentException('Can’t change target of link share');
971
+        }
972
+
973
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
974
+            throw new \InvalidArgumentException('Invalid recipient');
975
+        }
976
+
977
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
978
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
979
+            if (is_null($sharedWith)) {
980
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
981
+            }
982
+            $recipient = $this->userManager->get($recipientId);
983
+            if (!$sharedWith->inGroup($recipient)) {
984
+                throw new \InvalidArgumentException('Invalid recipient');
985
+            }
986
+        }
987
+
988
+        list($providerId, ) = $this->splitFullId($share->getFullId());
989
+        $provider = $this->factory->getProvider($providerId);
990
+
991
+        $provider->move($share, $recipientId);
992
+    }
993
+
994
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
995
+        $providers = $this->factory->getAllProviders();
996
+
997
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
998
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
999
+            foreach ($newShares as $fid => $data) {
1000
+                if (!isset($shares[$fid])) {
1001
+                    $shares[$fid] = [];
1002
+                }
1003
+
1004
+                $shares[$fid] = array_merge($shares[$fid], $data);
1005
+            }
1006
+            return $shares;
1007
+        }, []);
1008
+    }
1009
+
1010
+    /**
1011
+     * @inheritdoc
1012
+     */
1013
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1014
+        if ($path !== null &&
1015
+                !($path instanceof \OCP\Files\File) &&
1016
+                !($path instanceof \OCP\Files\Folder)) {
1017
+            throw new \InvalidArgumentException('invalid path');
1018
+        }
1019
+
1020
+        try {
1021
+            $provider = $this->factory->getProviderForType($shareType);
1022
+        } catch (ProviderException $e) {
1023
+            return [];
1024
+        }
1025
+
1026
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1027
+
1028
+        /*
1029 1029
 		 * Work around so we don't return expired shares but still follow
1030 1030
 		 * proper pagination.
1031 1031
 		 */
1032 1032
 
1033
-		$shares2 = [];
1034
-
1035
-		while(true) {
1036
-			$added = 0;
1037
-			foreach ($shares as $share) {
1038
-
1039
-				try {
1040
-					$this->checkExpireDate($share);
1041
-				} catch (ShareNotFound $e) {
1042
-					//Ignore since this basically means the share is deleted
1043
-					continue;
1044
-				}
1045
-
1046
-				$added++;
1047
-				$shares2[] = $share;
1048
-
1049
-				if (count($shares2) === $limit) {
1050
-					break;
1051
-				}
1052
-			}
1053
-
1054
-			// If we did not fetch more shares than the limit then there are no more shares
1055
-			if (count($shares) < $limit) {
1056
-				break;
1057
-			}
1058
-
1059
-			if (count($shares2) === $limit) {
1060
-				break;
1061
-			}
1062
-
1063
-			// If there was no limit on the select we are done
1064
-			if ($limit === -1) {
1065
-				break;
1066
-			}
1067
-
1068
-			$offset += $added;
1069
-
1070
-			// Fetch again $limit shares
1071
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1072
-
1073
-			// No more shares means we are done
1074
-			if (empty($shares)) {
1075
-				break;
1076
-			}
1077
-		}
1078
-
1079
-		$shares = $shares2;
1080
-
1081
-		return $shares;
1082
-	}
1083
-
1084
-	/**
1085
-	 * @inheritdoc
1086
-	 */
1087
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1088
-		try {
1089
-			$provider = $this->factory->getProviderForType($shareType);
1090
-		} catch (ProviderException $e) {
1091
-			return [];
1092
-		}
1093
-
1094
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1095
-
1096
-		// remove all shares which are already expired
1097
-		foreach ($shares as $key => $share) {
1098
-			try {
1099
-				$this->checkExpireDate($share);
1100
-			} catch (ShareNotFound $e) {
1101
-				unset($shares[$key]);
1102
-			}
1103
-		}
1104
-
1105
-		return $shares;
1106
-	}
1107
-
1108
-	/**
1109
-	 * @inheritdoc
1110
-	 */
1111
-	public function getShareById($id, $recipient = null) {
1112
-		if ($id === null) {
1113
-			throw new ShareNotFound();
1114
-		}
1115
-
1116
-		list($providerId, $id) = $this->splitFullId($id);
1117
-
1118
-		try {
1119
-			$provider = $this->factory->getProvider($providerId);
1120
-		} catch (ProviderException $e) {
1121
-			throw new ShareNotFound();
1122
-		}
1123
-
1124
-		$share = $provider->getShareById($id, $recipient);
1125
-
1126
-		$this->checkExpireDate($share);
1127
-
1128
-		return $share;
1129
-	}
1130
-
1131
-	/**
1132
-	 * Get all the shares for a given path
1133
-	 *
1134
-	 * @param \OCP\Files\Node $path
1135
-	 * @param int $page
1136
-	 * @param int $perPage
1137
-	 *
1138
-	 * @return Share[]
1139
-	 */
1140
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1141
-		return [];
1142
-	}
1143
-
1144
-	/**
1145
-	 * Get the share by token possible with password
1146
-	 *
1147
-	 * @param string $token
1148
-	 * @return Share
1149
-	 *
1150
-	 * @throws ShareNotFound
1151
-	 */
1152
-	public function getShareByToken($token) {
1153
-		$share = null;
1154
-		try {
1155
-			if($this->shareApiAllowLinks()) {
1156
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1157
-				$share = $provider->getShareByToken($token);
1158
-			}
1159
-		} catch (ProviderException $e) {
1160
-		} catch (ShareNotFound $e) {
1161
-		}
1162
-
1163
-
1164
-		// If it is not a link share try to fetch a federated share by token
1165
-		if ($share === null) {
1166
-			try {
1167
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1168
-				$share = $provider->getShareByToken($token);
1169
-			} catch (ProviderException $e) {
1170
-			} catch (ShareNotFound $e) {
1171
-			}
1172
-		}
1173
-
1174
-		// If it is not a link share try to fetch a mail share by token
1175
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1176
-			try {
1177
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1178
-				$share = $provider->getShareByToken($token);
1179
-			} catch (ProviderException $e) {
1180
-			} catch (ShareNotFound $e) {
1181
-			}
1182
-		}
1183
-
1184
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1185
-			try {
1186
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1187
-				$share = $provider->getShareByToken($token);
1188
-			} catch (ProviderException $e) {
1189
-			} catch (ShareNotFound $e) {
1190
-			}
1191
-		}
1192
-
1193
-		if ($share === null) {
1194
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1195
-		}
1196
-
1197
-		$this->checkExpireDate($share);
1198
-
1199
-		/*
1033
+        $shares2 = [];
1034
+
1035
+        while(true) {
1036
+            $added = 0;
1037
+            foreach ($shares as $share) {
1038
+
1039
+                try {
1040
+                    $this->checkExpireDate($share);
1041
+                } catch (ShareNotFound $e) {
1042
+                    //Ignore since this basically means the share is deleted
1043
+                    continue;
1044
+                }
1045
+
1046
+                $added++;
1047
+                $shares2[] = $share;
1048
+
1049
+                if (count($shares2) === $limit) {
1050
+                    break;
1051
+                }
1052
+            }
1053
+
1054
+            // If we did not fetch more shares than the limit then there are no more shares
1055
+            if (count($shares) < $limit) {
1056
+                break;
1057
+            }
1058
+
1059
+            if (count($shares2) === $limit) {
1060
+                break;
1061
+            }
1062
+
1063
+            // If there was no limit on the select we are done
1064
+            if ($limit === -1) {
1065
+                break;
1066
+            }
1067
+
1068
+            $offset += $added;
1069
+
1070
+            // Fetch again $limit shares
1071
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1072
+
1073
+            // No more shares means we are done
1074
+            if (empty($shares)) {
1075
+                break;
1076
+            }
1077
+        }
1078
+
1079
+        $shares = $shares2;
1080
+
1081
+        return $shares;
1082
+    }
1083
+
1084
+    /**
1085
+     * @inheritdoc
1086
+     */
1087
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1088
+        try {
1089
+            $provider = $this->factory->getProviderForType($shareType);
1090
+        } catch (ProviderException $e) {
1091
+            return [];
1092
+        }
1093
+
1094
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1095
+
1096
+        // remove all shares which are already expired
1097
+        foreach ($shares as $key => $share) {
1098
+            try {
1099
+                $this->checkExpireDate($share);
1100
+            } catch (ShareNotFound $e) {
1101
+                unset($shares[$key]);
1102
+            }
1103
+        }
1104
+
1105
+        return $shares;
1106
+    }
1107
+
1108
+    /**
1109
+     * @inheritdoc
1110
+     */
1111
+    public function getShareById($id, $recipient = null) {
1112
+        if ($id === null) {
1113
+            throw new ShareNotFound();
1114
+        }
1115
+
1116
+        list($providerId, $id) = $this->splitFullId($id);
1117
+
1118
+        try {
1119
+            $provider = $this->factory->getProvider($providerId);
1120
+        } catch (ProviderException $e) {
1121
+            throw new ShareNotFound();
1122
+        }
1123
+
1124
+        $share = $provider->getShareById($id, $recipient);
1125
+
1126
+        $this->checkExpireDate($share);
1127
+
1128
+        return $share;
1129
+    }
1130
+
1131
+    /**
1132
+     * Get all the shares for a given path
1133
+     *
1134
+     * @param \OCP\Files\Node $path
1135
+     * @param int $page
1136
+     * @param int $perPage
1137
+     *
1138
+     * @return Share[]
1139
+     */
1140
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1141
+        return [];
1142
+    }
1143
+
1144
+    /**
1145
+     * Get the share by token possible with password
1146
+     *
1147
+     * @param string $token
1148
+     * @return Share
1149
+     *
1150
+     * @throws ShareNotFound
1151
+     */
1152
+    public function getShareByToken($token) {
1153
+        $share = null;
1154
+        try {
1155
+            if($this->shareApiAllowLinks()) {
1156
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1157
+                $share = $provider->getShareByToken($token);
1158
+            }
1159
+        } catch (ProviderException $e) {
1160
+        } catch (ShareNotFound $e) {
1161
+        }
1162
+
1163
+
1164
+        // If it is not a link share try to fetch a federated share by token
1165
+        if ($share === null) {
1166
+            try {
1167
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1168
+                $share = $provider->getShareByToken($token);
1169
+            } catch (ProviderException $e) {
1170
+            } catch (ShareNotFound $e) {
1171
+            }
1172
+        }
1173
+
1174
+        // If it is not a link share try to fetch a mail share by token
1175
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1176
+            try {
1177
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1178
+                $share = $provider->getShareByToken($token);
1179
+            } catch (ProviderException $e) {
1180
+            } catch (ShareNotFound $e) {
1181
+            }
1182
+        }
1183
+
1184
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1185
+            try {
1186
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1187
+                $share = $provider->getShareByToken($token);
1188
+            } catch (ProviderException $e) {
1189
+            } catch (ShareNotFound $e) {
1190
+            }
1191
+        }
1192
+
1193
+        if ($share === null) {
1194
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1195
+        }
1196
+
1197
+        $this->checkExpireDate($share);
1198
+
1199
+        /*
1200 1200
 		 * Reduce the permissions for link shares if public upload is not enabled
1201 1201
 		 */
1202
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1203
-			!$this->shareApiLinkAllowPublicUpload()) {
1204
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1205
-		}
1206
-
1207
-		return $share;
1208
-	}
1209
-
1210
-	protected function checkExpireDate($share) {
1211
-		if ($share->getExpirationDate() !== null &&
1212
-			$share->getExpirationDate() <= new \DateTime()) {
1213
-			$this->deleteShare($share);
1214
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1215
-		}
1216
-
1217
-	}
1218
-
1219
-	/**
1220
-	 * Verify the password of a public share
1221
-	 *
1222
-	 * @param \OCP\Share\IShare $share
1223
-	 * @param string $password
1224
-	 * @return bool
1225
-	 */
1226
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1227
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1228
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1229
-		if (!$passwordProtected) {
1230
-			//TODO maybe exception?
1231
-			return false;
1232
-		}
1233
-
1234
-		if ($password === null || $share->getPassword() === null) {
1235
-			return false;
1236
-		}
1237
-
1238
-		$newHash = '';
1239
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1240
-			return false;
1241
-		}
1242
-
1243
-		if (!empty($newHash)) {
1244
-			$share->setPassword($newHash);
1245
-			$provider = $this->factory->getProviderForType($share->getShareType());
1246
-			$provider->update($share);
1247
-		}
1248
-
1249
-		return true;
1250
-	}
1251
-
1252
-	/**
1253
-	 * @inheritdoc
1254
-	 */
1255
-	public function userDeleted($uid) {
1256
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1257
-
1258
-		foreach ($types as $type) {
1259
-			try {
1260
-				$provider = $this->factory->getProviderForType($type);
1261
-			} catch (ProviderException $e) {
1262
-				continue;
1263
-			}
1264
-			$provider->userDeleted($uid, $type);
1265
-		}
1266
-	}
1267
-
1268
-	/**
1269
-	 * @inheritdoc
1270
-	 */
1271
-	public function groupDeleted($gid) {
1272
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1273
-		$provider->groupDeleted($gid);
1274
-	}
1275
-
1276
-	/**
1277
-	 * @inheritdoc
1278
-	 */
1279
-	public function userDeletedFromGroup($uid, $gid) {
1280
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1281
-		$provider->userDeletedFromGroup($uid, $gid);
1282
-	}
1283
-
1284
-	/**
1285
-	 * Get access list to a path. This means
1286
-	 * all the users that can access a given path.
1287
-	 *
1288
-	 * Consider:
1289
-	 * -root
1290
-	 * |-folder1 (23)
1291
-	 *  |-folder2 (32)
1292
-	 *   |-fileA (42)
1293
-	 *
1294
-	 * fileA is shared with user1 and user1@server1
1295
-	 * folder2 is shared with group2 (user4 is a member of group2)
1296
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1297
-	 *
1298
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1299
-	 * [
1300
-	 *  users  => [
1301
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1302
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1303
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1304
-	 *  ],
1305
-	 *  remote => [
1306
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1307
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1308
-	 *  ],
1309
-	 *  public => bool
1310
-	 *  mail => bool
1311
-	 * ]
1312
-	 *
1313
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1314
-	 * [
1315
-	 *  users  => ['user1', 'user2', 'user4'],
1316
-	 *  remote => bool,
1317
-	 *  public => bool
1318
-	 *  mail => bool
1319
-	 * ]
1320
-	 *
1321
-	 * This is required for encryption/activity
1322
-	 *
1323
-	 * @param \OCP\Files\Node $path
1324
-	 * @param bool $recursive Should we check all parent folders as well
1325
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1326
-	 * @return array
1327
-	 */
1328
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1329
-		$owner = $path->getOwner()->getUID();
1330
-
1331
-		if ($currentAccess) {
1332
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1333
-		} else {
1334
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1335
-		}
1336
-		if (!$this->userManager->userExists($owner)) {
1337
-			return $al;
1338
-		}
1339
-
1340
-		//Get node for the owner
1341
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1342
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1343
-			$path = $userFolder->getById($path->getId())[0];
1344
-		}
1345
-
1346
-		$providers = $this->factory->getAllProviders();
1347
-
1348
-		/** @var Node[] $nodes */
1349
-		$nodes = [];
1350
-
1351
-
1352
-		if ($currentAccess) {
1353
-			$ownerPath = $path->getPath();
1354
-			$ownerPath = explode('/', $ownerPath, 4);
1355
-			if (count($ownerPath) < 4) {
1356
-				$ownerPath = '';
1357
-			} else {
1358
-				$ownerPath = $ownerPath[3];
1359
-			}
1360
-			$al['users'][$owner] = [
1361
-				'node_id' => $path->getId(),
1362
-				'node_path' => '/' . $ownerPath,
1363
-			];
1364
-		} else {
1365
-			$al['users'][] = $owner;
1366
-		}
1367
-
1368
-		// Collect all the shares
1369
-		while ($path->getPath() !== $userFolder->getPath()) {
1370
-			$nodes[] = $path;
1371
-			if (!$recursive) {
1372
-				break;
1373
-			}
1374
-			$path = $path->getParent();
1375
-		}
1376
-
1377
-		foreach ($providers as $provider) {
1378
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1379
-
1380
-			foreach ($tmp as $k => $v) {
1381
-				if (isset($al[$k])) {
1382
-					if (is_array($al[$k])) {
1383
-						$al[$k] = array_merge($al[$k], $v);
1384
-					} else {
1385
-						$al[$k] = $al[$k] || $v;
1386
-					}
1387
-				} else {
1388
-					$al[$k] = $v;
1389
-				}
1390
-			}
1391
-		}
1392
-
1393
-		return $al;
1394
-	}
1395
-
1396
-	/**
1397
-	 * Create a new share
1398
-	 * @return \OCP\Share\IShare;
1399
-	 */
1400
-	public function newShare() {
1401
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1402
-	}
1403
-
1404
-	/**
1405
-	 * Is the share API enabled
1406
-	 *
1407
-	 * @return bool
1408
-	 */
1409
-	public function shareApiEnabled() {
1410
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1411
-	}
1412
-
1413
-	/**
1414
-	 * Is public link sharing enabled
1415
-	 *
1416
-	 * @return bool
1417
-	 */
1418
-	public function shareApiAllowLinks() {
1419
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1420
-	}
1421
-
1422
-	/**
1423
-	 * Is password on public link requires
1424
-	 *
1425
-	 * @return bool
1426
-	 */
1427
-	public function shareApiLinkEnforcePassword() {
1428
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1429
-	}
1430
-
1431
-	/**
1432
-	 * Is default expire date enabled
1433
-	 *
1434
-	 * @return bool
1435
-	 */
1436
-	public function shareApiLinkDefaultExpireDate() {
1437
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1438
-	}
1439
-
1440
-	/**
1441
-	 * Is default expire date enforced
1442
-	 *`
1443
-	 * @return bool
1444
-	 */
1445
-	public function shareApiLinkDefaultExpireDateEnforced() {
1446
-		return $this->shareApiLinkDefaultExpireDate() &&
1447
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1448
-	}
1449
-
1450
-	/**
1451
-	 * Number of default expire days
1452
-	 *shareApiLinkAllowPublicUpload
1453
-	 * @return int
1454
-	 */
1455
-	public function shareApiLinkDefaultExpireDays() {
1456
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1457
-	}
1458
-
1459
-	/**
1460
-	 * Allow public upload on link shares
1461
-	 *
1462
-	 * @return bool
1463
-	 */
1464
-	public function shareApiLinkAllowPublicUpload() {
1465
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1466
-	}
1467
-
1468
-	/**
1469
-	 * check if user can only share with group members
1470
-	 * @return bool
1471
-	 */
1472
-	public function shareWithGroupMembersOnly() {
1473
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1474
-	}
1475
-
1476
-	/**
1477
-	 * Check if users can share with groups
1478
-	 * @return bool
1479
-	 */
1480
-	public function allowGroupSharing() {
1481
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1482
-	}
1483
-
1484
-	/**
1485
-	 * Copied from \OC_Util::isSharingDisabledForUser
1486
-	 *
1487
-	 * TODO: Deprecate fuction from OC_Util
1488
-	 *
1489
-	 * @param string $userId
1490
-	 * @return bool
1491
-	 */
1492
-	public function sharingDisabledForUser($userId) {
1493
-		if ($userId === null) {
1494
-			return false;
1495
-		}
1496
-
1497
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1498
-			return $this->sharingDisabledForUsersCache[$userId];
1499
-		}
1500
-
1501
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1502
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1503
-			$excludedGroups = json_decode($groupsList);
1504
-			if (is_null($excludedGroups)) {
1505
-				$excludedGroups = explode(',', $groupsList);
1506
-				$newValue = json_encode($excludedGroups);
1507
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1508
-			}
1509
-			$user = $this->userManager->get($userId);
1510
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1511
-			if (!empty($usersGroups)) {
1512
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1513
-				// if the user is only in groups which are disabled for sharing then
1514
-				// sharing is also disabled for the user
1515
-				if (empty($remainingGroups)) {
1516
-					$this->sharingDisabledForUsersCache[$userId] = true;
1517
-					return true;
1518
-				}
1519
-			}
1520
-		}
1521
-
1522
-		$this->sharingDisabledForUsersCache[$userId] = false;
1523
-		return false;
1524
-	}
1525
-
1526
-	/**
1527
-	 * @inheritdoc
1528
-	 */
1529
-	public function outgoingServer2ServerSharesAllowed() {
1530
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1531
-	}
1532
-
1533
-	/**
1534
-	 * @inheritdoc
1535
-	 */
1536
-	public function shareProviderExists($shareType) {
1537
-		try {
1538
-			$this->factory->getProviderForType($shareType);
1539
-		} catch (ProviderException $e) {
1540
-			return false;
1541
-		}
1542
-
1543
-		return true;
1544
-	}
1202
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1203
+            !$this->shareApiLinkAllowPublicUpload()) {
1204
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1205
+        }
1206
+
1207
+        return $share;
1208
+    }
1209
+
1210
+    protected function checkExpireDate($share) {
1211
+        if ($share->getExpirationDate() !== null &&
1212
+            $share->getExpirationDate() <= new \DateTime()) {
1213
+            $this->deleteShare($share);
1214
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1215
+        }
1216
+
1217
+    }
1218
+
1219
+    /**
1220
+     * Verify the password of a public share
1221
+     *
1222
+     * @param \OCP\Share\IShare $share
1223
+     * @param string $password
1224
+     * @return bool
1225
+     */
1226
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1227
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1228
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1229
+        if (!$passwordProtected) {
1230
+            //TODO maybe exception?
1231
+            return false;
1232
+        }
1233
+
1234
+        if ($password === null || $share->getPassword() === null) {
1235
+            return false;
1236
+        }
1237
+
1238
+        $newHash = '';
1239
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1240
+            return false;
1241
+        }
1242
+
1243
+        if (!empty($newHash)) {
1244
+            $share->setPassword($newHash);
1245
+            $provider = $this->factory->getProviderForType($share->getShareType());
1246
+            $provider->update($share);
1247
+        }
1248
+
1249
+        return true;
1250
+    }
1251
+
1252
+    /**
1253
+     * @inheritdoc
1254
+     */
1255
+    public function userDeleted($uid) {
1256
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1257
+
1258
+        foreach ($types as $type) {
1259
+            try {
1260
+                $provider = $this->factory->getProviderForType($type);
1261
+            } catch (ProviderException $e) {
1262
+                continue;
1263
+            }
1264
+            $provider->userDeleted($uid, $type);
1265
+        }
1266
+    }
1267
+
1268
+    /**
1269
+     * @inheritdoc
1270
+     */
1271
+    public function groupDeleted($gid) {
1272
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1273
+        $provider->groupDeleted($gid);
1274
+    }
1275
+
1276
+    /**
1277
+     * @inheritdoc
1278
+     */
1279
+    public function userDeletedFromGroup($uid, $gid) {
1280
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1281
+        $provider->userDeletedFromGroup($uid, $gid);
1282
+    }
1283
+
1284
+    /**
1285
+     * Get access list to a path. This means
1286
+     * all the users that can access a given path.
1287
+     *
1288
+     * Consider:
1289
+     * -root
1290
+     * |-folder1 (23)
1291
+     *  |-folder2 (32)
1292
+     *   |-fileA (42)
1293
+     *
1294
+     * fileA is shared with user1 and user1@server1
1295
+     * folder2 is shared with group2 (user4 is a member of group2)
1296
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1297
+     *
1298
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1299
+     * [
1300
+     *  users  => [
1301
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1302
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1303
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1304
+     *  ],
1305
+     *  remote => [
1306
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1307
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1308
+     *  ],
1309
+     *  public => bool
1310
+     *  mail => bool
1311
+     * ]
1312
+     *
1313
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1314
+     * [
1315
+     *  users  => ['user1', 'user2', 'user4'],
1316
+     *  remote => bool,
1317
+     *  public => bool
1318
+     *  mail => bool
1319
+     * ]
1320
+     *
1321
+     * This is required for encryption/activity
1322
+     *
1323
+     * @param \OCP\Files\Node $path
1324
+     * @param bool $recursive Should we check all parent folders as well
1325
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1326
+     * @return array
1327
+     */
1328
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1329
+        $owner = $path->getOwner()->getUID();
1330
+
1331
+        if ($currentAccess) {
1332
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1333
+        } else {
1334
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1335
+        }
1336
+        if (!$this->userManager->userExists($owner)) {
1337
+            return $al;
1338
+        }
1339
+
1340
+        //Get node for the owner
1341
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1342
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1343
+            $path = $userFolder->getById($path->getId())[0];
1344
+        }
1345
+
1346
+        $providers = $this->factory->getAllProviders();
1347
+
1348
+        /** @var Node[] $nodes */
1349
+        $nodes = [];
1350
+
1351
+
1352
+        if ($currentAccess) {
1353
+            $ownerPath = $path->getPath();
1354
+            $ownerPath = explode('/', $ownerPath, 4);
1355
+            if (count($ownerPath) < 4) {
1356
+                $ownerPath = '';
1357
+            } else {
1358
+                $ownerPath = $ownerPath[3];
1359
+            }
1360
+            $al['users'][$owner] = [
1361
+                'node_id' => $path->getId(),
1362
+                'node_path' => '/' . $ownerPath,
1363
+            ];
1364
+        } else {
1365
+            $al['users'][] = $owner;
1366
+        }
1367
+
1368
+        // Collect all the shares
1369
+        while ($path->getPath() !== $userFolder->getPath()) {
1370
+            $nodes[] = $path;
1371
+            if (!$recursive) {
1372
+                break;
1373
+            }
1374
+            $path = $path->getParent();
1375
+        }
1376
+
1377
+        foreach ($providers as $provider) {
1378
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1379
+
1380
+            foreach ($tmp as $k => $v) {
1381
+                if (isset($al[$k])) {
1382
+                    if (is_array($al[$k])) {
1383
+                        $al[$k] = array_merge($al[$k], $v);
1384
+                    } else {
1385
+                        $al[$k] = $al[$k] || $v;
1386
+                    }
1387
+                } else {
1388
+                    $al[$k] = $v;
1389
+                }
1390
+            }
1391
+        }
1392
+
1393
+        return $al;
1394
+    }
1395
+
1396
+    /**
1397
+     * Create a new share
1398
+     * @return \OCP\Share\IShare;
1399
+     */
1400
+    public function newShare() {
1401
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1402
+    }
1403
+
1404
+    /**
1405
+     * Is the share API enabled
1406
+     *
1407
+     * @return bool
1408
+     */
1409
+    public function shareApiEnabled() {
1410
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1411
+    }
1412
+
1413
+    /**
1414
+     * Is public link sharing enabled
1415
+     *
1416
+     * @return bool
1417
+     */
1418
+    public function shareApiAllowLinks() {
1419
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1420
+    }
1421
+
1422
+    /**
1423
+     * Is password on public link requires
1424
+     *
1425
+     * @return bool
1426
+     */
1427
+    public function shareApiLinkEnforcePassword() {
1428
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1429
+    }
1430
+
1431
+    /**
1432
+     * Is default expire date enabled
1433
+     *
1434
+     * @return bool
1435
+     */
1436
+    public function shareApiLinkDefaultExpireDate() {
1437
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1438
+    }
1439
+
1440
+    /**
1441
+     * Is default expire date enforced
1442
+     *`
1443
+     * @return bool
1444
+     */
1445
+    public function shareApiLinkDefaultExpireDateEnforced() {
1446
+        return $this->shareApiLinkDefaultExpireDate() &&
1447
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1448
+    }
1449
+
1450
+    /**
1451
+     * Number of default expire days
1452
+     *shareApiLinkAllowPublicUpload
1453
+     * @return int
1454
+     */
1455
+    public function shareApiLinkDefaultExpireDays() {
1456
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1457
+    }
1458
+
1459
+    /**
1460
+     * Allow public upload on link shares
1461
+     *
1462
+     * @return bool
1463
+     */
1464
+    public function shareApiLinkAllowPublicUpload() {
1465
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1466
+    }
1467
+
1468
+    /**
1469
+     * check if user can only share with group members
1470
+     * @return bool
1471
+     */
1472
+    public function shareWithGroupMembersOnly() {
1473
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1474
+    }
1475
+
1476
+    /**
1477
+     * Check if users can share with groups
1478
+     * @return bool
1479
+     */
1480
+    public function allowGroupSharing() {
1481
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1482
+    }
1483
+
1484
+    /**
1485
+     * Copied from \OC_Util::isSharingDisabledForUser
1486
+     *
1487
+     * TODO: Deprecate fuction from OC_Util
1488
+     *
1489
+     * @param string $userId
1490
+     * @return bool
1491
+     */
1492
+    public function sharingDisabledForUser($userId) {
1493
+        if ($userId === null) {
1494
+            return false;
1495
+        }
1496
+
1497
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1498
+            return $this->sharingDisabledForUsersCache[$userId];
1499
+        }
1500
+
1501
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1502
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1503
+            $excludedGroups = json_decode($groupsList);
1504
+            if (is_null($excludedGroups)) {
1505
+                $excludedGroups = explode(',', $groupsList);
1506
+                $newValue = json_encode($excludedGroups);
1507
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1508
+            }
1509
+            $user = $this->userManager->get($userId);
1510
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1511
+            if (!empty($usersGroups)) {
1512
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1513
+                // if the user is only in groups which are disabled for sharing then
1514
+                // sharing is also disabled for the user
1515
+                if (empty($remainingGroups)) {
1516
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1517
+                    return true;
1518
+                }
1519
+            }
1520
+        }
1521
+
1522
+        $this->sharingDisabledForUsersCache[$userId] = false;
1523
+        return false;
1524
+    }
1525
+
1526
+    /**
1527
+     * @inheritdoc
1528
+     */
1529
+    public function outgoingServer2ServerSharesAllowed() {
1530
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1531
+    }
1532
+
1533
+    /**
1534
+     * @inheritdoc
1535
+     */
1536
+    public function shareProviderExists($shareType) {
1537
+        try {
1538
+            $this->factory->getProviderForType($shareType);
1539
+        } catch (ProviderException $e) {
1540
+            return false;
1541
+        }
1542
+
1543
+        return true;
1544
+    }
1545 1545
 
1546 1546
 }
Please login to merge, or discard this patch.
apps/files_sharing/composer/composer/autoload_classmap.php 1 patch
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -6,52 +6,52 @@
 block discarded – undo
6 6
 $baseDir = $vendorDir;
7 7
 
8 8
 return array(
9
-    'OCA\\Files_Sharing\\Activity\\Filter' => $baseDir . '/../lib/Activity/Filter.php',
10
-    'OCA\\Files_Sharing\\Activity\\Providers\\Base' => $baseDir . '/../lib/Activity/Providers/Base.php',
11
-    'OCA\\Files_Sharing\\Activity\\Providers\\Downloads' => $baseDir . '/../lib/Activity/Providers/Downloads.php',
12
-    'OCA\\Files_Sharing\\Activity\\Providers\\Groups' => $baseDir . '/../lib/Activity/Providers/Groups.php',
13
-    'OCA\\Files_Sharing\\Activity\\Providers\\PublicLinks' => $baseDir . '/../lib/Activity/Providers/PublicLinks.php',
14
-    'OCA\\Files_Sharing\\Activity\\Providers\\RemoteShares' => $baseDir . '/../lib/Activity/Providers/RemoteShares.php',
15
-    'OCA\\Files_Sharing\\Activity\\Providers\\Users' => $baseDir . '/../lib/Activity/Providers/Users.php',
16
-    'OCA\\Files_Sharing\\Activity\\Settings\\PublicLinks' => $baseDir . '/../lib/Activity/Settings/PublicLinks.php',
17
-    'OCA\\Files_Sharing\\Activity\\Settings\\RemoteShare' => $baseDir . '/../lib/Activity/Settings/RemoteShare.php',
18
-    'OCA\\Files_Sharing\\Activity\\Settings\\Shared' => $baseDir . '/../lib/Activity/Settings/Shared.php',
19
-    'OCA\\Files_Sharing\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php',
20
-    'OCA\\Files_Sharing\\Cache' => $baseDir . '/../lib/Cache.php',
21
-    'OCA\\Files_Sharing\\Capabilities' => $baseDir . '/../lib/Capabilities.php',
22
-    'OCA\\Files_Sharing\\Collaboration\\ShareRecipientSorter' => $baseDir . '/../lib/Collaboration/ShareRecipientSorter.php',
23
-    'OCA\\Files_Sharing\\Command\\CleanupRemoteStorages' => $baseDir . '/../lib/Command/CleanupRemoteStorages.php',
24
-    'OCA\\Files_Sharing\\Controller\\ExternalSharesController' => $baseDir . '/../lib/Controller/ExternalSharesController.php',
25
-    'OCA\\Files_Sharing\\Controller\\PublicPreviewController' => $baseDir . '/../lib/Controller/PublicPreviewController.php',
26
-    'OCA\\Files_Sharing\\Controller\\RemoteController' => $baseDir . '/../lib/Controller/RemoteController.php',
27
-    'OCA\\Files_Sharing\\Controller\\ShareAPIController' => $baseDir . '/../lib/Controller/ShareAPIController.php',
28
-    'OCA\\Files_Sharing\\Controller\\ShareController' => $baseDir . '/../lib/Controller/ShareController.php',
29
-    'OCA\\Files_Sharing\\Controller\\ShareInfoController' => $baseDir . '/../lib/Controller/ShareInfoController.php',
30
-    'OCA\\Files_Sharing\\Controller\\ShareesAPIController' => $baseDir . '/../lib/Controller/ShareesAPIController.php',
31
-    'OCA\\Files_Sharing\\DeleteOrphanedSharesJob' => $baseDir . '/../lib/DeleteOrphanedSharesJob.php',
32
-    'OCA\\Files_Sharing\\Exceptions\\BrokenPath' => $baseDir . '/../lib/Exceptions/BrokenPath.php',
33
-    'OCA\\Files_Sharing\\Exceptions\\S2SException' => $baseDir . '/../lib/Exceptions/S2SException.php',
34
-    'OCA\\Files_Sharing\\ExpireSharesJob' => $baseDir . '/../lib/ExpireSharesJob.php',
35
-    'OCA\\Files_Sharing\\External\\Cache' => $baseDir . '/../lib/External/Cache.php',
36
-    'OCA\\Files_Sharing\\External\\Manager' => $baseDir . '/../lib/External/Manager.php',
37
-    'OCA\\Files_Sharing\\External\\Mount' => $baseDir . '/../lib/External/Mount.php',
38
-    'OCA\\Files_Sharing\\External\\MountProvider' => $baseDir . '/../lib/External/MountProvider.php',
39
-    'OCA\\Files_Sharing\\External\\Scanner' => $baseDir . '/../lib/External/Scanner.php',
40
-    'OCA\\Files_Sharing\\External\\Storage' => $baseDir . '/../lib/External/Storage.php',
41
-    'OCA\\Files_Sharing\\External\\Watcher' => $baseDir . '/../lib/External/Watcher.php',
42
-    'OCA\\Files_Sharing\\Helper' => $baseDir . '/../lib/Helper.php',
43
-    'OCA\\Files_Sharing\\Hooks' => $baseDir . '/../lib/Hooks.php',
44
-    'OCA\\Files_Sharing\\ISharedStorage' => $baseDir . '/../lib/ISharedStorage.php',
45
-    'OCA\\Files_Sharing\\Middleware\\OCSShareAPIMiddleware' => $baseDir . '/../lib/Middleware/OCSShareAPIMiddleware.php',
46
-    'OCA\\Files_Sharing\\Middleware\\ShareInfoMiddleware' => $baseDir . '/../lib/Middleware/ShareInfoMiddleware.php',
47
-    'OCA\\Files_Sharing\\Middleware\\SharingCheckMiddleware' => $baseDir . '/../lib/Middleware/SharingCheckMiddleware.php',
48
-    'OCA\\Files_Sharing\\Migration\\OwncloudGuestShareType' => $baseDir . '/../lib/Migration/OwncloudGuestShareType.php',
49
-    'OCA\\Files_Sharing\\Migration\\SetPasswordColumn' => $baseDir . '/../lib/Migration/SetPasswordColumn.php',
50
-    'OCA\\Files_Sharing\\MountProvider' => $baseDir . '/../lib/MountProvider.php',
51
-    'OCA\\Files_Sharing\\Scanner' => $baseDir . '/../lib/Scanner.php',
52
-    'OCA\\Files_Sharing\\ShareBackend\\File' => $baseDir . '/../lib/ShareBackend/File.php',
53
-    'OCA\\Files_Sharing\\ShareBackend\\Folder' => $baseDir . '/../lib/ShareBackend/Folder.php',
54
-    'OCA\\Files_Sharing\\SharedMount' => $baseDir . '/../lib/SharedMount.php',
55
-    'OCA\\Files_Sharing\\SharedStorage' => $baseDir . '/../lib/SharedStorage.php',
56
-    'OCA\\Files_Sharing\\Updater' => $baseDir . '/../lib/Updater.php',
9
+    'OCA\\Files_Sharing\\Activity\\Filter' => $baseDir.'/../lib/Activity/Filter.php',
10
+    'OCA\\Files_Sharing\\Activity\\Providers\\Base' => $baseDir.'/../lib/Activity/Providers/Base.php',
11
+    'OCA\\Files_Sharing\\Activity\\Providers\\Downloads' => $baseDir.'/../lib/Activity/Providers/Downloads.php',
12
+    'OCA\\Files_Sharing\\Activity\\Providers\\Groups' => $baseDir.'/../lib/Activity/Providers/Groups.php',
13
+    'OCA\\Files_Sharing\\Activity\\Providers\\PublicLinks' => $baseDir.'/../lib/Activity/Providers/PublicLinks.php',
14
+    'OCA\\Files_Sharing\\Activity\\Providers\\RemoteShares' => $baseDir.'/../lib/Activity/Providers/RemoteShares.php',
15
+    'OCA\\Files_Sharing\\Activity\\Providers\\Users' => $baseDir.'/../lib/Activity/Providers/Users.php',
16
+    'OCA\\Files_Sharing\\Activity\\Settings\\PublicLinks' => $baseDir.'/../lib/Activity/Settings/PublicLinks.php',
17
+    'OCA\\Files_Sharing\\Activity\\Settings\\RemoteShare' => $baseDir.'/../lib/Activity/Settings/RemoteShare.php',
18
+    'OCA\\Files_Sharing\\Activity\\Settings\\Shared' => $baseDir.'/../lib/Activity/Settings/Shared.php',
19
+    'OCA\\Files_Sharing\\AppInfo\\Application' => $baseDir.'/../lib/AppInfo/Application.php',
20
+    'OCA\\Files_Sharing\\Cache' => $baseDir.'/../lib/Cache.php',
21
+    'OCA\\Files_Sharing\\Capabilities' => $baseDir.'/../lib/Capabilities.php',
22
+    'OCA\\Files_Sharing\\Collaboration\\ShareRecipientSorter' => $baseDir.'/../lib/Collaboration/ShareRecipientSorter.php',
23
+    'OCA\\Files_Sharing\\Command\\CleanupRemoteStorages' => $baseDir.'/../lib/Command/CleanupRemoteStorages.php',
24
+    'OCA\\Files_Sharing\\Controller\\ExternalSharesController' => $baseDir.'/../lib/Controller/ExternalSharesController.php',
25
+    'OCA\\Files_Sharing\\Controller\\PublicPreviewController' => $baseDir.'/../lib/Controller/PublicPreviewController.php',
26
+    'OCA\\Files_Sharing\\Controller\\RemoteController' => $baseDir.'/../lib/Controller/RemoteController.php',
27
+    'OCA\\Files_Sharing\\Controller\\ShareAPIController' => $baseDir.'/../lib/Controller/ShareAPIController.php',
28
+    'OCA\\Files_Sharing\\Controller\\ShareController' => $baseDir.'/../lib/Controller/ShareController.php',
29
+    'OCA\\Files_Sharing\\Controller\\ShareInfoController' => $baseDir.'/../lib/Controller/ShareInfoController.php',
30
+    'OCA\\Files_Sharing\\Controller\\ShareesAPIController' => $baseDir.'/../lib/Controller/ShareesAPIController.php',
31
+    'OCA\\Files_Sharing\\DeleteOrphanedSharesJob' => $baseDir.'/../lib/DeleteOrphanedSharesJob.php',
32
+    'OCA\\Files_Sharing\\Exceptions\\BrokenPath' => $baseDir.'/../lib/Exceptions/BrokenPath.php',
33
+    'OCA\\Files_Sharing\\Exceptions\\S2SException' => $baseDir.'/../lib/Exceptions/S2SException.php',
34
+    'OCA\\Files_Sharing\\ExpireSharesJob' => $baseDir.'/../lib/ExpireSharesJob.php',
35
+    'OCA\\Files_Sharing\\External\\Cache' => $baseDir.'/../lib/External/Cache.php',
36
+    'OCA\\Files_Sharing\\External\\Manager' => $baseDir.'/../lib/External/Manager.php',
37
+    'OCA\\Files_Sharing\\External\\Mount' => $baseDir.'/../lib/External/Mount.php',
38
+    'OCA\\Files_Sharing\\External\\MountProvider' => $baseDir.'/../lib/External/MountProvider.php',
39
+    'OCA\\Files_Sharing\\External\\Scanner' => $baseDir.'/../lib/External/Scanner.php',
40
+    'OCA\\Files_Sharing\\External\\Storage' => $baseDir.'/../lib/External/Storage.php',
41
+    'OCA\\Files_Sharing\\External\\Watcher' => $baseDir.'/../lib/External/Watcher.php',
42
+    'OCA\\Files_Sharing\\Helper' => $baseDir.'/../lib/Helper.php',
43
+    'OCA\\Files_Sharing\\Hooks' => $baseDir.'/../lib/Hooks.php',
44
+    'OCA\\Files_Sharing\\ISharedStorage' => $baseDir.'/../lib/ISharedStorage.php',
45
+    'OCA\\Files_Sharing\\Middleware\\OCSShareAPIMiddleware' => $baseDir.'/../lib/Middleware/OCSShareAPIMiddleware.php',
46
+    'OCA\\Files_Sharing\\Middleware\\ShareInfoMiddleware' => $baseDir.'/../lib/Middleware/ShareInfoMiddleware.php',
47
+    'OCA\\Files_Sharing\\Middleware\\SharingCheckMiddleware' => $baseDir.'/../lib/Middleware/SharingCheckMiddleware.php',
48
+    'OCA\\Files_Sharing\\Migration\\OwncloudGuestShareType' => $baseDir.'/../lib/Migration/OwncloudGuestShareType.php',
49
+    'OCA\\Files_Sharing\\Migration\\SetPasswordColumn' => $baseDir.'/../lib/Migration/SetPasswordColumn.php',
50
+    'OCA\\Files_Sharing\\MountProvider' => $baseDir.'/../lib/MountProvider.php',
51
+    'OCA\\Files_Sharing\\Scanner' => $baseDir.'/../lib/Scanner.php',
52
+    'OCA\\Files_Sharing\\ShareBackend\\File' => $baseDir.'/../lib/ShareBackend/File.php',
53
+    'OCA\\Files_Sharing\\ShareBackend\\Folder' => $baseDir.'/../lib/ShareBackend/Folder.php',
54
+    'OCA\\Files_Sharing\\SharedMount' => $baseDir.'/../lib/SharedMount.php',
55
+    'OCA\\Files_Sharing\\SharedStorage' => $baseDir.'/../lib/SharedStorage.php',
56
+    'OCA\\Files_Sharing\\Updater' => $baseDir.'/../lib/Updater.php',
57 57
 );
Please login to merge, or discard this patch.
apps/files_sharing/composer/composer/autoload_static.php 1 patch
Spacing   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -6,74 +6,74 @@
 block discarded – undo
6 6
 
7 7
 class ComposerStaticInitf32f03f7cd82bff20d6a51be16689441
8 8
 {
9
-    public static $prefixLengthsPsr4 = array (
9
+    public static $prefixLengthsPsr4 = array(
10 10
         'O' => 
11
-        array (
11
+        array(
12 12
             'OCA\\Files_Sharing\\' => 18,
13 13
         ),
14 14
     );
15 15
 
16
-    public static $prefixDirsPsr4 = array (
16
+    public static $prefixDirsPsr4 = array(
17 17
         'OCA\\Files_Sharing\\' => 
18
-        array (
19
-            0 => __DIR__ . '/..' . '/../lib',
18
+        array(
19
+            0 => __DIR__.'/..'.'/../lib',
20 20
         ),
21 21
     );
22 22
 
23
-    public static $classMap = array (
24
-        'OCA\\Files_Sharing\\Activity\\Filter' => __DIR__ . '/..' . '/../lib/Activity/Filter.php',
25
-        'OCA\\Files_Sharing\\Activity\\Providers\\Base' => __DIR__ . '/..' . '/../lib/Activity/Providers/Base.php',
26
-        'OCA\\Files_Sharing\\Activity\\Providers\\Downloads' => __DIR__ . '/..' . '/../lib/Activity/Providers/Downloads.php',
27
-        'OCA\\Files_Sharing\\Activity\\Providers\\Groups' => __DIR__ . '/..' . '/../lib/Activity/Providers/Groups.php',
28
-        'OCA\\Files_Sharing\\Activity\\Providers\\PublicLinks' => __DIR__ . '/..' . '/../lib/Activity/Providers/PublicLinks.php',
29
-        'OCA\\Files_Sharing\\Activity\\Providers\\RemoteShares' => __DIR__ . '/..' . '/../lib/Activity/Providers/RemoteShares.php',
30
-        'OCA\\Files_Sharing\\Activity\\Providers\\Users' => __DIR__ . '/..' . '/../lib/Activity/Providers/Users.php',
31
-        'OCA\\Files_Sharing\\Activity\\Settings\\PublicLinks' => __DIR__ . '/..' . '/../lib/Activity/Settings/PublicLinks.php',
32
-        'OCA\\Files_Sharing\\Activity\\Settings\\RemoteShare' => __DIR__ . '/..' . '/../lib/Activity/Settings/RemoteShare.php',
33
-        'OCA\\Files_Sharing\\Activity\\Settings\\Shared' => __DIR__ . '/..' . '/../lib/Activity/Settings/Shared.php',
34
-        'OCA\\Files_Sharing\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php',
35
-        'OCA\\Files_Sharing\\Cache' => __DIR__ . '/..' . '/../lib/Cache.php',
36
-        'OCA\\Files_Sharing\\Capabilities' => __DIR__ . '/..' . '/../lib/Capabilities.php',
37
-        'OCA\\Files_Sharing\\Collaboration\\ShareRecipientSorter' => __DIR__ . '/..' . '/../lib/Collaboration/ShareRecipientSorter.php',
38
-        'OCA\\Files_Sharing\\Command\\CleanupRemoteStorages' => __DIR__ . '/..' . '/../lib/Command/CleanupRemoteStorages.php',
39
-        'OCA\\Files_Sharing\\Controller\\ExternalSharesController' => __DIR__ . '/..' . '/../lib/Controller/ExternalSharesController.php',
40
-        'OCA\\Files_Sharing\\Controller\\PublicPreviewController' => __DIR__ . '/..' . '/../lib/Controller/PublicPreviewController.php',
41
-        'OCA\\Files_Sharing\\Controller\\RemoteController' => __DIR__ . '/..' . '/../lib/Controller/RemoteController.php',
42
-        'OCA\\Files_Sharing\\Controller\\ShareAPIController' => __DIR__ . '/..' . '/../lib/Controller/ShareAPIController.php',
43
-        'OCA\\Files_Sharing\\Controller\\ShareController' => __DIR__ . '/..' . '/../lib/Controller/ShareController.php',
44
-        'OCA\\Files_Sharing\\Controller\\ShareInfoController' => __DIR__ . '/..' . '/../lib/Controller/ShareInfoController.php',
45
-        'OCA\\Files_Sharing\\Controller\\ShareesAPIController' => __DIR__ . '/..' . '/../lib/Controller/ShareesAPIController.php',
46
-        'OCA\\Files_Sharing\\DeleteOrphanedSharesJob' => __DIR__ . '/..' . '/../lib/DeleteOrphanedSharesJob.php',
47
-        'OCA\\Files_Sharing\\Exceptions\\BrokenPath' => __DIR__ . '/..' . '/../lib/Exceptions/BrokenPath.php',
48
-        'OCA\\Files_Sharing\\Exceptions\\S2SException' => __DIR__ . '/..' . '/../lib/Exceptions/S2SException.php',
49
-        'OCA\\Files_Sharing\\ExpireSharesJob' => __DIR__ . '/..' . '/../lib/ExpireSharesJob.php',
50
-        'OCA\\Files_Sharing\\External\\Cache' => __DIR__ . '/..' . '/../lib/External/Cache.php',
51
-        'OCA\\Files_Sharing\\External\\Manager' => __DIR__ . '/..' . '/../lib/External/Manager.php',
52
-        'OCA\\Files_Sharing\\External\\Mount' => __DIR__ . '/..' . '/../lib/External/Mount.php',
53
-        'OCA\\Files_Sharing\\External\\MountProvider' => __DIR__ . '/..' . '/../lib/External/MountProvider.php',
54
-        'OCA\\Files_Sharing\\External\\Scanner' => __DIR__ . '/..' . '/../lib/External/Scanner.php',
55
-        'OCA\\Files_Sharing\\External\\Storage' => __DIR__ . '/..' . '/../lib/External/Storage.php',
56
-        'OCA\\Files_Sharing\\External\\Watcher' => __DIR__ . '/..' . '/../lib/External/Watcher.php',
57
-        'OCA\\Files_Sharing\\Helper' => __DIR__ . '/..' . '/../lib/Helper.php',
58
-        'OCA\\Files_Sharing\\Hooks' => __DIR__ . '/..' . '/../lib/Hooks.php',
59
-        'OCA\\Files_Sharing\\ISharedStorage' => __DIR__ . '/..' . '/../lib/ISharedStorage.php',
60
-        'OCA\\Files_Sharing\\Middleware\\OCSShareAPIMiddleware' => __DIR__ . '/..' . '/../lib/Middleware/OCSShareAPIMiddleware.php',
61
-        'OCA\\Files_Sharing\\Middleware\\ShareInfoMiddleware' => __DIR__ . '/..' . '/../lib/Middleware/ShareInfoMiddleware.php',
62
-        'OCA\\Files_Sharing\\Middleware\\SharingCheckMiddleware' => __DIR__ . '/..' . '/../lib/Middleware/SharingCheckMiddleware.php',
63
-        'OCA\\Files_Sharing\\Migration\\OwncloudGuestShareType' => __DIR__ . '/..' . '/../lib/Migration/OwncloudGuestShareType.php',
64
-        'OCA\\Files_Sharing\\Migration\\SetPasswordColumn' => __DIR__ . '/..' . '/../lib/Migration/SetPasswordColumn.php',
65
-        'OCA\\Files_Sharing\\MountProvider' => __DIR__ . '/..' . '/../lib/MountProvider.php',
66
-        'OCA\\Files_Sharing\\Scanner' => __DIR__ . '/..' . '/../lib/Scanner.php',
67
-        'OCA\\Files_Sharing\\ShareBackend\\File' => __DIR__ . '/..' . '/../lib/ShareBackend/File.php',
68
-        'OCA\\Files_Sharing\\ShareBackend\\Folder' => __DIR__ . '/..' . '/../lib/ShareBackend/Folder.php',
69
-        'OCA\\Files_Sharing\\SharedMount' => __DIR__ . '/..' . '/../lib/SharedMount.php',
70
-        'OCA\\Files_Sharing\\SharedStorage' => __DIR__ . '/..' . '/../lib/SharedStorage.php',
71
-        'OCA\\Files_Sharing\\Updater' => __DIR__ . '/..' . '/../lib/Updater.php',
23
+    public static $classMap = array(
24
+        'OCA\\Files_Sharing\\Activity\\Filter' => __DIR__.'/..'.'/../lib/Activity/Filter.php',
25
+        'OCA\\Files_Sharing\\Activity\\Providers\\Base' => __DIR__.'/..'.'/../lib/Activity/Providers/Base.php',
26
+        'OCA\\Files_Sharing\\Activity\\Providers\\Downloads' => __DIR__.'/..'.'/../lib/Activity/Providers/Downloads.php',
27
+        'OCA\\Files_Sharing\\Activity\\Providers\\Groups' => __DIR__.'/..'.'/../lib/Activity/Providers/Groups.php',
28
+        'OCA\\Files_Sharing\\Activity\\Providers\\PublicLinks' => __DIR__.'/..'.'/../lib/Activity/Providers/PublicLinks.php',
29
+        'OCA\\Files_Sharing\\Activity\\Providers\\RemoteShares' => __DIR__.'/..'.'/../lib/Activity/Providers/RemoteShares.php',
30
+        'OCA\\Files_Sharing\\Activity\\Providers\\Users' => __DIR__.'/..'.'/../lib/Activity/Providers/Users.php',
31
+        'OCA\\Files_Sharing\\Activity\\Settings\\PublicLinks' => __DIR__.'/..'.'/../lib/Activity/Settings/PublicLinks.php',
32
+        'OCA\\Files_Sharing\\Activity\\Settings\\RemoteShare' => __DIR__.'/..'.'/../lib/Activity/Settings/RemoteShare.php',
33
+        'OCA\\Files_Sharing\\Activity\\Settings\\Shared' => __DIR__.'/..'.'/../lib/Activity/Settings/Shared.php',
34
+        'OCA\\Files_Sharing\\AppInfo\\Application' => __DIR__.'/..'.'/../lib/AppInfo/Application.php',
35
+        'OCA\\Files_Sharing\\Cache' => __DIR__.'/..'.'/../lib/Cache.php',
36
+        'OCA\\Files_Sharing\\Capabilities' => __DIR__.'/..'.'/../lib/Capabilities.php',
37
+        'OCA\\Files_Sharing\\Collaboration\\ShareRecipientSorter' => __DIR__.'/..'.'/../lib/Collaboration/ShareRecipientSorter.php',
38
+        'OCA\\Files_Sharing\\Command\\CleanupRemoteStorages' => __DIR__.'/..'.'/../lib/Command/CleanupRemoteStorages.php',
39
+        'OCA\\Files_Sharing\\Controller\\ExternalSharesController' => __DIR__.'/..'.'/../lib/Controller/ExternalSharesController.php',
40
+        'OCA\\Files_Sharing\\Controller\\PublicPreviewController' => __DIR__.'/..'.'/../lib/Controller/PublicPreviewController.php',
41
+        'OCA\\Files_Sharing\\Controller\\RemoteController' => __DIR__.'/..'.'/../lib/Controller/RemoteController.php',
42
+        'OCA\\Files_Sharing\\Controller\\ShareAPIController' => __DIR__.'/..'.'/../lib/Controller/ShareAPIController.php',
43
+        'OCA\\Files_Sharing\\Controller\\ShareController' => __DIR__.'/..'.'/../lib/Controller/ShareController.php',
44
+        'OCA\\Files_Sharing\\Controller\\ShareInfoController' => __DIR__.'/..'.'/../lib/Controller/ShareInfoController.php',
45
+        'OCA\\Files_Sharing\\Controller\\ShareesAPIController' => __DIR__.'/..'.'/../lib/Controller/ShareesAPIController.php',
46
+        'OCA\\Files_Sharing\\DeleteOrphanedSharesJob' => __DIR__.'/..'.'/../lib/DeleteOrphanedSharesJob.php',
47
+        'OCA\\Files_Sharing\\Exceptions\\BrokenPath' => __DIR__.'/..'.'/../lib/Exceptions/BrokenPath.php',
48
+        'OCA\\Files_Sharing\\Exceptions\\S2SException' => __DIR__.'/..'.'/../lib/Exceptions/S2SException.php',
49
+        'OCA\\Files_Sharing\\ExpireSharesJob' => __DIR__.'/..'.'/../lib/ExpireSharesJob.php',
50
+        'OCA\\Files_Sharing\\External\\Cache' => __DIR__.'/..'.'/../lib/External/Cache.php',
51
+        'OCA\\Files_Sharing\\External\\Manager' => __DIR__.'/..'.'/../lib/External/Manager.php',
52
+        'OCA\\Files_Sharing\\External\\Mount' => __DIR__.'/..'.'/../lib/External/Mount.php',
53
+        'OCA\\Files_Sharing\\External\\MountProvider' => __DIR__.'/..'.'/../lib/External/MountProvider.php',
54
+        'OCA\\Files_Sharing\\External\\Scanner' => __DIR__.'/..'.'/../lib/External/Scanner.php',
55
+        'OCA\\Files_Sharing\\External\\Storage' => __DIR__.'/..'.'/../lib/External/Storage.php',
56
+        'OCA\\Files_Sharing\\External\\Watcher' => __DIR__.'/..'.'/../lib/External/Watcher.php',
57
+        'OCA\\Files_Sharing\\Helper' => __DIR__.'/..'.'/../lib/Helper.php',
58
+        'OCA\\Files_Sharing\\Hooks' => __DIR__.'/..'.'/../lib/Hooks.php',
59
+        'OCA\\Files_Sharing\\ISharedStorage' => __DIR__.'/..'.'/../lib/ISharedStorage.php',
60
+        'OCA\\Files_Sharing\\Middleware\\OCSShareAPIMiddleware' => __DIR__.'/..'.'/../lib/Middleware/OCSShareAPIMiddleware.php',
61
+        'OCA\\Files_Sharing\\Middleware\\ShareInfoMiddleware' => __DIR__.'/..'.'/../lib/Middleware/ShareInfoMiddleware.php',
62
+        'OCA\\Files_Sharing\\Middleware\\SharingCheckMiddleware' => __DIR__.'/..'.'/../lib/Middleware/SharingCheckMiddleware.php',
63
+        'OCA\\Files_Sharing\\Migration\\OwncloudGuestShareType' => __DIR__.'/..'.'/../lib/Migration/OwncloudGuestShareType.php',
64
+        'OCA\\Files_Sharing\\Migration\\SetPasswordColumn' => __DIR__.'/..'.'/../lib/Migration/SetPasswordColumn.php',
65
+        'OCA\\Files_Sharing\\MountProvider' => __DIR__.'/..'.'/../lib/MountProvider.php',
66
+        'OCA\\Files_Sharing\\Scanner' => __DIR__.'/..'.'/../lib/Scanner.php',
67
+        'OCA\\Files_Sharing\\ShareBackend\\File' => __DIR__.'/..'.'/../lib/ShareBackend/File.php',
68
+        'OCA\\Files_Sharing\\ShareBackend\\Folder' => __DIR__.'/..'.'/../lib/ShareBackend/Folder.php',
69
+        'OCA\\Files_Sharing\\SharedMount' => __DIR__.'/..'.'/../lib/SharedMount.php',
70
+        'OCA\\Files_Sharing\\SharedStorage' => __DIR__.'/..'.'/../lib/SharedStorage.php',
71
+        'OCA\\Files_Sharing\\Updater' => __DIR__.'/..'.'/../lib/Updater.php',
72 72
     );
73 73
 
74 74
     public static function getInitializer(ClassLoader $loader)
75 75
     {
76
-        return \Closure::bind(function () use ($loader) {
76
+        return \Closure::bind(function() use ($loader) {
77 77
             $loader->prefixLengthsPsr4 = ComposerStaticInitf32f03f7cd82bff20d6a51be16689441::$prefixLengthsPsr4;
78 78
             $loader->prefixDirsPsr4 = ComposerStaticInitf32f03f7cd82bff20d6a51be16689441::$prefixDirsPsr4;
79 79
             $loader->classMap = ComposerStaticInitf32f03f7cd82bff20d6a51be16689441::$classMap;
Please login to merge, or discard this patch.