Passed
Push — master ( 346770...2398d1 )
by Roeland
10:40 queued 35s
created
apps/files_sharing/appinfo/app.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -40,10 +40,10 @@  discard block
 block discarded – undo
40 40
 
41 41
 $eventDispatcher = \OC::$server->getEventDispatcher();
42 42
 $eventDispatcher->addListener(
43
-	'OCA\Files::loadAdditionalScripts',
44
-	function() {
45
-		\OCP\Util::addScript('files_sharing', 'dist/additionalScripts');
46
-	}
43
+    'OCA\Files::loadAdditionalScripts',
44
+    function() {
45
+        \OCP\Util::addScript('files_sharing', 'dist/additionalScripts');
46
+    }
47 47
 );
48 48
 
49 49
 $config = \OC::$server->getConfig();
@@ -53,62 +53,62 @@  discard block
 block discarded – undo
53 53
 
54 54
 if ($config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes') {
55 55
 
56
-	$sharingSublistArray = [];
56
+    $sharingSublistArray = [];
57 57
 
58
-	if (\OCP\Util::isSharingDisabledForUser() === false) {
59
-		array_push($sharingSublistArray, [
60
-			'id' => 'sharingout',
61
-			'appname' => 'files_sharing',
62
-			'script' => 'list.php',
63
-			'order' => 16,
64
-			'name' => $l->t('Shared with others'),
65
-		]);
66
-	}
58
+    if (\OCP\Util::isSharingDisabledForUser() === false) {
59
+        array_push($sharingSublistArray, [
60
+            'id' => 'sharingout',
61
+            'appname' => 'files_sharing',
62
+            'script' => 'list.php',
63
+            'order' => 16,
64
+            'name' => $l->t('Shared with others'),
65
+        ]);
66
+    }
67 67
 
68
-	array_push($sharingSublistArray, [
69
-		'id' => 'sharingin',
70
-		'appname' => 'files_sharing',
71
-		'script' => 'list.php',
72
-		'order' => 15,
73
-		'name' => $l->t('Shared with you'),
74
-	]);
68
+    array_push($sharingSublistArray, [
69
+        'id' => 'sharingin',
70
+        'appname' => 'files_sharing',
71
+        'script' => 'list.php',
72
+        'order' => 15,
73
+        'name' => $l->t('Shared with you'),
74
+    ]);
75 75
 
76
-	if (\OCP\Util::isSharingDisabledForUser() === false) {
77
-		// Check if sharing by link is enabled
78
-		if ($config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes') {
79
-			array_push($sharingSublistArray, [
80
-				'id' => 'sharinglinks',
81
-				'appname' => 'files_sharing',
82
-				'script' => 'list.php',
83
-				'order' => 17,
84
-				'name' => $l->t('Shared by link'),
85
-			]);
86
-		}
87
-	}
76
+    if (\OCP\Util::isSharingDisabledForUser() === false) {
77
+        // Check if sharing by link is enabled
78
+        if ($config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes') {
79
+            array_push($sharingSublistArray, [
80
+                'id' => 'sharinglinks',
81
+                'appname' => 'files_sharing',
82
+                'script' => 'list.php',
83
+                'order' => 17,
84
+                'name' => $l->t('Shared by link'),
85
+            ]);
86
+        }
87
+    }
88 88
 
89
-	array_push($sharingSublistArray, [
90
-		'id' => 'deletedshares',
91
-		'appname' => 'files_sharing',
92
-		'script' => 'list.php',
93
-		'order' => 19,
94
-		'name' => $l->t('Deleted shares'),
95
-	]);
89
+    array_push($sharingSublistArray, [
90
+        'id' => 'deletedshares',
91
+        'appname' => 'files_sharing',
92
+        'script' => 'list.php',
93
+        'order' => 19,
94
+        'name' => $l->t('Deleted shares'),
95
+    ]);
96 96
 
97
-	// show_Quick_Access stored as string
98
-	$user = $userSession->getUser();
99
-	$defaultExpandedState = true;
100
-	if ($user instanceof \OCP\IUser) {
101
-		$defaultExpandedState = $config->getUserValue($userSession->getUser()->getUID(), 'files', 'show_sharing_menu', '0') === '1';
102
-	}
97
+    // show_Quick_Access stored as string
98
+    $user = $userSession->getUser();
99
+    $defaultExpandedState = true;
100
+    if ($user instanceof \OCP\IUser) {
101
+        $defaultExpandedState = $config->getUserValue($userSession->getUser()->getUID(), 'files', 'show_sharing_menu', '0') === '1';
102
+    }
103 103
 
104
-	\OCA\Files\App::getNavigationManager()->add([
105
-		'id' => 'shareoverview',
106
-		'appname' => 'files_sharing',
107
-		'script' => 'list.php',
108
-		'order' => 18,
109
-		'name' => $l->t('Shares'),
110
-		'classes' => 'collapsible',
111
-		'sublist' => $sharingSublistArray,
112
-		'expandedState' => 'show_sharing_menu'
113
-	]);
104
+    \OCA\Files\App::getNavigationManager()->add([
105
+        'id' => 'shareoverview',
106
+        'appname' => 'files_sharing',
107
+        'script' => 'list.php',
108
+        'order' => 18,
109
+        'name' => $l->t('Shares'),
110
+        'classes' => 'collapsible',
111
+        'sublist' => $sharingSublistArray,
112
+        'expandedState' => 'show_sharing_menu'
113
+    ]);
114 114
 }
Please login to merge, or discard this patch.
apps/files/lib/Collaboration/Resources/ResourceProvider.php 1 patch
Indentation   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -32,109 +32,109 @@
 block discarded – undo
32 32
 
33 33
 class ResourceProvider implements IProvider {
34 34
 
35
-	const RESOURCE_TYPE = 'files';
36
-
37
-	/** @var IRootFolder */
38
-	protected $rootFolder;
39
-
40
-	/** @var IURLGenerator */
41
-	private $urlGenerator;
42
-
43
-	/** @var array */
44
-	protected $nodes = [];
45
-
46
-	public function __construct(IRootFolder $rootFolder, IURLGenerator $urlGenerator) {
47
-		$this->rootFolder = $rootFolder;
48
-		$this->urlGenerator = $urlGenerator;
49
-	}
50
-
51
-	private function getNode(IResource $resource): ?Node {
52
-		if (isset($this->nodes[(int) $resource->getId()])) {
53
-			return $this->nodes[(int) $resource->getId()];
54
-		}
55
-		$nodes = $this->rootFolder->getById((int) $resource->getId());
56
-		if (!empty($nodes)) {
57
-			$this->nodes[(int) $resource->getId()] = array_shift($nodes);
58
-			return $this->nodes[(int) $resource->getId()];
59
-		}
60
-		return null;
61
-	}
62
-
63
-	/**
64
-	 * Get the display name of a resource
65
-	 *
66
-	 * @param IResource $resource
67
-	 * @return string
68
-	 * @since 15.0.0
69
-	 */
70
-	public function getName(IResource $resource): string {
71
-		if (isset($this->nodes[(int) $resource->getId()])) {
72
-			return $this->nodes[(int) $resource->getId()]->getPath();
73
-		}
74
-		$node = $this->getNode($resource);
75
-		if ($node) {
76
-			return $node->getName();
77
-		}
78
-		return '';
79
-	}
80
-
81
-	/**
82
-	 * Can a user/guest access the collection
83
-	 *
84
-	 * @param IResource $resource
85
-	 * @param IUser $user
86
-	 * @return bool
87
-	 * @since 15.0.0
88
-	 */
89
-	public function canAccessResource(IResource $resource, IUser $user = null): bool {
90
-		if (!$user instanceof IUser) {
91
-			return false;
92
-		}
93
-
94
-		$userFolder = $this->rootFolder->getUserFolder($user->getUID());
95
-		$nodes = $userFolder->getById((int) $resource->getId());
96
-
97
-		if (!empty($nodes)) {
98
-			$this->nodes[(int) $resource->getId()] = array_shift($nodes);
99
-			return true;
100
-		}
101
-
102
-		return false;
103
-	}
104
-
105
-	/**
106
-	 * Get the icon class of a resource
107
-	 *
108
-	 * @param IResource $resource
109
-	 * @return string
110
-	 * @since 15.0.0
111
-	 */
112
-	public function getIconClass(IResource $resource): string {
113
-		$node = $this->getNode($resource);
114
-		if ($node && $node->getMimetype() === 'httpd/unix-directory') {
115
-			return 'icon-files-dark';
116
-		}
117
-		return 'icon-filetype-file';
118
-	}
119
-
120
-	/**
121
-	 * Get the resource type of the provider
122
-	 *
123
-	 * @return string
124
-	 * @since 15.0.0
125
-	 */
126
-	public function getType(): string {
127
-		return self::RESOURCE_TYPE;
128
-	}
129
-
130
-	/**
131
-	 * Get the link to a resource
132
-	 *
133
-	 * @param IResource $resource
134
-	 * @return string
135
-	 * @since 15.0.0
136
-	 */
137
-	public function getLink(IResource $resource): string {
138
-		return $this->urlGenerator->linkToRoute('files.viewcontroller.showFile', ['fileid' => $resource->getId()]);
139
-	}
35
+    const RESOURCE_TYPE = 'files';
36
+
37
+    /** @var IRootFolder */
38
+    protected $rootFolder;
39
+
40
+    /** @var IURLGenerator */
41
+    private $urlGenerator;
42
+
43
+    /** @var array */
44
+    protected $nodes = [];
45
+
46
+    public function __construct(IRootFolder $rootFolder, IURLGenerator $urlGenerator) {
47
+        $this->rootFolder = $rootFolder;
48
+        $this->urlGenerator = $urlGenerator;
49
+    }
50
+
51
+    private function getNode(IResource $resource): ?Node {
52
+        if (isset($this->nodes[(int) $resource->getId()])) {
53
+            return $this->nodes[(int) $resource->getId()];
54
+        }
55
+        $nodes = $this->rootFolder->getById((int) $resource->getId());
56
+        if (!empty($nodes)) {
57
+            $this->nodes[(int) $resource->getId()] = array_shift($nodes);
58
+            return $this->nodes[(int) $resource->getId()];
59
+        }
60
+        return null;
61
+    }
62
+
63
+    /**
64
+     * Get the display name of a resource
65
+     *
66
+     * @param IResource $resource
67
+     * @return string
68
+     * @since 15.0.0
69
+     */
70
+    public function getName(IResource $resource): string {
71
+        if (isset($this->nodes[(int) $resource->getId()])) {
72
+            return $this->nodes[(int) $resource->getId()]->getPath();
73
+        }
74
+        $node = $this->getNode($resource);
75
+        if ($node) {
76
+            return $node->getName();
77
+        }
78
+        return '';
79
+    }
80
+
81
+    /**
82
+     * Can a user/guest access the collection
83
+     *
84
+     * @param IResource $resource
85
+     * @param IUser $user
86
+     * @return bool
87
+     * @since 15.0.0
88
+     */
89
+    public function canAccessResource(IResource $resource, IUser $user = null): bool {
90
+        if (!$user instanceof IUser) {
91
+            return false;
92
+        }
93
+
94
+        $userFolder = $this->rootFolder->getUserFolder($user->getUID());
95
+        $nodes = $userFolder->getById((int) $resource->getId());
96
+
97
+        if (!empty($nodes)) {
98
+            $this->nodes[(int) $resource->getId()] = array_shift($nodes);
99
+            return true;
100
+        }
101
+
102
+        return false;
103
+    }
104
+
105
+    /**
106
+     * Get the icon class of a resource
107
+     *
108
+     * @param IResource $resource
109
+     * @return string
110
+     * @since 15.0.0
111
+     */
112
+    public function getIconClass(IResource $resource): string {
113
+        $node = $this->getNode($resource);
114
+        if ($node && $node->getMimetype() === 'httpd/unix-directory') {
115
+            return 'icon-files-dark';
116
+        }
117
+        return 'icon-filetype-file';
118
+    }
119
+
120
+    /**
121
+     * Get the resource type of the provider
122
+     *
123
+     * @return string
124
+     * @since 15.0.0
125
+     */
126
+    public function getType(): string {
127
+        return self::RESOURCE_TYPE;
128
+    }
129
+
130
+    /**
131
+     * Get the link to a resource
132
+     *
133
+     * @param IResource $resource
134
+     * @return string
135
+     * @since 15.0.0
136
+     */
137
+    public function getLink(IResource $resource): string {
138
+        return $this->urlGenerator->linkToRoute('files.viewcontroller.showFile', ['fileid' => $resource->getId()]);
139
+    }
140 140
 }
Please login to merge, or discard this patch.
apps/files/lib/Collaboration/Resources/Listener.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -27,18 +27,18 @@
 block discarded – undo
27 27
 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
28 28
 
29 29
 class Listener {
30
-	public static function register(EventDispatcherInterface $dispatcher): void {
31
-		$dispatcher->addListener('OCP\Share::postShare', [self::class, 'shareModification']);
32
-		$dispatcher->addListener('OCP\Share::postUnshare', [self::class, 'shareModification']);
33
-		$dispatcher->addListener('OCP\Share::postUnshareFromSelf', [self::class, 'shareModification']);
34
-	}
30
+    public static function register(EventDispatcherInterface $dispatcher): void {
31
+        $dispatcher->addListener('OCP\Share::postShare', [self::class, 'shareModification']);
32
+        $dispatcher->addListener('OCP\Share::postUnshare', [self::class, 'shareModification']);
33
+        $dispatcher->addListener('OCP\Share::postUnshareFromSelf', [self::class, 'shareModification']);
34
+    }
35 35
 
36
-	public static function shareModification(): void {
37
-		/** @var IManager $resourceManager */
38
-		$resourceManager = \OC::$server->query(IManager::class);
39
-		/** @var ResourceProvider $resourceProvider */
40
-		$resourceProvider = \OC::$server->query(ResourceProvider::class);
36
+    public static function shareModification(): void {
37
+        /** @var IManager $resourceManager */
38
+        $resourceManager = \OC::$server->query(IManager::class);
39
+        /** @var ResourceProvider $resourceProvider */
40
+        $resourceProvider = \OC::$server->query(ResourceProvider::class);
41 41
 
42
-		$resourceManager->invalidateAccessCacheForProvider($resourceProvider);
43
-	}
42
+        $resourceManager->invalidateAccessCacheForProvider($resourceProvider);
43
+    }
44 44
 }
Please login to merge, or discard this patch.
apps/files/lib/AppInfo/Application.php 1 patch
Indentation   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -38,77 +38,77 @@
 block discarded – undo
38 38
 use OCA\Files\Capabilities;
39 39
 
40 40
 class Application extends App {
41
-	public function __construct(array $urlParams=array()) {
42
-		parent::__construct('files', $urlParams);
43
-		$container = $this->getContainer();
44
-		$server = $container->getServer();
41
+    public function __construct(array $urlParams=array()) {
42
+        parent::__construct('files', $urlParams);
43
+        $container = $this->getContainer();
44
+        $server = $container->getServer();
45 45
 
46
-		/**
47
-		 * Controllers
48
-		 */
49
-		$container->registerService('APIController', function (IContainer $c) use ($server) {
50
-			return new ApiController(
51
-				$c->query('AppName'),
52
-				$c->query('Request'),
53
-				$server->getUserSession(),
54
-				$c->query('TagService'),
55
-				$server->getPreviewManager(),
56
-				$server->getShareManager(),
57
-				$server->getConfig(),
58
-				$server->getUserFolder()
59
-			);
60
-		});
46
+        /**
47
+         * Controllers
48
+         */
49
+        $container->registerService('APIController', function (IContainer $c) use ($server) {
50
+            return new ApiController(
51
+                $c->query('AppName'),
52
+                $c->query('Request'),
53
+                $server->getUserSession(),
54
+                $c->query('TagService'),
55
+                $server->getPreviewManager(),
56
+                $server->getShareManager(),
57
+                $server->getConfig(),
58
+                $server->getUserFolder()
59
+            );
60
+        });
61 61
 
62
-		$container->registerService('ViewController', function (IContainer $c) use ($server) {
63
-			return new ViewController(
64
-				$c->query('AppName'),
65
-				$c->query('Request'),
66
-				$server->getURLGenerator(),
67
-				$c->query('L10N'),
68
-				$server->getConfig(),
69
-				$server->getEventDispatcher(),
70
-				$server->getUserSession(),
71
-				$server->getAppManager(),
72
-				$server->getRootFolder(),
73
-				$c->query(Helper::class)
74
-			);
75
-		});
62
+        $container->registerService('ViewController', function (IContainer $c) use ($server) {
63
+            return new ViewController(
64
+                $c->query('AppName'),
65
+                $c->query('Request'),
66
+                $server->getURLGenerator(),
67
+                $c->query('L10N'),
68
+                $server->getConfig(),
69
+                $server->getEventDispatcher(),
70
+                $server->getUserSession(),
71
+                $server->getAppManager(),
72
+                $server->getRootFolder(),
73
+                $c->query(Helper::class)
74
+            );
75
+        });
76 76
 
77
-		/**
78
-		 * Core
79
-		 */
80
-		$container->registerService('L10N', function(IContainer $c) {
81
-			return $c->query('ServerContainer')->getL10N($c->query('AppName'));
82
-		});
77
+        /**
78
+         * Core
79
+         */
80
+        $container->registerService('L10N', function(IContainer $c) {
81
+            return $c->query('ServerContainer')->getL10N($c->query('AppName'));
82
+        });
83 83
 
84
-		/**
85
-		 * Services
86
-		 */
87
-		$container->registerService('Tagger', function(IContainer $c)  {
88
-			return $c->query('ServerContainer')->getTagManager()->load('files');
89
-		});
90
-		$container->registerService('TagService', function(IContainer $c) use ($server) {
91
-			$homeFolder = $c->query('ServerContainer')->getUserFolder();
92
-			return new TagService(
93
-				$c->query('ServerContainer')->getUserSession(),
94
-				$c->query('ServerContainer')->getActivityManager(),
95
-				$c->query('Tagger'),
96
-				$homeFolder,
97
-				$server->getEventDispatcher()
98
-			);
99
-		});
84
+        /**
85
+         * Services
86
+         */
87
+        $container->registerService('Tagger', function(IContainer $c)  {
88
+            return $c->query('ServerContainer')->getTagManager()->load('files');
89
+        });
90
+        $container->registerService('TagService', function(IContainer $c) use ($server) {
91
+            $homeFolder = $c->query('ServerContainer')->getUserFolder();
92
+            return new TagService(
93
+                $c->query('ServerContainer')->getUserSession(),
94
+                $c->query('ServerContainer')->getActivityManager(),
95
+                $c->query('Tagger'),
96
+                $homeFolder,
97
+                $server->getEventDispatcher()
98
+            );
99
+        });
100 100
 
101
-		/*
101
+        /*
102 102
 		 * Register capabilities
103 103
 		 */
104
-		$container->registerCapability(Capabilities::class);
104
+        $container->registerCapability(Capabilities::class);
105 105
 
106
-		/**
107
-		 * Register Collaboration ResourceProvider
108
-		 */
109
-		/** @var IManager $resourceManager */
110
-		$resourceManager = $container->query(IManager::class);
111
-		$resourceManager->registerResourceProvider(ResourceProvider::class);
112
-		Listener::register($server->getEventDispatcher());
113
-	}
106
+        /**
107
+         * Register Collaboration ResourceProvider
108
+         */
109
+        /** @var IManager $resourceManager */
110
+        $resourceManager = $container->query(IManager::class);
111
+        $resourceManager->registerResourceProvider(ResourceProvider::class);
112
+        Listener::register($server->getEventDispatcher());
113
+    }
114 114
 }
Please login to merge, or discard this patch.
core/routes.php 1 patch
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -36,70 +36,70 @@  discard block
 block discarded – undo
36 36
 
37 37
 $application = new Application();
38 38
 $application->registerRoutes($this, [
39
-	'routes' => [
40
-		['name' => 'lost#email', 'url' => '/lostpassword/email', 'verb' => 'POST'],
41
-		['name' => 'lost#resetform', 'url' => '/lostpassword/reset/form/{token}/{userId}', 'verb' => 'GET'],
42
-		['name' => 'lost#setPassword', 'url' => '/lostpassword/set/{token}/{userId}', 'verb' => 'POST'],
43
-		['name' => 'user#getDisplayNames', 'url' => '/displaynames', 'verb' => 'POST'],
44
-		['name' => 'avatar#getAvatar', 'url' => '/avatar/{userId}/{size}', 'verb' => 'GET'],
45
-		['name' => 'avatar#deleteAvatar', 'url' => '/avatar/', 'verb' => 'DELETE'],
46
-		['name' => 'avatar#postCroppedAvatar', 'url' => '/avatar/cropped', 'verb' => 'POST'],
47
-		['name' => 'avatar#getTmpAvatar', 'url' => '/avatar/tmp', 'verb' => 'GET'],
48
-		['name' => 'avatar#postAvatar', 'url' => '/avatar/', 'verb' => 'POST'],
49
-		['name' => 'GuestAvatar#getAvatar', 'url' => '/avatar/guest/{guestName}/{size}', 'verb' => 'GET'],
50
-		['name' => 'CSRFToken#index', 'url' => '/csrftoken', 'verb' => 'GET'],
51
-		['name' => 'login#tryLogin', 'url' => '/login', 'verb' => 'POST'],
52
-		['name' => 'login#confirmPassword', 'url' => '/login/confirm', 'verb' => 'POST'],
53
-		['name' => 'login#showLoginForm', 'url' => '/login', 'verb' => 'GET'],
54
-		['name' => 'login#logout', 'url' => '/logout', 'verb' => 'GET'],
55
-		// Original login flow used by all clients
56
-		['name' => 'ClientFlowLogin#showAuthPickerPage', 'url' => '/login/flow', 'verb' => 'GET'],
57
-		['name' => 'ClientFlowLogin#generateAppPassword', 'url' => '/login/flow', 'verb' => 'POST'],
58
-		['name' => 'ClientFlowLogin#grantPage', 'url' => '/login/flow/grant', 'verb' => 'GET'],
59
-		['name' => 'ClientFlowLogin#apptokenRedirect', 'url' => '/login/flow/apptoken', 'verb' => 'POST'],
60
-		// NG login flow used by desktop client in case of Kerberos/fancy 2fa (smart cards for example)
61
-		['name' => 'ClientFlowLoginV2#poll', 'url' => '/login/v2/poll', 'verb' => 'POST'],
62
-		['name' => 'ClientFlowLoginV2#showAuthPickerPage', 'url' => '/login/v2/flow', 'verb' => 'GET'],
63
-		['name' => 'ClientFlowLoginV2#landing', 'url' => '/login/v2/flow/{token}', 'verb' => 'GET'],
64
-		['name' => 'ClientFlowLoginV2#grantPage', 'url' => '/login/v2/grant', 'verb' => 'GET'],
65
-		['name' => 'ClientFlowLoginV2#generateAppPassword', 'url' => '/login/v2/grant', 'verb' => 'POST'],
66
-		['name' => 'ClientFlowLoginV2#init', 'url' => '/login/v2', 'verb' => 'POST'],
67
-		['name' => 'TwoFactorChallenge#selectChallenge', 'url' => '/login/selectchallenge', 'verb' => 'GET'],
68
-		['name' => 'TwoFactorChallenge#showChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'GET'],
69
-		['name' => 'TwoFactorChallenge#solveChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'POST'],
70
-		['name' => 'OCJS#getConfig', 'url' => '/core/js/oc.js', 'verb' => 'GET'],
71
-		['name' => 'Preview#getPreviewByFileId', 'url' => '/core/preview', 'verb' => 'GET'],
72
-		['name' => 'Preview#getPreview', 'url' => '/core/preview.png', 'verb' => 'GET'],
73
-		['name' => 'Svg#getSvgFromCore', 'url' => '/svg/core/{folder}/{fileName}', 'verb' => 'GET'],
74
-		['name' => 'Svg#getSvgFromApp', 'url' => '/svg/{app}/{fileName}', 'verb' => 'GET'],
75
-		['name' => 'Css#getCss', 'url' => '/css/{appName}/{fileName}', 'verb' => 'GET'],
76
-		['name' => 'Js#getJs', 'url' => '/js/{appName}/{fileName}', 'verb' => 'GET'],
77
-		['name' => 'contactsMenu#index', 'url' => '/contactsmenu/contacts', 'verb' => 'POST'],
78
-		['name' => 'contactsMenu#findOne', 'url' => '/contactsmenu/findOne', 'verb' => 'POST'],
79
-		['name' => 'WalledGarden#get', 'url' => '/204', 'verb' => 'GET'],
80
-		['name' => 'Search#search', 'url' => '/core/search', 'verb' => 'GET'],
81
-	],
82
-	'ocs' => [
83
-		['root' => '/cloud', 'name' => 'OCS#getCapabilities', 'url' => '/capabilities', 'verb' => 'GET'],
84
-		['root' => '', 'name' => 'OCS#getConfig', 'url' => '/config', 'verb' => 'GET'],
85
-		['root' => '/person', 'name' => 'OCS#personCheck', 'url' => '/check', 'verb' => 'POST'],
86
-		['root' => '/identityproof', 'name' => 'OCS#getIdentityProof', 'url' => '/key/{cloudId}', 'verb' => 'GET'],
87
-		['root' => '/core', 'name' => 'Navigation#getAppsNavigation', 'url' => '/navigation/apps', 'verb' => 'GET'],
88
-		['root' => '/core', 'name' => 'Navigation#getSettingsNavigation', 'url' => '/navigation/settings', 'verb' => 'GET'],
89
-		['root' => '/core', 'name' => 'AutoComplete#get', 'url' => '/autocomplete/get', 'verb' => 'GET'],
90
-		['root' => '/core', 'name' => 'WhatsNew#get', 'url' => '/whatsnew', 'verb' => 'GET'],
91
-		['root' => '/core', 'name' => 'WhatsNew#dismiss', 'url' => '/whatsnew', 'verb' => 'POST'],
92
-		['root' => '/core', 'name' => 'AppPassword#getAppPassword', 'url' => '/getapppassword', 'verb' => 'GET'],
39
+    'routes' => [
40
+        ['name' => 'lost#email', 'url' => '/lostpassword/email', 'verb' => 'POST'],
41
+        ['name' => 'lost#resetform', 'url' => '/lostpassword/reset/form/{token}/{userId}', 'verb' => 'GET'],
42
+        ['name' => 'lost#setPassword', 'url' => '/lostpassword/set/{token}/{userId}', 'verb' => 'POST'],
43
+        ['name' => 'user#getDisplayNames', 'url' => '/displaynames', 'verb' => 'POST'],
44
+        ['name' => 'avatar#getAvatar', 'url' => '/avatar/{userId}/{size}', 'verb' => 'GET'],
45
+        ['name' => 'avatar#deleteAvatar', 'url' => '/avatar/', 'verb' => 'DELETE'],
46
+        ['name' => 'avatar#postCroppedAvatar', 'url' => '/avatar/cropped', 'verb' => 'POST'],
47
+        ['name' => 'avatar#getTmpAvatar', 'url' => '/avatar/tmp', 'verb' => 'GET'],
48
+        ['name' => 'avatar#postAvatar', 'url' => '/avatar/', 'verb' => 'POST'],
49
+        ['name' => 'GuestAvatar#getAvatar', 'url' => '/avatar/guest/{guestName}/{size}', 'verb' => 'GET'],
50
+        ['name' => 'CSRFToken#index', 'url' => '/csrftoken', 'verb' => 'GET'],
51
+        ['name' => 'login#tryLogin', 'url' => '/login', 'verb' => 'POST'],
52
+        ['name' => 'login#confirmPassword', 'url' => '/login/confirm', 'verb' => 'POST'],
53
+        ['name' => 'login#showLoginForm', 'url' => '/login', 'verb' => 'GET'],
54
+        ['name' => 'login#logout', 'url' => '/logout', 'verb' => 'GET'],
55
+        // Original login flow used by all clients
56
+        ['name' => 'ClientFlowLogin#showAuthPickerPage', 'url' => '/login/flow', 'verb' => 'GET'],
57
+        ['name' => 'ClientFlowLogin#generateAppPassword', 'url' => '/login/flow', 'verb' => 'POST'],
58
+        ['name' => 'ClientFlowLogin#grantPage', 'url' => '/login/flow/grant', 'verb' => 'GET'],
59
+        ['name' => 'ClientFlowLogin#apptokenRedirect', 'url' => '/login/flow/apptoken', 'verb' => 'POST'],
60
+        // NG login flow used by desktop client in case of Kerberos/fancy 2fa (smart cards for example)
61
+        ['name' => 'ClientFlowLoginV2#poll', 'url' => '/login/v2/poll', 'verb' => 'POST'],
62
+        ['name' => 'ClientFlowLoginV2#showAuthPickerPage', 'url' => '/login/v2/flow', 'verb' => 'GET'],
63
+        ['name' => 'ClientFlowLoginV2#landing', 'url' => '/login/v2/flow/{token}', 'verb' => 'GET'],
64
+        ['name' => 'ClientFlowLoginV2#grantPage', 'url' => '/login/v2/grant', 'verb' => 'GET'],
65
+        ['name' => 'ClientFlowLoginV2#generateAppPassword', 'url' => '/login/v2/grant', 'verb' => 'POST'],
66
+        ['name' => 'ClientFlowLoginV2#init', 'url' => '/login/v2', 'verb' => 'POST'],
67
+        ['name' => 'TwoFactorChallenge#selectChallenge', 'url' => '/login/selectchallenge', 'verb' => 'GET'],
68
+        ['name' => 'TwoFactorChallenge#showChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'GET'],
69
+        ['name' => 'TwoFactorChallenge#solveChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'POST'],
70
+        ['name' => 'OCJS#getConfig', 'url' => '/core/js/oc.js', 'verb' => 'GET'],
71
+        ['name' => 'Preview#getPreviewByFileId', 'url' => '/core/preview', 'verb' => 'GET'],
72
+        ['name' => 'Preview#getPreview', 'url' => '/core/preview.png', 'verb' => 'GET'],
73
+        ['name' => 'Svg#getSvgFromCore', 'url' => '/svg/core/{folder}/{fileName}', 'verb' => 'GET'],
74
+        ['name' => 'Svg#getSvgFromApp', 'url' => '/svg/{app}/{fileName}', 'verb' => 'GET'],
75
+        ['name' => 'Css#getCss', 'url' => '/css/{appName}/{fileName}', 'verb' => 'GET'],
76
+        ['name' => 'Js#getJs', 'url' => '/js/{appName}/{fileName}', 'verb' => 'GET'],
77
+        ['name' => 'contactsMenu#index', 'url' => '/contactsmenu/contacts', 'verb' => 'POST'],
78
+        ['name' => 'contactsMenu#findOne', 'url' => '/contactsmenu/findOne', 'verb' => 'POST'],
79
+        ['name' => 'WalledGarden#get', 'url' => '/204', 'verb' => 'GET'],
80
+        ['name' => 'Search#search', 'url' => '/core/search', 'verb' => 'GET'],
81
+    ],
82
+    'ocs' => [
83
+        ['root' => '/cloud', 'name' => 'OCS#getCapabilities', 'url' => '/capabilities', 'verb' => 'GET'],
84
+        ['root' => '', 'name' => 'OCS#getConfig', 'url' => '/config', 'verb' => 'GET'],
85
+        ['root' => '/person', 'name' => 'OCS#personCheck', 'url' => '/check', 'verb' => 'POST'],
86
+        ['root' => '/identityproof', 'name' => 'OCS#getIdentityProof', 'url' => '/key/{cloudId}', 'verb' => 'GET'],
87
+        ['root' => '/core', 'name' => 'Navigation#getAppsNavigation', 'url' => '/navigation/apps', 'verb' => 'GET'],
88
+        ['root' => '/core', 'name' => 'Navigation#getSettingsNavigation', 'url' => '/navigation/settings', 'verb' => 'GET'],
89
+        ['root' => '/core', 'name' => 'AutoComplete#get', 'url' => '/autocomplete/get', 'verb' => 'GET'],
90
+        ['root' => '/core', 'name' => 'WhatsNew#get', 'url' => '/whatsnew', 'verb' => 'GET'],
91
+        ['root' => '/core', 'name' => 'WhatsNew#dismiss', 'url' => '/whatsnew', 'verb' => 'POST'],
92
+        ['root' => '/core', 'name' => 'AppPassword#getAppPassword', 'url' => '/getapppassword', 'verb' => 'GET'],
93 93
 
94
-		['root' => '/collaboration', 'name' => 'CollaborationResources#searchCollections', 'url' => '/resources/collections/search/{filter}', 'verb' => 'GET'],
95
-		['root' => '/collaboration', 'name' => 'CollaborationResources#listCollection', 'url' => '/resources/collections/{collectionId}', 'verb' => 'GET'],
96
-		['root' => '/collaboration', 'name' => 'CollaborationResources#renameCollection', 'url' => '/resources/collections/{collectionId}', 'verb' => 'PUT'],
97
-		['root' => '/collaboration', 'name' => 'CollaborationResources#addResource', 'url' => '/resources/collections/{collectionId}', 'verb' => 'POST'],
94
+        ['root' => '/collaboration', 'name' => 'CollaborationResources#searchCollections', 'url' => '/resources/collections/search/{filter}', 'verb' => 'GET'],
95
+        ['root' => '/collaboration', 'name' => 'CollaborationResources#listCollection', 'url' => '/resources/collections/{collectionId}', 'verb' => 'GET'],
96
+        ['root' => '/collaboration', 'name' => 'CollaborationResources#renameCollection', 'url' => '/resources/collections/{collectionId}', 'verb' => 'PUT'],
97
+        ['root' => '/collaboration', 'name' => 'CollaborationResources#addResource', 'url' => '/resources/collections/{collectionId}', 'verb' => 'POST'],
98 98
 
99
-		['root' => '/collaboration', 'name' => 'CollaborationResources#removeResource', 'url' => '/resources/collections/{collectionId}', 'verb' => 'DELETE'],
100
-		['root' => '/collaboration', 'name' => 'CollaborationResources#getCollectionsByResource', 'url' => '/resources/{resourceType}/{resourceId}', 'verb' => 'GET'],
101
-		['root' => '/collaboration', 'name' => 'CollaborationResources#createCollectionOnResource', 'url' => '/resources/{baseResourceType}/{baseResourceId}', 'verb' => 'POST'],
102
-	],
99
+        ['root' => '/collaboration', 'name' => 'CollaborationResources#removeResource', 'url' => '/resources/collections/{collectionId}', 'verb' => 'DELETE'],
100
+        ['root' => '/collaboration', 'name' => 'CollaborationResources#getCollectionsByResource', 'url' => '/resources/{resourceType}/{resourceId}', 'verb' => 'GET'],
101
+        ['root' => '/collaboration', 'name' => 'CollaborationResources#createCollectionOnResource', 'url' => '/resources/{baseResourceType}/{baseResourceId}', 'verb' => 'POST'],
102
+    ],
103 103
 ]);
104 104
 
105 105
 // Post installation check
@@ -108,12 +108,12 @@  discard block
 block discarded – undo
108 108
 // Core ajax actions
109 109
 // Routing
110 110
 $this->create('core_ajax_update', '/core/ajax/update.php')
111
-	->actionInclude('core/ajax/update.php');
111
+    ->actionInclude('core/ajax/update.php');
112 112
 
113 113
 // File routes
114 114
 $this->create('files.viewcontroller.showFile', '/f/{fileid}')->action(function($urlParams) {
115
-	$app = new \OCA\Files\AppInfo\Application($urlParams);
116
-	$app->dispatch('ViewController', 'index');
115
+    $app = new \OCA\Files\AppInfo\Application($urlParams);
116
+    $app->dispatch('ViewController', 'index');
117 117
 });
118 118
 
119 119
 // Call routes
@@ -122,12 +122,12 @@  discard block
 block discarded – undo
122 122
  * @suppress PhanUndeclaredClassMethod
123 123
  */
124 124
 $this->create('spreed.pagecontroller.showCall', '/call/{token}')->action(function($urlParams) {
125
-	if (class_exists(\OCA\Spreed\AppInfo\Application::class, false)) {
126
-		$app = new \OCA\Spreed\AppInfo\Application($urlParams);
127
-		$app->dispatch('PageController', 'index');
128
-	} else {
129
-		throw new \OC\HintException('App spreed is not enabled');
130
-	}
125
+    if (class_exists(\OCA\Spreed\AppInfo\Application::class, false)) {
126
+        $app = new \OCA\Spreed\AppInfo\Application($urlParams);
127
+        $app->dispatch('PageController', 'index');
128
+    } else {
129
+        throw new \OC\HintException('App spreed is not enabled');
130
+    }
131 131
 });
132 132
 
133 133
 // OCM routes
@@ -136,12 +136,12 @@  discard block
 block discarded – undo
136 136
  * @suppress PhanUndeclaredClassMethod
137 137
  */
138 138
 $this->create('cloud_federation_api.requesthandlercontroller.addShare', '/ocm/shares')->post()->action(function($urlParams) {
139
-	if (class_exists(\OCA\CloudFederationAPI\AppInfo\Application::class, false)) {
140
-		$app = new \OCA\CloudFederationAPI\AppInfo\Application($urlParams);
141
-		$app->dispatch('RequestHandlerController', 'addShare');
142
-	} else {
143
-		throw new \OC\HintException('Cloud Federation API not enabled');
144
-	}
139
+    if (class_exists(\OCA\CloudFederationAPI\AppInfo\Application::class, false)) {
140
+        $app = new \OCA\CloudFederationAPI\AppInfo\Application($urlParams);
141
+        $app->dispatch('RequestHandlerController', 'addShare');
142
+    } else {
143
+        throw new \OC\HintException('Cloud Federation API not enabled');
144
+    }
145 145
 });
146 146
 
147 147
 /**
@@ -149,53 +149,53 @@  discard block
 block discarded – undo
149 149
  * @suppress PhanUndeclaredClassMethod
150 150
  */
151 151
 $this->create('cloud_federation_api.requesthandlercontroller.receiveNotification', '/ocm/notifications')->post()->action(function($urlParams) {
152
-	if (class_exists(\OCA\CloudFederationAPI\AppInfo\Application::class, false)) {
153
-		$app = new \OCA\CloudFederationAPI\AppInfo\Application($urlParams);
154
-		$app->dispatch('RequestHandlerController', 'receiveNotification');
155
-	} else {
156
-		throw new \OC\HintException('Cloud Federation API not enabled');
157
-	}
152
+    if (class_exists(\OCA\CloudFederationAPI\AppInfo\Application::class, false)) {
153
+        $app = new \OCA\CloudFederationAPI\AppInfo\Application($urlParams);
154
+        $app->dispatch('RequestHandlerController', 'receiveNotification');
155
+    } else {
156
+        throw new \OC\HintException('Cloud Federation API not enabled');
157
+    }
158 158
 });
159 159
 
160 160
 
161 161
 // Sharing routes
162 162
 $this->create('files_sharing.sharecontroller.showShare', '/s/{token}')->action(function($urlParams) {
163
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
164
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
165
-		$app->dispatch('ShareController', 'showShare');
166
-	} else {
167
-		throw new \OC\HintException('App file sharing is not enabled');
168
-	}
163
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
164
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
165
+        $app->dispatch('ShareController', 'showShare');
166
+    } else {
167
+        throw new \OC\HintException('App file sharing is not enabled');
168
+    }
169 169
 });
170 170
 $this->create('files_sharing.sharecontroller.authenticate', '/s/{token}/authenticate/{redirect}')->post()->action(function($urlParams) {
171
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
172
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
173
-		$app->dispatch('ShareController', 'authenticate');
174
-	} else {
175
-		throw new \OC\HintException('App file sharing is not enabled');
176
-	}
171
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
172
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
173
+        $app->dispatch('ShareController', 'authenticate');
174
+    } else {
175
+        throw new \OC\HintException('App file sharing is not enabled');
176
+    }
177 177
 });
178 178
 $this->create('files_sharing.sharecontroller.showAuthenticate', '/s/{token}/authenticate/{redirect}')->get()->action(function($urlParams) {
179
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
180
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
181
-		$app->dispatch('ShareController', 'showAuthenticate');
182
-	} else {
183
-		throw new \OC\HintException('App file sharing is not enabled');
184
-	}
179
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
180
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
181
+        $app->dispatch('ShareController', 'showAuthenticate');
182
+    } else {
183
+        throw new \OC\HintException('App file sharing is not enabled');
184
+    }
185 185
 });
186 186
 $this->create('files_sharing.sharecontroller.downloadShare', '/s/{token}/download')->get()->action(function($urlParams) {
187
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
188
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
189
-		$app->dispatch('ShareController', 'downloadShare');
190
-	} else {
191
-		throw new \OC\HintException('App file sharing is not enabled');
192
-	}
187
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
188
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
189
+        $app->dispatch('ShareController', 'downloadShare');
190
+    } else {
191
+        throw new \OC\HintException('App file sharing is not enabled');
192
+    }
193 193
 });
194 194
 $this->create('files_sharing.publicpreview.directLink', '/s/{token}/preview')->get()->action(function($urlParams) {
195
-	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
196
-		$app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
197
-		$app->dispatch('PublicPreviewController', 'directLink');
198
-	} else {
199
-		throw new \OC\HintException('App file sharing is not enabled');
200
-	}
195
+    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) {
196
+        $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams);
197
+        $app->dispatch('PublicPreviewController', 'directLink');
198
+    } else {
199
+        throw new \OC\HintException('App file sharing is not enabled');
200
+    }
201 201
 });
Please login to merge, or discard this patch.
core/Migrations/Version16000Date20190207141427.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -31,81 +31,81 @@
 block discarded – undo
31 31
 class Version16000Date20190207141427 extends SimpleMigrationStep {
32 32
 
33 33
 
34
-	/**
35
-	 * @param IOutput $output
36
-	 * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
37
-	 * @param array $options
38
-	 * @return null|ISchemaWrapper
39
-	 */
40
-	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options) {
41
-		/** @var ISchemaWrapper $schema */
42
-		$schema = $schemaClosure();
43
-
44
-		if (!$schema->hasTable('collres_collections')) {
45
-			$table = $schema->createTable('collres_collections');
46
-
47
-			$table->addColumn('id', Type::BIGINT, [
48
-				'autoincrement' => true,
49
-				'notnull' => true,
50
-			]);
51
-			$table->addColumn('name', Type::STRING, [
52
-				'notnull' => true,
53
-				'length' => 64,
54
-			]);
55
-
56
-			$table->setPrimaryKey(['id']);
57
-		}
58
-
59
-		if (!$schema->hasTable('collres_resources')) {
60
-			$table = $schema->createTable('collres_resources');
61
-
62
-			$table->addColumn('collection_id', Type::BIGINT, [
63
-				'notnull' => true,
64
-			]);
65
-			$table->addColumn('resource_type', Type::STRING, [
66
-				'notnull' => true,
67
-				'length' => 64,
68
-			]);
69
-			$table->addColumn('resource_id', Type::STRING, [
70
-				'notnull' => true,
71
-				'length' => 64,
72
-			]);
73
-
74
-			$table->addUniqueIndex(['collection_id', 'resource_type', 'resource_id'], 'collres_unique_res');
75
-		}
76
-
77
-		if (!$schema->hasTable('collres_accesscache')) {
78
-			$table = $schema->createTable('collres_accesscache');
79
-
80
-			$table->addColumn('user_id', Type::STRING, [
81
-				'notnull' => true,
82
-				'length' => 64,
83
-			]);
84
-			$table->addColumn('collection_id', Type::BIGINT, [
85
-				'notnull' => false,
86
-				'default' => 0,
87
-			]);
88
-			$table->addColumn('resource_type', Type::STRING, [
89
-				'notnull' => false,
90
-				'length' => 64,
91
-				'default' => '',
92
-			]);
93
-			$table->addColumn('resource_id', Type::STRING, [
94
-				'notnull' => false,
95
-				'length' => 64,
96
-				'default' => '',
97
-			]);
98
-			$table->addColumn('access', Type::SMALLINT, [
99
-				'notnull' => true,
100
-				'default' => 0,
101
-			]);
102
-
103
-			$table->addUniqueIndex(['user_id', 'collection_id', 'resource_type', 'resource_id'], 'collres_unique_user');
104
-			$table->addIndex(['user_id', 'resource_type', 'resource_id'], 'collres_user_res');
105
-			$table->addIndex(['user_id', 'collection_id'], 'collres_user_coll');
106
-		}
107
-
108
-		return $schema;
109
-	}
34
+    /**
35
+     * @param IOutput $output
36
+     * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
37
+     * @param array $options
38
+     * @return null|ISchemaWrapper
39
+     */
40
+    public function changeSchema(IOutput $output, Closure $schemaClosure, array $options) {
41
+        /** @var ISchemaWrapper $schema */
42
+        $schema = $schemaClosure();
43
+
44
+        if (!$schema->hasTable('collres_collections')) {
45
+            $table = $schema->createTable('collres_collections');
46
+
47
+            $table->addColumn('id', Type::BIGINT, [
48
+                'autoincrement' => true,
49
+                'notnull' => true,
50
+            ]);
51
+            $table->addColumn('name', Type::STRING, [
52
+                'notnull' => true,
53
+                'length' => 64,
54
+            ]);
55
+
56
+            $table->setPrimaryKey(['id']);
57
+        }
58
+
59
+        if (!$schema->hasTable('collres_resources')) {
60
+            $table = $schema->createTable('collres_resources');
61
+
62
+            $table->addColumn('collection_id', Type::BIGINT, [
63
+                'notnull' => true,
64
+            ]);
65
+            $table->addColumn('resource_type', Type::STRING, [
66
+                'notnull' => true,
67
+                'length' => 64,
68
+            ]);
69
+            $table->addColumn('resource_id', Type::STRING, [
70
+                'notnull' => true,
71
+                'length' => 64,
72
+            ]);
73
+
74
+            $table->addUniqueIndex(['collection_id', 'resource_type', 'resource_id'], 'collres_unique_res');
75
+        }
76
+
77
+        if (!$schema->hasTable('collres_accesscache')) {
78
+            $table = $schema->createTable('collres_accesscache');
79
+
80
+            $table->addColumn('user_id', Type::STRING, [
81
+                'notnull' => true,
82
+                'length' => 64,
83
+            ]);
84
+            $table->addColumn('collection_id', Type::BIGINT, [
85
+                'notnull' => false,
86
+                'default' => 0,
87
+            ]);
88
+            $table->addColumn('resource_type', Type::STRING, [
89
+                'notnull' => false,
90
+                'length' => 64,
91
+                'default' => '',
92
+            ]);
93
+            $table->addColumn('resource_id', Type::STRING, [
94
+                'notnull' => false,
95
+                'length' => 64,
96
+                'default' => '',
97
+            ]);
98
+            $table->addColumn('access', Type::SMALLINT, [
99
+                'notnull' => true,
100
+                'default' => 0,
101
+            ]);
102
+
103
+            $table->addUniqueIndex(['user_id', 'collection_id', 'resource_type', 'resource_id'], 'collres_unique_user');
104
+            $table->addIndex(['user_id', 'resource_type', 'resource_id'], 'collres_user_res');
105
+            $table->addIndex(['user_id', 'collection_id'], 'collres_user_coll');
106
+        }
107
+
108
+        return $schema;
109
+    }
110 110
 
111 111
 }
Please login to merge, or discard this patch.
core/Controller/CollaborationResourcesController.php 1 patch
Indentation   +214 added lines, -214 removed lines patch added patch discarded remove patch
@@ -35,218 +35,218 @@
 block discarded – undo
35 35
 
36 36
 class CollaborationResourcesController extends OCSController {
37 37
 
38
-	/** @var IManager */
39
-	private $manager;
40
-
41
-	/** @var IUserSession */
42
-	private $userSession;
43
-
44
-	public function __construct(
45
-		string $appName,
46
-		IRequest $request,
47
-		IManager $manager,
48
-		IUserSession $userSession
49
-	) {
50
-		parent::__construct($appName, $request);
51
-
52
-		$this->manager = $manager;
53
-		$this->userSession = $userSession;
54
-	}
55
-
56
-	/**
57
-	 * @param int $collectionId
58
-	 * @return ICollection
59
-	 * @throws CollectionException when the collection was not found for the user
60
-	 */
61
-	protected function getCollection(int $collectionId): ICollection {
62
-		$collection = $this->manager->getCollectionForUser($collectionId, $this->userSession->getUser());
63
-
64
-		if (!$collection->canAccess($this->userSession->getUser())) {
65
-			throw new CollectionException('Not found');
66
-		}
67
-
68
-		return $collection;
69
-	}
70
-
71
-	/**
72
-	 * @NoAdminRequired
73
-	 *
74
-	 * @param int $collectionId
75
-	 * @return DataResponse
76
-	 */
77
-	public function listCollection(int $collectionId): DataResponse {
78
-		try {
79
-			$collection = $this->getCollection($collectionId);
80
-		} catch (CollectionException $e) {
81
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
82
-		}
83
-
84
-		return new DataResponse($this->prepareCollection($collection));
85
-	}
86
-
87
-	/**
88
-	 * @NoAdminRequired
89
-	 *
90
-	 * @param string $filter
91
-	 * @return DataResponse
92
-	 */
93
-	public function searchCollections(string $filter): DataResponse {
94
-		try {
95
-			$collections = $this->manager->searchCollections($this->userSession->getUser(), $filter);
96
-		} catch (CollectionException $e) {
97
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
98
-		}
99
-
100
-		return new DataResponse(array_map([$this, 'prepareCollection'], $collections));
101
-	}
102
-
103
-	/**
104
-	 * @NoAdminRequired
105
-	 *
106
-	 * @param int $collectionId
107
-	 * @param string $resourceType
108
-	 * @param string $resourceId
109
-	 * @return DataResponse
110
-	 */
111
-	public function addResource(int $collectionId, string $resourceType, string $resourceId): DataResponse {
112
-		try {
113
-			$collection = $this->getCollection($collectionId);
114
-		} catch (CollectionException $e) {
115
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
116
-		}
117
-
118
-		$resource = $this->manager->createResource($resourceType, $resourceId);
119
-
120
-		if (!$resource->canAccess($this->userSession->getUser())) {
121
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
122
-		}
123
-
124
-		try {
125
-			$collection->addResource($resource);
126
-		} catch (ResourceException $e) {
127
-		}
128
-
129
-		return new DataResponse($this->prepareCollection($collection));
130
-	}
131
-
132
-	/**
133
-	 * @NoAdminRequired
134
-	 *
135
-	 * @param int $collectionId
136
-	 * @param string $resourceType
137
-	 * @param string $resourceId
138
-	 * @return DataResponse
139
-	 */
140
-	public function removeResource(int $collectionId, string $resourceType, string $resourceId): DataResponse {
141
-		try {
142
-			$collection = $this->getCollection($collectionId);
143
-		} catch (CollectionException $e) {
144
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
145
-		}
146
-
147
-		try {
148
-			$resource = $this->manager->getResourceForUser($resourceType, $resourceId, $this->userSession->getUser());
149
-		} catch (CollectionException $e) {
150
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
151
-		}
152
-
153
-		$collection->removeResource($resource);
154
-
155
-		return new DataResponse($this->prepareCollection($collection));
156
-	}
157
-
158
-	/**
159
-	 * @NoAdminRequired
160
-	 *
161
-	 * @param string $resourceType
162
-	 * @param string $resourceId
163
-	 * @return DataResponse
164
-	 */
165
-	public function getCollectionsByResource(string $resourceType, string $resourceId): DataResponse {
166
-		try {
167
-			$resource = $this->manager->getResourceForUser($resourceType, $resourceId, $this->userSession->getUser());
168
-		} catch (ResourceException $e) {
169
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
170
-		}
171
-
172
-		if (!$resource->canAccess($this->userSession->getUser())) {
173
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
174
-		}
175
-
176
-		return new DataResponse(array_map([$this, 'prepareCollection'], $resource->getCollections()));
177
-	}
178
-
179
-	/**
180
-	 * @NoAdminRequired
181
-	 *
182
-	 * @param string $baseResourceType
183
-	 * @param string $baseResourceId
184
-	 * @param string $name
185
-	 * @return DataResponse
186
-	 */
187
-	public function createCollectionOnResource(string $baseResourceType, string $baseResourceId, string $name): DataResponse {
188
-		if (!isset($name[0]) || isset($name[64])) {
189
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
190
-		}
191
-
192
-		try {
193
-			$resource = $this->manager->createResource($baseResourceType, $baseResourceId);
194
-		} catch (CollectionException $e) {
195
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
196
-		}
197
-
198
-		if (!$resource->canAccess($this->userSession->getUser())) {
199
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
200
-		}
201
-
202
-		$collection = $this->manager->newCollection($name);
203
-		$collection->addResource($resource);
204
-
205
-		return new DataResponse($this->prepareCollection($collection));
206
-	}
207
-
208
-	/**
209
-	 * @NoAdminRequired
210
-	 *
211
-	 * @param int $collectionId
212
-	 * @param string $collectionName
213
-	 * @return DataResponse
214
-	 */
215
-	public function renameCollection(int $collectionId, string $collectionName): DataResponse {
216
-		try {
217
-			$collection = $this->getCollection($collectionId);
218
-		} catch (CollectionException $exception) {
219
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
220
-		}
221
-
222
-		$collection->setName($collectionName);
223
-
224
-		return new DataResponse($this->prepareCollection($collection));
225
-	}
226
-
227
-	protected function prepareCollection(ICollection $collection): array {
228
-		if (!$collection->canAccess($this->userSession->getUser())) {
229
-			return null;
230
-		}
231
-
232
-		return [
233
-			'id' => $collection->getId(),
234
-			'name' => $collection->getName(),
235
-			'resources' => array_values(array_filter(array_map([$this, 'prepareResources'], $collection->getResources()))),
236
-		];
237
-	}
238
-
239
-	protected function prepareResources(IResource $resource): ?array {
240
-		if (!$resource->canAccess($this->userSession->getUser())) {
241
-			return null;
242
-		}
243
-
244
-		return [
245
-			'type' => $resource->getType(),
246
-			'id' => $resource->getId(),
247
-			'name' => $resource->getName(),
248
-			'iconClass' => $resource->getIconClass(),
249
-			'link' => $resource->getLink(),
250
-		];
251
-	}
38
+    /** @var IManager */
39
+    private $manager;
40
+
41
+    /** @var IUserSession */
42
+    private $userSession;
43
+
44
+    public function __construct(
45
+        string $appName,
46
+        IRequest $request,
47
+        IManager $manager,
48
+        IUserSession $userSession
49
+    ) {
50
+        parent::__construct($appName, $request);
51
+
52
+        $this->manager = $manager;
53
+        $this->userSession = $userSession;
54
+    }
55
+
56
+    /**
57
+     * @param int $collectionId
58
+     * @return ICollection
59
+     * @throws CollectionException when the collection was not found for the user
60
+     */
61
+    protected function getCollection(int $collectionId): ICollection {
62
+        $collection = $this->manager->getCollectionForUser($collectionId, $this->userSession->getUser());
63
+
64
+        if (!$collection->canAccess($this->userSession->getUser())) {
65
+            throw new CollectionException('Not found');
66
+        }
67
+
68
+        return $collection;
69
+    }
70
+
71
+    /**
72
+     * @NoAdminRequired
73
+     *
74
+     * @param int $collectionId
75
+     * @return DataResponse
76
+     */
77
+    public function listCollection(int $collectionId): DataResponse {
78
+        try {
79
+            $collection = $this->getCollection($collectionId);
80
+        } catch (CollectionException $e) {
81
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
82
+        }
83
+
84
+        return new DataResponse($this->prepareCollection($collection));
85
+    }
86
+
87
+    /**
88
+     * @NoAdminRequired
89
+     *
90
+     * @param string $filter
91
+     * @return DataResponse
92
+     */
93
+    public function searchCollections(string $filter): DataResponse {
94
+        try {
95
+            $collections = $this->manager->searchCollections($this->userSession->getUser(), $filter);
96
+        } catch (CollectionException $e) {
97
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
98
+        }
99
+
100
+        return new DataResponse(array_map([$this, 'prepareCollection'], $collections));
101
+    }
102
+
103
+    /**
104
+     * @NoAdminRequired
105
+     *
106
+     * @param int $collectionId
107
+     * @param string $resourceType
108
+     * @param string $resourceId
109
+     * @return DataResponse
110
+     */
111
+    public function addResource(int $collectionId, string $resourceType, string $resourceId): DataResponse {
112
+        try {
113
+            $collection = $this->getCollection($collectionId);
114
+        } catch (CollectionException $e) {
115
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
116
+        }
117
+
118
+        $resource = $this->manager->createResource($resourceType, $resourceId);
119
+
120
+        if (!$resource->canAccess($this->userSession->getUser())) {
121
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
122
+        }
123
+
124
+        try {
125
+            $collection->addResource($resource);
126
+        } catch (ResourceException $e) {
127
+        }
128
+
129
+        return new DataResponse($this->prepareCollection($collection));
130
+    }
131
+
132
+    /**
133
+     * @NoAdminRequired
134
+     *
135
+     * @param int $collectionId
136
+     * @param string $resourceType
137
+     * @param string $resourceId
138
+     * @return DataResponse
139
+     */
140
+    public function removeResource(int $collectionId, string $resourceType, string $resourceId): DataResponse {
141
+        try {
142
+            $collection = $this->getCollection($collectionId);
143
+        } catch (CollectionException $e) {
144
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
145
+        }
146
+
147
+        try {
148
+            $resource = $this->manager->getResourceForUser($resourceType, $resourceId, $this->userSession->getUser());
149
+        } catch (CollectionException $e) {
150
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
151
+        }
152
+
153
+        $collection->removeResource($resource);
154
+
155
+        return new DataResponse($this->prepareCollection($collection));
156
+    }
157
+
158
+    /**
159
+     * @NoAdminRequired
160
+     *
161
+     * @param string $resourceType
162
+     * @param string $resourceId
163
+     * @return DataResponse
164
+     */
165
+    public function getCollectionsByResource(string $resourceType, string $resourceId): DataResponse {
166
+        try {
167
+            $resource = $this->manager->getResourceForUser($resourceType, $resourceId, $this->userSession->getUser());
168
+        } catch (ResourceException $e) {
169
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
170
+        }
171
+
172
+        if (!$resource->canAccess($this->userSession->getUser())) {
173
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
174
+        }
175
+
176
+        return new DataResponse(array_map([$this, 'prepareCollection'], $resource->getCollections()));
177
+    }
178
+
179
+    /**
180
+     * @NoAdminRequired
181
+     *
182
+     * @param string $baseResourceType
183
+     * @param string $baseResourceId
184
+     * @param string $name
185
+     * @return DataResponse
186
+     */
187
+    public function createCollectionOnResource(string $baseResourceType, string $baseResourceId, string $name): DataResponse {
188
+        if (!isset($name[0]) || isset($name[64])) {
189
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
190
+        }
191
+
192
+        try {
193
+            $resource = $this->manager->createResource($baseResourceType, $baseResourceId);
194
+        } catch (CollectionException $e) {
195
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
196
+        }
197
+
198
+        if (!$resource->canAccess($this->userSession->getUser())) {
199
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
200
+        }
201
+
202
+        $collection = $this->manager->newCollection($name);
203
+        $collection->addResource($resource);
204
+
205
+        return new DataResponse($this->prepareCollection($collection));
206
+    }
207
+
208
+    /**
209
+     * @NoAdminRequired
210
+     *
211
+     * @param int $collectionId
212
+     * @param string $collectionName
213
+     * @return DataResponse
214
+     */
215
+    public function renameCollection(int $collectionId, string $collectionName): DataResponse {
216
+        try {
217
+            $collection = $this->getCollection($collectionId);
218
+        } catch (CollectionException $exception) {
219
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
220
+        }
221
+
222
+        $collection->setName($collectionName);
223
+
224
+        return new DataResponse($this->prepareCollection($collection));
225
+    }
226
+
227
+    protected function prepareCollection(ICollection $collection): array {
228
+        if (!$collection->canAccess($this->userSession->getUser())) {
229
+            return null;
230
+        }
231
+
232
+        return [
233
+            'id' => $collection->getId(),
234
+            'name' => $collection->getName(),
235
+            'resources' => array_values(array_filter(array_map([$this, 'prepareResources'], $collection->getResources()))),
236
+        ];
237
+    }
238
+
239
+    protected function prepareResources(IResource $resource): ?array {
240
+        if (!$resource->canAccess($this->userSession->getUser())) {
241
+            return null;
242
+        }
243
+
244
+        return [
245
+            'type' => $resource->getType(),
246
+            'id' => $resource->getId(),
247
+            'name' => $resource->getName(),
248
+            'iconClass' => $resource->getIconClass(),
249
+            'link' => $resource->getLink(),
250
+        ];
251
+    }
252 252
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +983 added lines, -983 removed lines patch added patch discarded remove patch
@@ -68,989 +68,989 @@
 block discarded – undo
68 68
  * OC_autoload!
69 69
  */
70 70
 class OC {
71
-	/**
72
-	 * Associative array for autoloading. classname => filename
73
-	 */
74
-	public static $CLASSPATH = array();
75
-	/**
76
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
77
-	 */
78
-	public static $SERVERROOT = '';
79
-	/**
80
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
81
-	 */
82
-	private static $SUBURI = '';
83
-	/**
84
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
85
-	 */
86
-	public static $WEBROOT = '';
87
-	/**
88
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
89
-	 * web path in 'url'
90
-	 */
91
-	public static $APPSROOTS = array();
92
-
93
-	/**
94
-	 * @var string
95
-	 */
96
-	public static $configDir;
97
-
98
-	/**
99
-	 * requested app
100
-	 */
101
-	public static $REQUESTEDAPP = '';
102
-
103
-	/**
104
-	 * check if Nextcloud runs in cli mode
105
-	 */
106
-	public static $CLI = false;
107
-
108
-	/**
109
-	 * @var \OC\Autoloader $loader
110
-	 */
111
-	public static $loader = null;
112
-
113
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
114
-	public static $composerAutoloader = null;
115
-
116
-	/**
117
-	 * @var \OC\Server
118
-	 */
119
-	public static $server = null;
120
-
121
-	/**
122
-	 * @var \OC\Config
123
-	 */
124
-	private static $config = null;
125
-
126
-	/**
127
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
128
-	 * the app path list is empty or contains an invalid path
129
-	 */
130
-	public static function initPaths() {
131
-		if(defined('PHPUNIT_CONFIG_DIR')) {
132
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
-			self::$configDir = rtrim($dir, '/') . '/';
137
-		} else {
138
-			self::$configDir = OC::$SERVERROOT . '/config/';
139
-		}
140
-		self::$config = new \OC\Config(self::$configDir);
141
-
142
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
143
-		/**
144
-		 * FIXME: The following lines are required because we can't yet instantiate
145
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
146
-		 */
147
-		$params = [
148
-			'server' => [
149
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
150
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
151
-			],
152
-		];
153
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
154
-		$scriptName = $fakeRequest->getScriptName();
155
-		if (substr($scriptName, -1) == '/') {
156
-			$scriptName .= 'index.php';
157
-			//make sure suburi follows the same rules as scriptName
158
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
159
-				if (substr(OC::$SUBURI, -1) != '/') {
160
-					OC::$SUBURI = OC::$SUBURI . '/';
161
-				}
162
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
163
-			}
164
-		}
165
-
166
-
167
-		if (OC::$CLI) {
168
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
169
-		} else {
170
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
171
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172
-
173
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
175
-				}
176
-			} else {
177
-				// The scriptName is not ending with OC::$SUBURI
178
-				// This most likely means that we are calling from CLI.
179
-				// However some cron jobs still need to generate
180
-				// a web URL, so we use overwritewebroot as a fallback.
181
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
182
-			}
183
-
184
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
185
-			// slash which is required by URL generation.
186
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
187
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
188
-				header('Location: '.\OC::$WEBROOT.'/');
189
-				exit();
190
-			}
191
-		}
192
-
193
-		// search the apps folder
194
-		$config_paths = self::$config->getValue('apps_paths', array());
195
-		if (!empty($config_paths)) {
196
-			foreach ($config_paths as $paths) {
197
-				if (isset($paths['url']) && isset($paths['path'])) {
198
-					$paths['url'] = rtrim($paths['url'], '/');
199
-					$paths['path'] = rtrim($paths['path'], '/');
200
-					OC::$APPSROOTS[] = $paths;
201
-				}
202
-			}
203
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
206
-			OC::$APPSROOTS[] = array(
207
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
208
-				'url' => '/apps',
209
-				'writable' => true
210
-			);
211
-		}
212
-
213
-		if (empty(OC::$APPSROOTS)) {
214
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
215
-				. ' or the folder above. You can also configure the location in the config.php file.');
216
-		}
217
-		$paths = array();
218
-		foreach (OC::$APPSROOTS as $path) {
219
-			$paths[] = $path['path'];
220
-			if (!is_dir($path['path'])) {
221
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
222
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
223
-					. ' config.php file.', $path['path']));
224
-			}
225
-		}
226
-
227
-		// set the right include path
228
-		set_include_path(
229
-			implode(PATH_SEPARATOR, $paths)
230
-		);
231
-	}
232
-
233
-	public static function checkConfig() {
234
-		$l = \OC::$server->getL10N('lib');
235
-
236
-		// Create config if it does not already exist
237
-		$configFilePath = self::$configDir .'/config.php';
238
-		if(!file_exists($configFilePath)) {
239
-			@touch($configFilePath);
240
-		}
241
-
242
-		// Check if config is writable
243
-		$configFileWritable = is_writable($configFilePath);
244
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
245
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
246
-
247
-			$urlGenerator = \OC::$server->getURLGenerator();
248
-
249
-			if (self::$CLI) {
250
-				echo $l->t('Cannot write into "config" directory!')."\n";
251
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
253
-				echo "\n";
254
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
256
-				exit;
257
-			} else {
258
-				OC_Template::printErrorPage(
259
-					$l->t('Cannot write into "config" directory!'),
260
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
261
-					[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
262
-					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
263
-					[ $urlGenerator->linkToDocs('admin-config') ] ),
264
-					503
265
-				);
266
-			}
267
-		}
268
-	}
269
-
270
-	public static function checkInstalled() {
271
-		if (defined('OC_CONSOLE')) {
272
-			return;
273
-		}
274
-		// Redirect to installer if not installed
275
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
276
-			if (OC::$CLI) {
277
-				throw new Exception('Not installed');
278
-			} else {
279
-				$url = OC::$WEBROOT . '/index.php';
280
-				header('Location: ' . $url);
281
-			}
282
-			exit();
283
-		}
284
-	}
285
-
286
-	public static function checkMaintenanceMode() {
287
-		// Allow ajax update script to execute without being stopped
288
-		if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
289
-			// send http status 503
290
-			http_response_code(503);
291
-			header('Retry-After: 120');
292
-
293
-			// render error page
294
-			$template = new OC_Template('', 'update.user', 'guest');
295
-			OC_Util::addScript('maintenance-check');
296
-			OC_Util::addStyle('core', 'guest');
297
-			$template->printPage();
298
-			die();
299
-		}
300
-	}
301
-
302
-	/**
303
-	 * Prints the upgrade page
304
-	 *
305
-	 * @param \OC\SystemConfig $systemConfig
306
-	 */
307
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
308
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
309
-		$tooBig = false;
310
-		if (!$disableWebUpdater) {
311
-			$apps = \OC::$server->getAppManager();
312
-			if ($apps->isInstalled('user_ldap')) {
313
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
314
-
315
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
316
-					->from('ldap_user_mapping')
317
-					->execute();
318
-				$row = $result->fetch();
319
-				$result->closeCursor();
320
-
321
-				$tooBig = ($row['user_count'] > 50);
322
-			}
323
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
324
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
325
-
326
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
327
-					->from('user_saml_users')
328
-					->execute();
329
-				$row = $result->fetch();
330
-				$result->closeCursor();
331
-
332
-				$tooBig = ($row['user_count'] > 50);
333
-			}
334
-			if (!$tooBig) {
335
-				// count users
336
-				$stats = \OC::$server->getUserManager()->countUsers();
337
-				$totalUsers = array_sum($stats);
338
-				$tooBig = ($totalUsers > 50);
339
-			}
340
-		}
341
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
342
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
343
-
344
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
345
-			// send http status 503
346
-			http_response_code(503);
347
-			header('Retry-After: 120');
348
-
349
-			// render error page
350
-			$template = new OC_Template('', 'update.use-cli', 'guest');
351
-			$template->assign('productName', 'nextcloud'); // for now
352
-			$template->assign('version', OC_Util::getVersionString());
353
-			$template->assign('tooBig', $tooBig);
354
-
355
-			$template->printPage();
356
-			die();
357
-		}
358
-
359
-		// check whether this is a core update or apps update
360
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
361
-		$currentVersion = implode('.', \OCP\Util::getVersion());
362
-
363
-		// if not a core upgrade, then it's apps upgrade
364
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
365
-
366
-		$oldTheme = $systemConfig->getValue('theme');
367
-		$systemConfig->setValue('theme', '');
368
-		OC_Util::addScript('config'); // needed for web root
369
-		OC_Util::addScript('update');
370
-
371
-		/** @var \OC\App\AppManager $appManager */
372
-		$appManager = \OC::$server->getAppManager();
373
-
374
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
375
-		$tmpl->assign('version', OC_Util::getVersionString());
376
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
377
-
378
-		// get third party apps
379
-		$ocVersion = \OCP\Util::getVersion();
380
-		$ocVersion = implode('.', $ocVersion);
381
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
382
-		$incompatibleShippedApps = [];
383
-		foreach ($incompatibleApps as $appInfo) {
384
-			if ($appManager->isShipped($appInfo['id'])) {
385
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
386
-			}
387
-		}
388
-
389
-		if (!empty($incompatibleShippedApps)) {
390
-			$l = \OC::$server->getL10N('core');
391
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
392
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
393
-		}
394
-
395
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
396
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
397
-		$tmpl->assign('productName', 'Nextcloud'); // for now
398
-		$tmpl->assign('oldTheme', $oldTheme);
399
-		$tmpl->printPage();
400
-	}
401
-
402
-	public static function initSession() {
403
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
404
-			ini_set('session.cookie_secure', true);
405
-		}
406
-
407
-		// prevents javascript from accessing php session cookies
408
-		ini_set('session.cookie_httponly', 'true');
409
-
410
-		// set the cookie path to the Nextcloud directory
411
-		$cookie_path = OC::$WEBROOT ? : '/';
412
-		ini_set('session.cookie_path', $cookie_path);
413
-
414
-		// Let the session name be changed in the initSession Hook
415
-		$sessionName = OC_Util::getInstanceId();
416
-
417
-		try {
418
-			// Allow session apps to create a custom session object
419
-			$useCustomSession = false;
420
-			$session = self::$server->getSession();
421
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
422
-			if (!$useCustomSession) {
423
-				// set the session name to the instance id - which is unique
424
-				$session = new \OC\Session\Internal($sessionName);
425
-			}
426
-
427
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
428
-			$session = $cryptoWrapper->wrapSession($session);
429
-			self::$server->setSession($session);
430
-
431
-			// if session can't be started break with http 500 error
432
-		} catch (Exception $e) {
433
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
434
-			//show the user a detailed error page
435
-			OC_Template::printExceptionErrorPage($e, 500);
436
-			die();
437
-		}
438
-
439
-		$sessionLifeTime = self::getSessionLifeTime();
440
-
441
-		// session timeout
442
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
443
-			if (isset($_COOKIE[session_name()])) {
444
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
445
-			}
446
-			\OC::$server->getUserSession()->logout();
447
-		}
448
-
449
-		$session->set('LAST_ACTIVITY', time());
450
-	}
451
-
452
-	/**
453
-	 * @return string
454
-	 */
455
-	private static function getSessionLifeTime() {
456
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
457
-	}
458
-
459
-	/**
460
-	 * Try to set some values to the required Nextcloud default
461
-	 */
462
-	public static function setRequiredIniValues() {
463
-		@ini_set('default_charset', 'UTF-8');
464
-		@ini_set('gd.jpeg_ignore_warning', '1');
465
-	}
466
-
467
-	/**
468
-	 * Send the same site cookies
469
-	 */
470
-	private static function sendSameSiteCookies() {
471
-		$cookieParams = session_get_cookie_params();
472
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
473
-		$policies = [
474
-			'lax',
475
-			'strict',
476
-		];
477
-
478
-		// Append __Host to the cookie if it meets the requirements
479
-		$cookiePrefix = '';
480
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
481
-			$cookiePrefix = '__Host-';
482
-		}
483
-
484
-		foreach($policies as $policy) {
485
-			header(
486
-				sprintf(
487
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
488
-					$cookiePrefix,
489
-					$policy,
490
-					$cookieParams['path'],
491
-					$policy
492
-				),
493
-				false
494
-			);
495
-		}
496
-	}
497
-
498
-	/**
499
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
500
-	 * be set in every request if cookies are sent to add a second level of
501
-	 * defense against CSRF.
502
-	 *
503
-	 * If the cookie is not sent this will set the cookie and reload the page.
504
-	 * We use an additional cookie since we want to protect logout CSRF and
505
-	 * also we can't directly interfere with PHP's session mechanism.
506
-	 */
507
-	private static function performSameSiteCookieProtection() {
508
-		$request = \OC::$server->getRequest();
509
-
510
-		// Some user agents are notorious and don't really properly follow HTTP
511
-		// specifications. For those, have an automated opt-out. Since the protection
512
-		// for remote.php is applied in base.php as starting point we need to opt out
513
-		// here.
514
-		$incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
515
-
516
-		// Fallback, if csrf.optout is unset
517
-		if (!is_array($incompatibleUserAgents)) {
518
-			$incompatibleUserAgents = [
519
-				// OS X Finder
520
-				'/^WebDAVFS/',
521
-				// Windows webdav drive
522
-				'/^Microsoft-WebDAV-MiniRedir/',
523
-			];
524
-		}
525
-
526
-		if($request->isUserAgent($incompatibleUserAgents)) {
527
-			return;
528
-		}
529
-
530
-		if(count($_COOKIE) > 0) {
531
-			$requestUri = $request->getScriptName();
532
-			$processingScript = explode('/', $requestUri);
533
-			$processingScript = $processingScript[count($processingScript)-1];
534
-
535
-			// index.php routes are handled in the middleware
536
-			if($processingScript === 'index.php') {
537
-				return;
538
-			}
539
-
540
-			// All other endpoints require the lax and the strict cookie
541
-			if(!$request->passesStrictCookieCheck()) {
542
-				self::sendSameSiteCookies();
543
-				// Debug mode gets access to the resources without strict cookie
544
-				// due to the fact that the SabreDAV browser also lives there.
545
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
546
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
547
-					exit();
548
-				}
549
-			}
550
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
551
-			self::sendSameSiteCookies();
552
-		}
553
-	}
554
-
555
-	public static function init() {
556
-		// calculate the root directories
557
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
558
-
559
-		// register autoloader
560
-		$loaderStart = microtime(true);
561
-		require_once __DIR__ . '/autoloader.php';
562
-		self::$loader = new \OC\Autoloader([
563
-			OC::$SERVERROOT . '/lib/private/legacy',
564
-		]);
565
-		if (defined('PHPUNIT_RUN')) {
566
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
567
-		}
568
-		spl_autoload_register(array(self::$loader, 'load'));
569
-		$loaderEnd = microtime(true);
570
-
571
-		self::$CLI = (php_sapi_name() == 'cli');
572
-
573
-		// Add default composer PSR-4 autoloader
574
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
575
-
576
-		try {
577
-			self::initPaths();
578
-			// setup 3rdparty autoloader
579
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
580
-			if (!file_exists($vendorAutoLoad)) {
581
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
582
-			}
583
-			require_once $vendorAutoLoad;
584
-
585
-		} catch (\RuntimeException $e) {
586
-			if (!self::$CLI) {
587
-				http_response_code(503);
588
-			}
589
-			// we can't use the template error page here, because this needs the
590
-			// DI container which isn't available yet
591
-			print($e->getMessage());
592
-			exit();
593
-		}
594
-
595
-		// setup the basic server
596
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
597
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
598
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
599
-
600
-		// Don't display errors and log them
601
-		error_reporting(E_ALL | E_STRICT);
602
-		@ini_set('display_errors', '0');
603
-		@ini_set('log_errors', '1');
604
-
605
-		if(!date_default_timezone_set('UTC')) {
606
-			throw new \RuntimeException('Could not set timezone to UTC');
607
-		}
608
-
609
-		//try to configure php to enable big file uploads.
610
-		//this doesn´t work always depending on the webserver and php configuration.
611
-		//Let´s try to overwrite some defaults anyway
612
-
613
-		//try to set the maximum execution time to 60min
614
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
615
-			@set_time_limit(3600);
616
-		}
617
-		@ini_set('max_execution_time', '3600');
618
-		@ini_set('max_input_time', '3600');
619
-
620
-		//try to set the maximum filesize to 10G
621
-		@ini_set('upload_max_filesize', '10G');
622
-		@ini_set('post_max_size', '10G');
623
-		@ini_set('file_uploads', '50');
624
-
625
-		self::setRequiredIniValues();
626
-		self::handleAuthHeaders();
627
-		self::registerAutoloaderCache();
628
-
629
-		// initialize intl fallback is necessary
630
-		\Patchwork\Utf8\Bootup::initIntl();
631
-		OC_Util::isSetLocaleWorking();
632
-
633
-		if (!defined('PHPUNIT_RUN')) {
634
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
635
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
636
-			OC\Log\ErrorHandler::register($debug);
637
-		}
638
-
639
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
640
-		OC_App::loadApps(array('session'));
641
-		if (!self::$CLI) {
642
-			self::initSession();
643
-		}
644
-		\OC::$server->getEventLogger()->end('init_session');
645
-		self::checkConfig();
646
-		self::checkInstalled();
647
-
648
-		OC_Response::addSecurityHeaders();
649
-
650
-		self::performSameSiteCookieProtection();
651
-
652
-		if (!defined('OC_CONSOLE')) {
653
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
654
-			if (count($errors) > 0) {
655
-				if (self::$CLI) {
656
-					// Convert l10n string into regular string for usage in database
657
-					$staticErrors = [];
658
-					foreach ($errors as $error) {
659
-						echo $error['error'] . "\n";
660
-						echo $error['hint'] . "\n\n";
661
-						$staticErrors[] = [
662
-							'error' => (string)$error['error'],
663
-							'hint' => (string)$error['hint'],
664
-						];
665
-					}
666
-
667
-					try {
668
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
669
-					} catch (\Exception $e) {
670
-						echo('Writing to database failed');
671
-					}
672
-					exit(1);
673
-				} else {
674
-					http_response_code(503);
675
-					OC_Util::addStyle('guest');
676
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
677
-					exit;
678
-				}
679
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
680
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
681
-			}
682
-		}
683
-		//try to set the session lifetime
684
-		$sessionLifeTime = self::getSessionLifeTime();
685
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
686
-
687
-		$systemConfig = \OC::$server->getSystemConfig();
688
-
689
-		// User and Groups
690
-		if (!$systemConfig->getValue("installed", false)) {
691
-			self::$server->getSession()->set('user_id', '');
692
-		}
693
-
694
-		OC_User::useBackend(new \OC\User\Database());
695
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
696
-
697
-		// Subscribe to the hook
698
-		\OCP\Util::connectHook(
699
-			'\OCA\Files_Sharing\API\Server2Server',
700
-			'preLoginNameUsedAsUserName',
701
-			'\OC\User\Database',
702
-			'preLoginNameUsedAsUserName'
703
-		);
704
-
705
-		//setup extra user backends
706
-		if (!\OCP\Util::needUpgrade()) {
707
-			OC_User::setupBackends();
708
-		} else {
709
-			// Run upgrades in incognito mode
710
-			OC_User::setIncognitoMode(true);
711
-		}
712
-
713
-		self::registerCleanupHooks();
714
-		self::registerFilesystemHooks();
715
-		self::registerShareHooks();
716
-		self::registerEncryptionWrapper();
717
-		self::registerEncryptionHooks();
718
-		self::registerAccountHooks();
719
-		self::registerResourceCollectionHooks();
720
-
721
-		// Make sure that the application class is not loaded before the database is setup
722
-		if ($systemConfig->getValue("installed", false)) {
723
-			$settings = new \OC\Settings\Application();
724
-			$settings->register();
725
-		}
726
-
727
-		//make sure temporary files are cleaned up
728
-		$tmpManager = \OC::$server->getTempManager();
729
-		register_shutdown_function(array($tmpManager, 'clean'));
730
-		$lockProvider = \OC::$server->getLockingProvider();
731
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
732
-
733
-		// Check whether the sample configuration has been copied
734
-		if($systemConfig->getValue('copied_sample_config', false)) {
735
-			$l = \OC::$server->getL10N('lib');
736
-			OC_Template::printErrorPage(
737
-				$l->t('Sample configuration detected'),
738
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
739
-				503
740
-			);
741
-			return;
742
-		}
743
-
744
-		$request = \OC::$server->getRequest();
745
-		$host = $request->getInsecureServerHost();
746
-		/**
747
-		 * if the host passed in headers isn't trusted
748
-		 * FIXME: Should not be in here at all :see_no_evil:
749
-		 */
750
-		if (!OC::$CLI
751
-			// overwritehost is always trusted, workaround to not have to make
752
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
753
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
754
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
755
-			&& self::$server->getConfig()->getSystemValue('installed', false)
756
-		) {
757
-			// Allow access to CSS resources
758
-			$isScssRequest = false;
759
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
760
-				$isScssRequest = true;
761
-			}
762
-
763
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
764
-				http_response_code(400);
765
-				header('Content-Type: application/json');
766
-				echo '{"error": "Trusted domain error.", "code": 15}';
767
-				exit();
768
-			}
769
-
770
-			if (!$isScssRequest) {
771
-				http_response_code(400);
772
-
773
-				\OC::$server->getLogger()->info(
774
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
775
-					[
776
-						'app' => 'core',
777
-						'remoteAddress' => $request->getRemoteAddress(),
778
-						'host' => $host,
779
-					]
780
-				);
781
-
782
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
783
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
784
-				$tmpl->printPage();
785
-
786
-				exit();
787
-			}
788
-		}
789
-		\OC::$server->getEventLogger()->end('boot');
790
-	}
791
-
792
-	/**
793
-	 * register hooks for the cleanup of cache and bruteforce protection
794
-	 */
795
-	public static function registerCleanupHooks() {
796
-		//don't try to do this before we are properly setup
797
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
798
-
799
-			// NOTE: This will be replaced to use OCP
800
-			$userSession = self::$server->getUserSession();
801
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
802
-				if (!defined('PHPUNIT_RUN')) {
803
-					// reset brute force delay for this IP address and username
804
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
805
-					$request = \OC::$server->getRequest();
806
-					$throttler = \OC::$server->getBruteForceThrottler();
807
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
808
-				}
809
-
810
-				try {
811
-					$cache = new \OC\Cache\File();
812
-					$cache->gc();
813
-				} catch (\OC\ServerNotAvailableException $e) {
814
-					// not a GC exception, pass it on
815
-					throw $e;
816
-				} catch (\OC\ForbiddenException $e) {
817
-					// filesystem blocked for this request, ignore
818
-				} catch (\Exception $e) {
819
-					// a GC exception should not prevent users from using OC,
820
-					// so log the exception
821
-					\OC::$server->getLogger()->logException($e, [
822
-						'message' => 'Exception when running cache gc.',
823
-						'level' => ILogger::WARN,
824
-						'app' => 'core',
825
-					]);
826
-				}
827
-			});
828
-		}
829
-	}
830
-
831
-	private static function registerEncryptionWrapper() {
832
-		$manager = self::$server->getEncryptionManager();
833
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
834
-	}
835
-
836
-	private static function registerEncryptionHooks() {
837
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
838
-		if ($enabled) {
839
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
840
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
841
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
842
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
843
-		}
844
-	}
845
-
846
-	private static function registerAccountHooks() {
847
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
848
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
849
-	}
850
-
851
-	private static function registerResourceCollectionHooks() {
852
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
853
-	}
854
-
855
-	/**
856
-	 * register hooks for the filesystem
857
-	 */
858
-	public static function registerFilesystemHooks() {
859
-		// Check for blacklisted files
860
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
861
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
862
-	}
863
-
864
-	/**
865
-	 * register hooks for sharing
866
-	 */
867
-	public static function registerShareHooks() {
868
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
869
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
870
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
871
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
872
-		}
873
-	}
874
-
875
-	protected static function registerAutoloaderCache() {
876
-		// The class loader takes an optional low-latency cache, which MUST be
877
-		// namespaced. The instanceid is used for namespacing, but might be
878
-		// unavailable at this point. Furthermore, it might not be possible to
879
-		// generate an instanceid via \OC_Util::getInstanceId() because the
880
-		// config file may not be writable. As such, we only register a class
881
-		// loader cache if instanceid is available without trying to create one.
882
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
883
-		if ($instanceId) {
884
-			try {
885
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
886
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
887
-			} catch (\Exception $ex) {
888
-			}
889
-		}
890
-	}
891
-
892
-	/**
893
-	 * Handle the request
894
-	 */
895
-	public static function handleRequest() {
896
-
897
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
898
-		$systemConfig = \OC::$server->getSystemConfig();
899
-
900
-		// Check if Nextcloud is installed or in maintenance (update) mode
901
-		if (!$systemConfig->getValue('installed', false)) {
902
-			\OC::$server->getSession()->clear();
903
-			$setupHelper = new OC\Setup(
904
-				$systemConfig,
905
-				\OC::$server->getIniWrapper(),
906
-				\OC::$server->getL10N('lib'),
907
-				\OC::$server->query(\OCP\Defaults::class),
908
-				\OC::$server->getLogger(),
909
-				\OC::$server->getSecureRandom(),
910
-				\OC::$server->query(\OC\Installer::class)
911
-			);
912
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
913
-			$controller->run($_POST);
914
-			exit();
915
-		}
916
-
917
-		$request = \OC::$server->getRequest();
918
-		$requestPath = $request->getRawPathInfo();
919
-		if ($requestPath === '/heartbeat') {
920
-			return;
921
-		}
922
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
923
-			self::checkMaintenanceMode();
924
-
925
-			if (\OCP\Util::needUpgrade()) {
926
-				if (function_exists('opcache_reset')) {
927
-					opcache_reset();
928
-				}
929
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
930
-					self::printUpgradePage($systemConfig);
931
-					exit();
932
-				}
933
-			}
934
-		}
935
-
936
-		// emergency app disabling
937
-		if ($requestPath === '/disableapp'
938
-			&& $request->getMethod() === 'POST'
939
-			&& ((array)$request->getParam('appid')) !== ''
940
-		) {
941
-			\OC_JSON::callCheck();
942
-			\OC_JSON::checkAdminUser();
943
-			$appIds = (array)$request->getParam('appid');
944
-			foreach($appIds as $appId) {
945
-				$appId = \OC_App::cleanAppId($appId);
946
-				\OC::$server->getAppManager()->disableApp($appId);
947
-			}
948
-			\OC_JSON::success();
949
-			exit();
950
-		}
951
-
952
-		// Always load authentication apps
953
-		OC_App::loadApps(['authentication']);
954
-
955
-		// Load minimum set of apps
956
-		if (!\OCP\Util::needUpgrade()
957
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
958
-			// For logged-in users: Load everything
959
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
960
-				OC_App::loadApps();
961
-			} else {
962
-				// For guests: Load only filesystem and logging
963
-				OC_App::loadApps(array('filesystem', 'logging'));
964
-				self::handleLogin($request);
965
-			}
966
-		}
967
-
968
-		if (!self::$CLI) {
969
-			try {
970
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
971
-					OC_App::loadApps(array('filesystem', 'logging'));
972
-					OC_App::loadApps();
973
-				}
974
-				OC_Util::setupFS();
975
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
976
-				return;
977
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
978
-				//header('HTTP/1.0 404 Not Found');
979
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
980
-				http_response_code(405);
981
-				return;
982
-			}
983
-		}
984
-
985
-		// Handle WebDAV
986
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
987
-			// not allowed any more to prevent people
988
-			// mounting this root directly.
989
-			// Users need to mount remote.php/webdav instead.
990
-			http_response_code(405);
991
-			return;
992
-		}
993
-
994
-		// Someone is logged in
995
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
996
-			OC_App::loadApps();
997
-			OC_User::setupBackends();
998
-			OC_Util::setupFS();
999
-			// FIXME
1000
-			// Redirect to default application
1001
-			OC_Util::redirectToDefaultPage();
1002
-		} else {
1003
-			// Not handled and not logged in
1004
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1005
-		}
1006
-	}
1007
-
1008
-	/**
1009
-	 * Check login: apache auth, auth token, basic auth
1010
-	 *
1011
-	 * @param OCP\IRequest $request
1012
-	 * @return boolean
1013
-	 */
1014
-	static function handleLogin(OCP\IRequest $request) {
1015
-		$userSession = self::$server->getUserSession();
1016
-		if (OC_User::handleApacheAuth()) {
1017
-			return true;
1018
-		}
1019
-		if ($userSession->tryTokenLogin($request)) {
1020
-			return true;
1021
-		}
1022
-		if (isset($_COOKIE['nc_username'])
1023
-			&& isset($_COOKIE['nc_token'])
1024
-			&& isset($_COOKIE['nc_session_id'])
1025
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1026
-			return true;
1027
-		}
1028
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1029
-			return true;
1030
-		}
1031
-		return false;
1032
-	}
1033
-
1034
-	protected static function handleAuthHeaders() {
1035
-		//copy http auth headers for apache+php-fcgid work around
1036
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1037
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1038
-		}
1039
-
1040
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1041
-		$vars = array(
1042
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1043
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1044
-		);
1045
-		foreach ($vars as $var) {
1046
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1047
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1048
-				$_SERVER['PHP_AUTH_USER'] = $name;
1049
-				$_SERVER['PHP_AUTH_PW'] = $password;
1050
-				break;
1051
-			}
1052
-		}
1053
-	}
71
+    /**
72
+     * Associative array for autoloading. classname => filename
73
+     */
74
+    public static $CLASSPATH = array();
75
+    /**
76
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
77
+     */
78
+    public static $SERVERROOT = '';
79
+    /**
80
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
81
+     */
82
+    private static $SUBURI = '';
83
+    /**
84
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
85
+     */
86
+    public static $WEBROOT = '';
87
+    /**
88
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
89
+     * web path in 'url'
90
+     */
91
+    public static $APPSROOTS = array();
92
+
93
+    /**
94
+     * @var string
95
+     */
96
+    public static $configDir;
97
+
98
+    /**
99
+     * requested app
100
+     */
101
+    public static $REQUESTEDAPP = '';
102
+
103
+    /**
104
+     * check if Nextcloud runs in cli mode
105
+     */
106
+    public static $CLI = false;
107
+
108
+    /**
109
+     * @var \OC\Autoloader $loader
110
+     */
111
+    public static $loader = null;
112
+
113
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
114
+    public static $composerAutoloader = null;
115
+
116
+    /**
117
+     * @var \OC\Server
118
+     */
119
+    public static $server = null;
120
+
121
+    /**
122
+     * @var \OC\Config
123
+     */
124
+    private static $config = null;
125
+
126
+    /**
127
+     * @throws \RuntimeException when the 3rdparty directory is missing or
128
+     * the app path list is empty or contains an invalid path
129
+     */
130
+    public static function initPaths() {
131
+        if(defined('PHPUNIT_CONFIG_DIR')) {
132
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
+            self::$configDir = rtrim($dir, '/') . '/';
137
+        } else {
138
+            self::$configDir = OC::$SERVERROOT . '/config/';
139
+        }
140
+        self::$config = new \OC\Config(self::$configDir);
141
+
142
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
143
+        /**
144
+         * FIXME: The following lines are required because we can't yet instantiate
145
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
146
+         */
147
+        $params = [
148
+            'server' => [
149
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
150
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
151
+            ],
152
+        ];
153
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
154
+        $scriptName = $fakeRequest->getScriptName();
155
+        if (substr($scriptName, -1) == '/') {
156
+            $scriptName .= 'index.php';
157
+            //make sure suburi follows the same rules as scriptName
158
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
159
+                if (substr(OC::$SUBURI, -1) != '/') {
160
+                    OC::$SUBURI = OC::$SUBURI . '/';
161
+                }
162
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
163
+            }
164
+        }
165
+
166
+
167
+        if (OC::$CLI) {
168
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
169
+        } else {
170
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
171
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172
+
173
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
175
+                }
176
+            } else {
177
+                // The scriptName is not ending with OC::$SUBURI
178
+                // This most likely means that we are calling from CLI.
179
+                // However some cron jobs still need to generate
180
+                // a web URL, so we use overwritewebroot as a fallback.
181
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
182
+            }
183
+
184
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
185
+            // slash which is required by URL generation.
186
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
187
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
188
+                header('Location: '.\OC::$WEBROOT.'/');
189
+                exit();
190
+            }
191
+        }
192
+
193
+        // search the apps folder
194
+        $config_paths = self::$config->getValue('apps_paths', array());
195
+        if (!empty($config_paths)) {
196
+            foreach ($config_paths as $paths) {
197
+                if (isset($paths['url']) && isset($paths['path'])) {
198
+                    $paths['url'] = rtrim($paths['url'], '/');
199
+                    $paths['path'] = rtrim($paths['path'], '/');
200
+                    OC::$APPSROOTS[] = $paths;
201
+                }
202
+            }
203
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
206
+            OC::$APPSROOTS[] = array(
207
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
208
+                'url' => '/apps',
209
+                'writable' => true
210
+            );
211
+        }
212
+
213
+        if (empty(OC::$APPSROOTS)) {
214
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
215
+                . ' or the folder above. You can also configure the location in the config.php file.');
216
+        }
217
+        $paths = array();
218
+        foreach (OC::$APPSROOTS as $path) {
219
+            $paths[] = $path['path'];
220
+            if (!is_dir($path['path'])) {
221
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
222
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
223
+                    . ' config.php file.', $path['path']));
224
+            }
225
+        }
226
+
227
+        // set the right include path
228
+        set_include_path(
229
+            implode(PATH_SEPARATOR, $paths)
230
+        );
231
+    }
232
+
233
+    public static function checkConfig() {
234
+        $l = \OC::$server->getL10N('lib');
235
+
236
+        // Create config if it does not already exist
237
+        $configFilePath = self::$configDir .'/config.php';
238
+        if(!file_exists($configFilePath)) {
239
+            @touch($configFilePath);
240
+        }
241
+
242
+        // Check if config is writable
243
+        $configFileWritable = is_writable($configFilePath);
244
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
245
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
246
+
247
+            $urlGenerator = \OC::$server->getURLGenerator();
248
+
249
+            if (self::$CLI) {
250
+                echo $l->t('Cannot write into "config" directory!')."\n";
251
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
253
+                echo "\n";
254
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
256
+                exit;
257
+            } else {
258
+                OC_Template::printErrorPage(
259
+                    $l->t('Cannot write into "config" directory!'),
260
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
261
+                    [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
262
+                    . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
263
+                    [ $urlGenerator->linkToDocs('admin-config') ] ),
264
+                    503
265
+                );
266
+            }
267
+        }
268
+    }
269
+
270
+    public static function checkInstalled() {
271
+        if (defined('OC_CONSOLE')) {
272
+            return;
273
+        }
274
+        // Redirect to installer if not installed
275
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
276
+            if (OC::$CLI) {
277
+                throw new Exception('Not installed');
278
+            } else {
279
+                $url = OC::$WEBROOT . '/index.php';
280
+                header('Location: ' . $url);
281
+            }
282
+            exit();
283
+        }
284
+    }
285
+
286
+    public static function checkMaintenanceMode() {
287
+        // Allow ajax update script to execute without being stopped
288
+        if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
289
+            // send http status 503
290
+            http_response_code(503);
291
+            header('Retry-After: 120');
292
+
293
+            // render error page
294
+            $template = new OC_Template('', 'update.user', 'guest');
295
+            OC_Util::addScript('maintenance-check');
296
+            OC_Util::addStyle('core', 'guest');
297
+            $template->printPage();
298
+            die();
299
+        }
300
+    }
301
+
302
+    /**
303
+     * Prints the upgrade page
304
+     *
305
+     * @param \OC\SystemConfig $systemConfig
306
+     */
307
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
308
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
309
+        $tooBig = false;
310
+        if (!$disableWebUpdater) {
311
+            $apps = \OC::$server->getAppManager();
312
+            if ($apps->isInstalled('user_ldap')) {
313
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
314
+
315
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
316
+                    ->from('ldap_user_mapping')
317
+                    ->execute();
318
+                $row = $result->fetch();
319
+                $result->closeCursor();
320
+
321
+                $tooBig = ($row['user_count'] > 50);
322
+            }
323
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
324
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
325
+
326
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
327
+                    ->from('user_saml_users')
328
+                    ->execute();
329
+                $row = $result->fetch();
330
+                $result->closeCursor();
331
+
332
+                $tooBig = ($row['user_count'] > 50);
333
+            }
334
+            if (!$tooBig) {
335
+                // count users
336
+                $stats = \OC::$server->getUserManager()->countUsers();
337
+                $totalUsers = array_sum($stats);
338
+                $tooBig = ($totalUsers > 50);
339
+            }
340
+        }
341
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
342
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
343
+
344
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
345
+            // send http status 503
346
+            http_response_code(503);
347
+            header('Retry-After: 120');
348
+
349
+            // render error page
350
+            $template = new OC_Template('', 'update.use-cli', 'guest');
351
+            $template->assign('productName', 'nextcloud'); // for now
352
+            $template->assign('version', OC_Util::getVersionString());
353
+            $template->assign('tooBig', $tooBig);
354
+
355
+            $template->printPage();
356
+            die();
357
+        }
358
+
359
+        // check whether this is a core update or apps update
360
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
361
+        $currentVersion = implode('.', \OCP\Util::getVersion());
362
+
363
+        // if not a core upgrade, then it's apps upgrade
364
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
365
+
366
+        $oldTheme = $systemConfig->getValue('theme');
367
+        $systemConfig->setValue('theme', '');
368
+        OC_Util::addScript('config'); // needed for web root
369
+        OC_Util::addScript('update');
370
+
371
+        /** @var \OC\App\AppManager $appManager */
372
+        $appManager = \OC::$server->getAppManager();
373
+
374
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
375
+        $tmpl->assign('version', OC_Util::getVersionString());
376
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
377
+
378
+        // get third party apps
379
+        $ocVersion = \OCP\Util::getVersion();
380
+        $ocVersion = implode('.', $ocVersion);
381
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
382
+        $incompatibleShippedApps = [];
383
+        foreach ($incompatibleApps as $appInfo) {
384
+            if ($appManager->isShipped($appInfo['id'])) {
385
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
386
+            }
387
+        }
388
+
389
+        if (!empty($incompatibleShippedApps)) {
390
+            $l = \OC::$server->getL10N('core');
391
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
392
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
393
+        }
394
+
395
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
396
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
397
+        $tmpl->assign('productName', 'Nextcloud'); // for now
398
+        $tmpl->assign('oldTheme', $oldTheme);
399
+        $tmpl->printPage();
400
+    }
401
+
402
+    public static function initSession() {
403
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
404
+            ini_set('session.cookie_secure', true);
405
+        }
406
+
407
+        // prevents javascript from accessing php session cookies
408
+        ini_set('session.cookie_httponly', 'true');
409
+
410
+        // set the cookie path to the Nextcloud directory
411
+        $cookie_path = OC::$WEBROOT ? : '/';
412
+        ini_set('session.cookie_path', $cookie_path);
413
+
414
+        // Let the session name be changed in the initSession Hook
415
+        $sessionName = OC_Util::getInstanceId();
416
+
417
+        try {
418
+            // Allow session apps to create a custom session object
419
+            $useCustomSession = false;
420
+            $session = self::$server->getSession();
421
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
422
+            if (!$useCustomSession) {
423
+                // set the session name to the instance id - which is unique
424
+                $session = new \OC\Session\Internal($sessionName);
425
+            }
426
+
427
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
428
+            $session = $cryptoWrapper->wrapSession($session);
429
+            self::$server->setSession($session);
430
+
431
+            // if session can't be started break with http 500 error
432
+        } catch (Exception $e) {
433
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
434
+            //show the user a detailed error page
435
+            OC_Template::printExceptionErrorPage($e, 500);
436
+            die();
437
+        }
438
+
439
+        $sessionLifeTime = self::getSessionLifeTime();
440
+
441
+        // session timeout
442
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
443
+            if (isset($_COOKIE[session_name()])) {
444
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
445
+            }
446
+            \OC::$server->getUserSession()->logout();
447
+        }
448
+
449
+        $session->set('LAST_ACTIVITY', time());
450
+    }
451
+
452
+    /**
453
+     * @return string
454
+     */
455
+    private static function getSessionLifeTime() {
456
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
457
+    }
458
+
459
+    /**
460
+     * Try to set some values to the required Nextcloud default
461
+     */
462
+    public static function setRequiredIniValues() {
463
+        @ini_set('default_charset', 'UTF-8');
464
+        @ini_set('gd.jpeg_ignore_warning', '1');
465
+    }
466
+
467
+    /**
468
+     * Send the same site cookies
469
+     */
470
+    private static function sendSameSiteCookies() {
471
+        $cookieParams = session_get_cookie_params();
472
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
473
+        $policies = [
474
+            'lax',
475
+            'strict',
476
+        ];
477
+
478
+        // Append __Host to the cookie if it meets the requirements
479
+        $cookiePrefix = '';
480
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
481
+            $cookiePrefix = '__Host-';
482
+        }
483
+
484
+        foreach($policies as $policy) {
485
+            header(
486
+                sprintf(
487
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
488
+                    $cookiePrefix,
489
+                    $policy,
490
+                    $cookieParams['path'],
491
+                    $policy
492
+                ),
493
+                false
494
+            );
495
+        }
496
+    }
497
+
498
+    /**
499
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
500
+     * be set in every request if cookies are sent to add a second level of
501
+     * defense against CSRF.
502
+     *
503
+     * If the cookie is not sent this will set the cookie and reload the page.
504
+     * We use an additional cookie since we want to protect logout CSRF and
505
+     * also we can't directly interfere with PHP's session mechanism.
506
+     */
507
+    private static function performSameSiteCookieProtection() {
508
+        $request = \OC::$server->getRequest();
509
+
510
+        // Some user agents are notorious and don't really properly follow HTTP
511
+        // specifications. For those, have an automated opt-out. Since the protection
512
+        // for remote.php is applied in base.php as starting point we need to opt out
513
+        // here.
514
+        $incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
515
+
516
+        // Fallback, if csrf.optout is unset
517
+        if (!is_array($incompatibleUserAgents)) {
518
+            $incompatibleUserAgents = [
519
+                // OS X Finder
520
+                '/^WebDAVFS/',
521
+                // Windows webdav drive
522
+                '/^Microsoft-WebDAV-MiniRedir/',
523
+            ];
524
+        }
525
+
526
+        if($request->isUserAgent($incompatibleUserAgents)) {
527
+            return;
528
+        }
529
+
530
+        if(count($_COOKIE) > 0) {
531
+            $requestUri = $request->getScriptName();
532
+            $processingScript = explode('/', $requestUri);
533
+            $processingScript = $processingScript[count($processingScript)-1];
534
+
535
+            // index.php routes are handled in the middleware
536
+            if($processingScript === 'index.php') {
537
+                return;
538
+            }
539
+
540
+            // All other endpoints require the lax and the strict cookie
541
+            if(!$request->passesStrictCookieCheck()) {
542
+                self::sendSameSiteCookies();
543
+                // Debug mode gets access to the resources without strict cookie
544
+                // due to the fact that the SabreDAV browser also lives there.
545
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
546
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
547
+                    exit();
548
+                }
549
+            }
550
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
551
+            self::sendSameSiteCookies();
552
+        }
553
+    }
554
+
555
+    public static function init() {
556
+        // calculate the root directories
557
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
558
+
559
+        // register autoloader
560
+        $loaderStart = microtime(true);
561
+        require_once __DIR__ . '/autoloader.php';
562
+        self::$loader = new \OC\Autoloader([
563
+            OC::$SERVERROOT . '/lib/private/legacy',
564
+        ]);
565
+        if (defined('PHPUNIT_RUN')) {
566
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
567
+        }
568
+        spl_autoload_register(array(self::$loader, 'load'));
569
+        $loaderEnd = microtime(true);
570
+
571
+        self::$CLI = (php_sapi_name() == 'cli');
572
+
573
+        // Add default composer PSR-4 autoloader
574
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
575
+
576
+        try {
577
+            self::initPaths();
578
+            // setup 3rdparty autoloader
579
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
580
+            if (!file_exists($vendorAutoLoad)) {
581
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
582
+            }
583
+            require_once $vendorAutoLoad;
584
+
585
+        } catch (\RuntimeException $e) {
586
+            if (!self::$CLI) {
587
+                http_response_code(503);
588
+            }
589
+            // we can't use the template error page here, because this needs the
590
+            // DI container which isn't available yet
591
+            print($e->getMessage());
592
+            exit();
593
+        }
594
+
595
+        // setup the basic server
596
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
597
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
598
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
599
+
600
+        // Don't display errors and log them
601
+        error_reporting(E_ALL | E_STRICT);
602
+        @ini_set('display_errors', '0');
603
+        @ini_set('log_errors', '1');
604
+
605
+        if(!date_default_timezone_set('UTC')) {
606
+            throw new \RuntimeException('Could not set timezone to UTC');
607
+        }
608
+
609
+        //try to configure php to enable big file uploads.
610
+        //this doesn´t work always depending on the webserver and php configuration.
611
+        //Let´s try to overwrite some defaults anyway
612
+
613
+        //try to set the maximum execution time to 60min
614
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
615
+            @set_time_limit(3600);
616
+        }
617
+        @ini_set('max_execution_time', '3600');
618
+        @ini_set('max_input_time', '3600');
619
+
620
+        //try to set the maximum filesize to 10G
621
+        @ini_set('upload_max_filesize', '10G');
622
+        @ini_set('post_max_size', '10G');
623
+        @ini_set('file_uploads', '50');
624
+
625
+        self::setRequiredIniValues();
626
+        self::handleAuthHeaders();
627
+        self::registerAutoloaderCache();
628
+
629
+        // initialize intl fallback is necessary
630
+        \Patchwork\Utf8\Bootup::initIntl();
631
+        OC_Util::isSetLocaleWorking();
632
+
633
+        if (!defined('PHPUNIT_RUN')) {
634
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
635
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
636
+            OC\Log\ErrorHandler::register($debug);
637
+        }
638
+
639
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
640
+        OC_App::loadApps(array('session'));
641
+        if (!self::$CLI) {
642
+            self::initSession();
643
+        }
644
+        \OC::$server->getEventLogger()->end('init_session');
645
+        self::checkConfig();
646
+        self::checkInstalled();
647
+
648
+        OC_Response::addSecurityHeaders();
649
+
650
+        self::performSameSiteCookieProtection();
651
+
652
+        if (!defined('OC_CONSOLE')) {
653
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
654
+            if (count($errors) > 0) {
655
+                if (self::$CLI) {
656
+                    // Convert l10n string into regular string for usage in database
657
+                    $staticErrors = [];
658
+                    foreach ($errors as $error) {
659
+                        echo $error['error'] . "\n";
660
+                        echo $error['hint'] . "\n\n";
661
+                        $staticErrors[] = [
662
+                            'error' => (string)$error['error'],
663
+                            'hint' => (string)$error['hint'],
664
+                        ];
665
+                    }
666
+
667
+                    try {
668
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
669
+                    } catch (\Exception $e) {
670
+                        echo('Writing to database failed');
671
+                    }
672
+                    exit(1);
673
+                } else {
674
+                    http_response_code(503);
675
+                    OC_Util::addStyle('guest');
676
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
677
+                    exit;
678
+                }
679
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
680
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
681
+            }
682
+        }
683
+        //try to set the session lifetime
684
+        $sessionLifeTime = self::getSessionLifeTime();
685
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
686
+
687
+        $systemConfig = \OC::$server->getSystemConfig();
688
+
689
+        // User and Groups
690
+        if (!$systemConfig->getValue("installed", false)) {
691
+            self::$server->getSession()->set('user_id', '');
692
+        }
693
+
694
+        OC_User::useBackend(new \OC\User\Database());
695
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
696
+
697
+        // Subscribe to the hook
698
+        \OCP\Util::connectHook(
699
+            '\OCA\Files_Sharing\API\Server2Server',
700
+            'preLoginNameUsedAsUserName',
701
+            '\OC\User\Database',
702
+            'preLoginNameUsedAsUserName'
703
+        );
704
+
705
+        //setup extra user backends
706
+        if (!\OCP\Util::needUpgrade()) {
707
+            OC_User::setupBackends();
708
+        } else {
709
+            // Run upgrades in incognito mode
710
+            OC_User::setIncognitoMode(true);
711
+        }
712
+
713
+        self::registerCleanupHooks();
714
+        self::registerFilesystemHooks();
715
+        self::registerShareHooks();
716
+        self::registerEncryptionWrapper();
717
+        self::registerEncryptionHooks();
718
+        self::registerAccountHooks();
719
+        self::registerResourceCollectionHooks();
720
+
721
+        // Make sure that the application class is not loaded before the database is setup
722
+        if ($systemConfig->getValue("installed", false)) {
723
+            $settings = new \OC\Settings\Application();
724
+            $settings->register();
725
+        }
726
+
727
+        //make sure temporary files are cleaned up
728
+        $tmpManager = \OC::$server->getTempManager();
729
+        register_shutdown_function(array($tmpManager, 'clean'));
730
+        $lockProvider = \OC::$server->getLockingProvider();
731
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
732
+
733
+        // Check whether the sample configuration has been copied
734
+        if($systemConfig->getValue('copied_sample_config', false)) {
735
+            $l = \OC::$server->getL10N('lib');
736
+            OC_Template::printErrorPage(
737
+                $l->t('Sample configuration detected'),
738
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
739
+                503
740
+            );
741
+            return;
742
+        }
743
+
744
+        $request = \OC::$server->getRequest();
745
+        $host = $request->getInsecureServerHost();
746
+        /**
747
+         * if the host passed in headers isn't trusted
748
+         * FIXME: Should not be in here at all :see_no_evil:
749
+         */
750
+        if (!OC::$CLI
751
+            // overwritehost is always trusted, workaround to not have to make
752
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
753
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
754
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
755
+            && self::$server->getConfig()->getSystemValue('installed', false)
756
+        ) {
757
+            // Allow access to CSS resources
758
+            $isScssRequest = false;
759
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
760
+                $isScssRequest = true;
761
+            }
762
+
763
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
764
+                http_response_code(400);
765
+                header('Content-Type: application/json');
766
+                echo '{"error": "Trusted domain error.", "code": 15}';
767
+                exit();
768
+            }
769
+
770
+            if (!$isScssRequest) {
771
+                http_response_code(400);
772
+
773
+                \OC::$server->getLogger()->info(
774
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
775
+                    [
776
+                        'app' => 'core',
777
+                        'remoteAddress' => $request->getRemoteAddress(),
778
+                        'host' => $host,
779
+                    ]
780
+                );
781
+
782
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
783
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
784
+                $tmpl->printPage();
785
+
786
+                exit();
787
+            }
788
+        }
789
+        \OC::$server->getEventLogger()->end('boot');
790
+    }
791
+
792
+    /**
793
+     * register hooks for the cleanup of cache and bruteforce protection
794
+     */
795
+    public static function registerCleanupHooks() {
796
+        //don't try to do this before we are properly setup
797
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
798
+
799
+            // NOTE: This will be replaced to use OCP
800
+            $userSession = self::$server->getUserSession();
801
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
802
+                if (!defined('PHPUNIT_RUN')) {
803
+                    // reset brute force delay for this IP address and username
804
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
805
+                    $request = \OC::$server->getRequest();
806
+                    $throttler = \OC::$server->getBruteForceThrottler();
807
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
808
+                }
809
+
810
+                try {
811
+                    $cache = new \OC\Cache\File();
812
+                    $cache->gc();
813
+                } catch (\OC\ServerNotAvailableException $e) {
814
+                    // not a GC exception, pass it on
815
+                    throw $e;
816
+                } catch (\OC\ForbiddenException $e) {
817
+                    // filesystem blocked for this request, ignore
818
+                } catch (\Exception $e) {
819
+                    // a GC exception should not prevent users from using OC,
820
+                    // so log the exception
821
+                    \OC::$server->getLogger()->logException($e, [
822
+                        'message' => 'Exception when running cache gc.',
823
+                        'level' => ILogger::WARN,
824
+                        'app' => 'core',
825
+                    ]);
826
+                }
827
+            });
828
+        }
829
+    }
830
+
831
+    private static function registerEncryptionWrapper() {
832
+        $manager = self::$server->getEncryptionManager();
833
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
834
+    }
835
+
836
+    private static function registerEncryptionHooks() {
837
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
838
+        if ($enabled) {
839
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
840
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
841
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
842
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
843
+        }
844
+    }
845
+
846
+    private static function registerAccountHooks() {
847
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
848
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
849
+    }
850
+
851
+    private static function registerResourceCollectionHooks() {
852
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
853
+    }
854
+
855
+    /**
856
+     * register hooks for the filesystem
857
+     */
858
+    public static function registerFilesystemHooks() {
859
+        // Check for blacklisted files
860
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
861
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
862
+    }
863
+
864
+    /**
865
+     * register hooks for sharing
866
+     */
867
+    public static function registerShareHooks() {
868
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
869
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
870
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
871
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
872
+        }
873
+    }
874
+
875
+    protected static function registerAutoloaderCache() {
876
+        // The class loader takes an optional low-latency cache, which MUST be
877
+        // namespaced. The instanceid is used for namespacing, but might be
878
+        // unavailable at this point. Furthermore, it might not be possible to
879
+        // generate an instanceid via \OC_Util::getInstanceId() because the
880
+        // config file may not be writable. As such, we only register a class
881
+        // loader cache if instanceid is available without trying to create one.
882
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
883
+        if ($instanceId) {
884
+            try {
885
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
886
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
887
+            } catch (\Exception $ex) {
888
+            }
889
+        }
890
+    }
891
+
892
+    /**
893
+     * Handle the request
894
+     */
895
+    public static function handleRequest() {
896
+
897
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
898
+        $systemConfig = \OC::$server->getSystemConfig();
899
+
900
+        // Check if Nextcloud is installed or in maintenance (update) mode
901
+        if (!$systemConfig->getValue('installed', false)) {
902
+            \OC::$server->getSession()->clear();
903
+            $setupHelper = new OC\Setup(
904
+                $systemConfig,
905
+                \OC::$server->getIniWrapper(),
906
+                \OC::$server->getL10N('lib'),
907
+                \OC::$server->query(\OCP\Defaults::class),
908
+                \OC::$server->getLogger(),
909
+                \OC::$server->getSecureRandom(),
910
+                \OC::$server->query(\OC\Installer::class)
911
+            );
912
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
913
+            $controller->run($_POST);
914
+            exit();
915
+        }
916
+
917
+        $request = \OC::$server->getRequest();
918
+        $requestPath = $request->getRawPathInfo();
919
+        if ($requestPath === '/heartbeat') {
920
+            return;
921
+        }
922
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
923
+            self::checkMaintenanceMode();
924
+
925
+            if (\OCP\Util::needUpgrade()) {
926
+                if (function_exists('opcache_reset')) {
927
+                    opcache_reset();
928
+                }
929
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
930
+                    self::printUpgradePage($systemConfig);
931
+                    exit();
932
+                }
933
+            }
934
+        }
935
+
936
+        // emergency app disabling
937
+        if ($requestPath === '/disableapp'
938
+            && $request->getMethod() === 'POST'
939
+            && ((array)$request->getParam('appid')) !== ''
940
+        ) {
941
+            \OC_JSON::callCheck();
942
+            \OC_JSON::checkAdminUser();
943
+            $appIds = (array)$request->getParam('appid');
944
+            foreach($appIds as $appId) {
945
+                $appId = \OC_App::cleanAppId($appId);
946
+                \OC::$server->getAppManager()->disableApp($appId);
947
+            }
948
+            \OC_JSON::success();
949
+            exit();
950
+        }
951
+
952
+        // Always load authentication apps
953
+        OC_App::loadApps(['authentication']);
954
+
955
+        // Load minimum set of apps
956
+        if (!\OCP\Util::needUpgrade()
957
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
958
+            // For logged-in users: Load everything
959
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
960
+                OC_App::loadApps();
961
+            } else {
962
+                // For guests: Load only filesystem and logging
963
+                OC_App::loadApps(array('filesystem', 'logging'));
964
+                self::handleLogin($request);
965
+            }
966
+        }
967
+
968
+        if (!self::$CLI) {
969
+            try {
970
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
971
+                    OC_App::loadApps(array('filesystem', 'logging'));
972
+                    OC_App::loadApps();
973
+                }
974
+                OC_Util::setupFS();
975
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
976
+                return;
977
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
978
+                //header('HTTP/1.0 404 Not Found');
979
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
980
+                http_response_code(405);
981
+                return;
982
+            }
983
+        }
984
+
985
+        // Handle WebDAV
986
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
987
+            // not allowed any more to prevent people
988
+            // mounting this root directly.
989
+            // Users need to mount remote.php/webdav instead.
990
+            http_response_code(405);
991
+            return;
992
+        }
993
+
994
+        // Someone is logged in
995
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
996
+            OC_App::loadApps();
997
+            OC_User::setupBackends();
998
+            OC_Util::setupFS();
999
+            // FIXME
1000
+            // Redirect to default application
1001
+            OC_Util::redirectToDefaultPage();
1002
+        } else {
1003
+            // Not handled and not logged in
1004
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1005
+        }
1006
+    }
1007
+
1008
+    /**
1009
+     * Check login: apache auth, auth token, basic auth
1010
+     *
1011
+     * @param OCP\IRequest $request
1012
+     * @return boolean
1013
+     */
1014
+    static function handleLogin(OCP\IRequest $request) {
1015
+        $userSession = self::$server->getUserSession();
1016
+        if (OC_User::handleApacheAuth()) {
1017
+            return true;
1018
+        }
1019
+        if ($userSession->tryTokenLogin($request)) {
1020
+            return true;
1021
+        }
1022
+        if (isset($_COOKIE['nc_username'])
1023
+            && isset($_COOKIE['nc_token'])
1024
+            && isset($_COOKIE['nc_session_id'])
1025
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1026
+            return true;
1027
+        }
1028
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1029
+            return true;
1030
+        }
1031
+        return false;
1032
+    }
1033
+
1034
+    protected static function handleAuthHeaders() {
1035
+        //copy http auth headers for apache+php-fcgid work around
1036
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1037
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1038
+        }
1039
+
1040
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1041
+        $vars = array(
1042
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1043
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1044
+        );
1045
+        foreach ($vars as $var) {
1046
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1047
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1048
+                $_SERVER['PHP_AUTH_USER'] = $name;
1049
+                $_SERVER['PHP_AUTH_PW'] = $password;
1050
+                break;
1051
+            }
1052
+        }
1053
+    }
1054 1054
 }
1055 1055
 
1056 1056
 OC::init();
Please login to merge, or discard this patch.
lib/public/Collaboration/Resources/IManager.php 1 patch
Indentation   +78 added lines, -78 removed lines patch added patch discarded remove patch
@@ -29,93 +29,93 @@
 block discarded – undo
29 29
  */
30 30
 interface IManager extends IProvider {
31 31
 
32
-	/**
33
-	 * @param int $id
34
-	 * @return ICollection
35
-	 * @throws CollectionException when the collection could not be found
36
-	 * @since 16.0.0
37
-	 */
38
-	public function getCollection(int $id): ICollection;
32
+    /**
33
+     * @param int $id
34
+     * @return ICollection
35
+     * @throws CollectionException when the collection could not be found
36
+     * @since 16.0.0
37
+     */
38
+    public function getCollection(int $id): ICollection;
39 39
 
40
-	/**
41
-	 * @param int $id
42
-	 * @param IUser|null $user
43
-	 * @return ICollection
44
-	 * @throws CollectionException when the collection could not be found
45
-	 * @since 16.0.0
46
-	 */
47
-	public function getCollectionForUser(int $id, ?IUser $user): ICollection;
40
+    /**
41
+     * @param int $id
42
+     * @param IUser|null $user
43
+     * @return ICollection
44
+     * @throws CollectionException when the collection could not be found
45
+     * @since 16.0.0
46
+     */
47
+    public function getCollectionForUser(int $id, ?IUser $user): ICollection;
48 48
 
49
-	/**
50
-	 * @param string $name
51
-	 * @return ICollection
52
-	 * @since 16.0.0
53
-	 */
54
-	public function newCollection(string $name): ICollection;
49
+    /**
50
+     * @param string $name
51
+     * @return ICollection
52
+     * @since 16.0.0
53
+     */
54
+    public function newCollection(string $name): ICollection;
55 55
 
56
-	/**
57
-	 * Can a user/guest access the collection
58
-	 *
59
-	 * @param ICollection $collection
60
-	 * @param IUser|null $user
61
-	 * @return bool
62
-	 * @since 16.0.0
63
-	 */
64
-	public function canAccessCollection(ICollection $collection, ?IUser $user): bool;
56
+    /**
57
+     * Can a user/guest access the collection
58
+     *
59
+     * @param ICollection $collection
60
+     * @param IUser|null $user
61
+     * @return bool
62
+     * @since 16.0.0
63
+     */
64
+    public function canAccessCollection(ICollection $collection, ?IUser $user): bool;
65 65
 
66
-	/**
67
-	 * @param IUser|null $user
68
-	 * @since 16.0.0
69
-	 */
70
-	public function invalidateAccessCacheForUser(?IUser $user): void;
66
+    /**
67
+     * @param IUser|null $user
68
+     * @since 16.0.0
69
+     */
70
+    public function invalidateAccessCacheForUser(?IUser $user): void;
71 71
 
72
-	/**
73
-	 * @param IResource $resource
74
-	 * @since 16.0.0
75
-	 */
76
-	public function invalidateAccessCacheForResource(IResource $resource): void;
72
+    /**
73
+     * @param IResource $resource
74
+     * @since 16.0.0
75
+     */
76
+    public function invalidateAccessCacheForResource(IResource $resource): void;
77 77
 
78
-	/**
79
-	 * @param IResource $resource
80
-	 * @param IUser|null $user
81
-	 * @since 16.0.0
82
-	 */
83
-	public function invalidateAccessCacheForResourceByUser(IResource $resource, ?IUser $user): void;
78
+    /**
79
+     * @param IResource $resource
80
+     * @param IUser|null $user
81
+     * @since 16.0.0
82
+     */
83
+    public function invalidateAccessCacheForResourceByUser(IResource $resource, ?IUser $user): void;
84 84
 
85
-	/**
86
-	 * @param IProvider $provider
87
-	 * @since 16.0.0
88
-	 */
89
-	public function invalidateAccessCacheForProvider(IProvider $provider): void;
85
+    /**
86
+     * @param IProvider $provider
87
+     * @since 16.0.0
88
+     */
89
+    public function invalidateAccessCacheForProvider(IProvider $provider): void;
90 90
 
91
-	/**
92
-	 * @param IProvider $provider
93
-	 * @param IUser|null $user
94
-	 * @since 16.0.0
95
-	 */
96
-	public function invalidateAccessCacheForProviderByUser(IProvider $provider, ?IUser $user): void;
91
+    /**
92
+     * @param IProvider $provider
93
+     * @param IUser|null $user
94
+     * @since 16.0.0
95
+     */
96
+    public function invalidateAccessCacheForProviderByUser(IProvider $provider, ?IUser $user): void;
97 97
 
98
-	/**
99
-	 * @param string $type
100
-	 * @param string $id
101
-	 * @return IResource
102
-	 * @since 16.0.0
103
-	 */
104
-	public function createResource(string $type, string $id): IResource;
98
+    /**
99
+     * @param string $type
100
+     * @param string $id
101
+     * @return IResource
102
+     * @since 16.0.0
103
+     */
104
+    public function createResource(string $type, string $id): IResource;
105 105
 
106
-	/**
107
-	 * @param string $type
108
-	 * @param string $id
109
-	 * @param IUser|null $user
110
-	 * @return IResource
111
-	 * @throws ResourceException
112
-	 * @since 16.0.0
113
-	 */
114
-	public function getResourceForUser(string $type, string $id, ?IUser $user): IResource;
106
+    /**
107
+     * @param string $type
108
+     * @param string $id
109
+     * @param IUser|null $user
110
+     * @return IResource
111
+     * @throws ResourceException
112
+     * @since 16.0.0
113
+     */
114
+    public function getResourceForUser(string $type, string $id, ?IUser $user): IResource;
115 115
 
116
-	/**
117
-	 * @param string $provider
118
-	 * @since 16.0.0
119
-	 */
120
-	public function registerResourceProvider(string $provider): void;
116
+    /**
117
+     * @param string $provider
118
+     * @since 16.0.0
119
+     */
120
+    public function registerResourceProvider(string $provider): void;
121 121
 }
Please login to merge, or discard this patch.