Completed
Push — master ( f71791...a48bc5 )
by
unknown
25:33 queued 34s
created
apps/dav/appinfo/v2/publicremote.php 1 patch
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -53,27 +53,27 @@  discard block
 block discarded – undo
53 53
 
54 54
 // Backends
55 55
 $authBackend = new PublicAuth(
56
-	$request,
57
-	Server::get(IManager::class),
58
-	$session,
59
-	Server::get(IThrottler::class),
60
-	Server::get(LoggerInterface::class),
61
-	Server::get(IURLGenerator::class),
56
+    $request,
57
+    Server::get(IManager::class),
58
+    $session,
59
+    Server::get(IThrottler::class),
60
+    Server::get(LoggerInterface::class),
61
+    Server::get(IURLGenerator::class),
62 62
 );
63 63
 $authPlugin = new \Sabre\DAV\Auth\Plugin($authBackend);
64 64
 
65 65
 $l10nFactory = Server::get(IFactory::class);
66 66
 $serverFactory = new ServerFactory(
67
-	Server::get(IConfig::class),
68
-	Server::get(LoggerInterface::class),
69
-	Server::get(IDBConnection::class),
70
-	Server::get(IUserSession::class),
71
-	Server::get(IMountManager::class),
72
-	Server::get(ITagManager::class),
73
-	$request,
74
-	Server::get(IPreview::class),
75
-	$eventDispatcher,
76
-	$l10nFactory->get('dav'),
67
+    Server::get(IConfig::class),
68
+    Server::get(LoggerInterface::class),
69
+    Server::get(IDBConnection::class),
70
+    Server::get(IUserSession::class),
71
+    Server::get(IMountManager::class),
72
+    Server::get(ITagManager::class),
73
+    $request,
74
+    Server::get(IPreview::class),
75
+    $eventDispatcher,
76
+    $l10nFactory->get('dav'),
77 77
 );
78 78
 
79 79
 
@@ -82,61 +82,61 @@  discard block
 block discarded – undo
82 82
 
83 83
 /** @var string $baseuri defined in public.php */
84 84
 $server = $serverFactory->createServer(true, $baseuri, $requestUri, $authPlugin, function (\Sabre\DAV\Server $server) use ($authBackend, $linkCheckPlugin, $filesDropPlugin) {
85
-	// GET must be allowed for e.g. showing images and allowing Zip downloads
86
-	if ($server->httpRequest->getMethod() !== 'GET') {
87
-		// If this is *not* a GET request we only allow access to public DAV from AJAX or when Server2Server is allowed
88
-		$isAjax = in_array('XMLHttpRequest', explode(',', $_SERVER['HTTP_X_REQUESTED_WITH'] ?? ''));
89
-		$federatedShareProvider = Server::get(FederatedShareProvider::class);
90
-		if ($federatedShareProvider->isOutgoingServer2serverShareEnabled() === false && $isAjax === false) {
91
-			// this is what is thrown when trying to access a non-existing share
92
-			throw new NotAuthenticated();
93
-		}
94
-	}
95
-
96
-	$share = $authBackend->getShare();
97
-	$owner = $share->getShareOwner();
98
-	$isReadable = $share->getPermissions() & Constants::PERMISSION_READ;
99
-	$fileId = $share->getNodeId();
100
-
101
-	// FIXME: should not add storage wrappers outside of preSetup, need to find a better way
102
-	/** @psalm-suppress InternalMethod */
103
-	$previousLog = Filesystem::logWarningWhenAddingStorageWrapper(false);
104
-
105
-	/** @psalm-suppress MissingClosureParamType */
106
-	Filesystem::addStorageWrapper('sharePermissions', function ($mountPoint, $storage) use ($share) {
107
-		return new PermissionsMask(['storage' => $storage, 'mask' => $share->getPermissions() | Constants::PERMISSION_SHARE]);
108
-	});
109
-
110
-	/** @psalm-suppress MissingClosureParamType */
111
-	Filesystem::addStorageWrapper('shareOwner', function ($mountPoint, $storage) use ($share) {
112
-		return new PublicOwnerWrapper(['storage' => $storage, 'owner' => $share->getShareOwner()]);
113
-	});
114
-
115
-	// Ensure that also private shares have the `getShare` method
116
-	/** @psalm-suppress MissingClosureParamType */
117
-	Filesystem::addStorageWrapper('getShare', function ($mountPoint, $storage) use ($share) {
118
-		return new PublicShareWrapper(['storage' => $storage, 'share' => $share]);
119
-	}, 0);
120
-
121
-	/** @psalm-suppress InternalMethod */
122
-	Filesystem::logWarningWhenAddingStorageWrapper($previousLog);
123
-
124
-	$rootFolder = Server::get(IRootFolder::class);
125
-	$userFolder = $rootFolder->getUserFolder($owner);
126
-	$node = $userFolder->getFirstNodeById($fileId);
127
-	if (!$node) {
128
-		throw new NotFound();
129
-	}
130
-	$linkCheckPlugin->setFileInfo($node);
131
-
132
-	// If not readable (files_drop) enable the filesdrop plugin
133
-	if (!$isReadable) {
134
-		$filesDropPlugin->enable();
135
-	}
136
-	$filesDropPlugin->setShare($share);
137
-
138
-	$view = new View($node->getPath());
139
-	return $view;
85
+    // GET must be allowed for e.g. showing images and allowing Zip downloads
86
+    if ($server->httpRequest->getMethod() !== 'GET') {
87
+        // If this is *not* a GET request we only allow access to public DAV from AJAX or when Server2Server is allowed
88
+        $isAjax = in_array('XMLHttpRequest', explode(',', $_SERVER['HTTP_X_REQUESTED_WITH'] ?? ''));
89
+        $federatedShareProvider = Server::get(FederatedShareProvider::class);
90
+        if ($federatedShareProvider->isOutgoingServer2serverShareEnabled() === false && $isAjax === false) {
91
+            // this is what is thrown when trying to access a non-existing share
92
+            throw new NotAuthenticated();
93
+        }
94
+    }
95
+
96
+    $share = $authBackend->getShare();
97
+    $owner = $share->getShareOwner();
98
+    $isReadable = $share->getPermissions() & Constants::PERMISSION_READ;
99
+    $fileId = $share->getNodeId();
100
+
101
+    // FIXME: should not add storage wrappers outside of preSetup, need to find a better way
102
+    /** @psalm-suppress InternalMethod */
103
+    $previousLog = Filesystem::logWarningWhenAddingStorageWrapper(false);
104
+
105
+    /** @psalm-suppress MissingClosureParamType */
106
+    Filesystem::addStorageWrapper('sharePermissions', function ($mountPoint, $storage) use ($share) {
107
+        return new PermissionsMask(['storage' => $storage, 'mask' => $share->getPermissions() | Constants::PERMISSION_SHARE]);
108
+    });
109
+
110
+    /** @psalm-suppress MissingClosureParamType */
111
+    Filesystem::addStorageWrapper('shareOwner', function ($mountPoint, $storage) use ($share) {
112
+        return new PublicOwnerWrapper(['storage' => $storage, 'owner' => $share->getShareOwner()]);
113
+    });
114
+
115
+    // Ensure that also private shares have the `getShare` method
116
+    /** @psalm-suppress MissingClosureParamType */
117
+    Filesystem::addStorageWrapper('getShare', function ($mountPoint, $storage) use ($share) {
118
+        return new PublicShareWrapper(['storage' => $storage, 'share' => $share]);
119
+    }, 0);
120
+
121
+    /** @psalm-suppress InternalMethod */
122
+    Filesystem::logWarningWhenAddingStorageWrapper($previousLog);
123
+
124
+    $rootFolder = Server::get(IRootFolder::class);
125
+    $userFolder = $rootFolder->getUserFolder($owner);
126
+    $node = $userFolder->getFirstNodeById($fileId);
127
+    if (!$node) {
128
+        throw new NotFound();
129
+    }
130
+    $linkCheckPlugin->setFileInfo($node);
131
+
132
+    // If not readable (files_drop) enable the filesdrop plugin
133
+    if (!$isReadable) {
134
+        $filesDropPlugin->enable();
135
+    }
136
+    $filesDropPlugin->setShare($share);
137
+
138
+    $view = new View($node->getPath());
139
+    return $view;
140 140
 });
141 141
 
142 142
 $server->addPlugin($linkCheckPlugin);
Please login to merge, or discard this patch.
apps/dav/tests/unit/Connector/Sabre/PublicAuthTest.php 1 patch
Indentation   +365 added lines, -365 removed lines patch added patch discarded remove patch
@@ -27,379 +27,379 @@
 block discarded – undo
27 27
  */
28 28
 class PublicAuthTest extends \Test\TestCase {
29 29
 
30
-	private ISession&MockObject $session;
31
-	private IRequest&MockObject $request;
32
-	private IManager&MockObject $shareManager;
33
-	private PublicAuth $auth;
34
-	private IThrottler&MockObject $throttler;
35
-	private LoggerInterface&MockObject $logger;
36
-	private IURLGenerator&MockObject $urlGenerator;
37
-
38
-	private string $oldUser;
39
-
40
-	protected function setUp(): void {
41
-		parent::setUp();
42
-
43
-		$this->session = $this->createMock(ISession::class);
44
-		$this->request = $this->createMock(IRequest::class);
45
-		$this->shareManager = $this->createMock(IManager::class);
46
-		$this->throttler = $this->createMock(IThrottler::class);
47
-		$this->logger = $this->createMock(LoggerInterface::class);
48
-		$this->urlGenerator = $this->createMock(IURLGenerator::class);
49
-
50
-		$this->auth = new PublicAuth(
51
-			$this->request,
52
-			$this->shareManager,
53
-			$this->session,
54
-			$this->throttler,
55
-			$this->logger,
56
-			$this->urlGenerator,
57
-		);
58
-
59
-		// Store current user
60
-		$this->oldUser = \OC_User::getUser();
61
-	}
62
-
63
-	protected function tearDown(): void {
64
-		\OC_User::setIncognitoMode(false);
65
-
66
-		// Set old user
67
-		\OC_User::setUserId($this->oldUser);
68
-		\OC_Util::setupFS($this->oldUser);
69
-
70
-		parent::tearDown();
71
-	}
72
-
73
-	public function testGetToken(): void {
74
-		$this->request->method('getPathInfo')
75
-			->willReturn('/dav/files/GX9HSGQrGE');
76
-
77
-		$result = $this->invokePrivate($this->auth, 'getToken');
78
-
79
-		$this->assertSame('GX9HSGQrGE', $result);
80
-	}
81
-
82
-	public function testGetTokenInvalid(): void {
83
-		$this->request->method('getPathInfo')
84
-			->willReturn('/dav/files');
85
-
86
-		$this->expectException(\Sabre\DAV\Exception\NotFound::class);
87
-		$this->invokePrivate($this->auth, 'getToken');
88
-	}
89
-
90
-	public function testCheckTokenValidShare(): void {
91
-		$this->request->method('getPathInfo')
92
-			->willReturn('/dav/files/GX9HSGQrGE');
93
-
94
-		$share = $this->getMockBuilder(IShare::class)
95
-			->disableOriginalConstructor()
96
-			->getMock();
97
-		$share->method('getPassword')->willReturn(null);
98
-
99
-		$this->shareManager->expects($this->once())
100
-			->method('getShareByToken')
101
-			->with('GX9HSGQrGE')
102
-			->willReturn($share);
103
-
104
-		$result = $this->invokePrivate($this->auth, 'checkToken');
105
-		$this->assertSame([true, 'principals/GX9HSGQrGE'], $result);
106
-	}
107
-
108
-	public function testCheckTokenInvalidShare(): void {
109
-		$this->request->method('getPathInfo')
110
-			->willReturn('/dav/files/GX9HSGQrGE');
111
-
112
-		$this->shareManager
113
-			->expects($this->once())
114
-			->method('getShareByToken')
115
-			->with('GX9HSGQrGE')
116
-			->will($this->throwException(new ShareNotFound()));
117
-
118
-		$this->expectException(\Sabre\DAV\Exception\NotFound::class);
119
-		$this->invokePrivate($this->auth, 'checkToken');
120
-	}
121
-
122
-	public function testCheckTokenAlreadyAuthenticated(): void {
123
-		$this->request->method('getPathInfo')
124
-			->willReturn('/dav/files/GX9HSGQrGE');
125
-
126
-		$share = $this->getMockBuilder(IShare::class)
127
-			->disableOriginalConstructor()
128
-			->getMock();
129
-		$share->method('getShareType')->willReturn(42);
130
-
131
-		$this->shareManager->expects($this->once())
132
-			->method('getShareByToken')
133
-			->with('GX9HSGQrGE')
134
-			->willReturn($share);
135
-
136
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
137
-		$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
138
-
139
-		$result = $this->invokePrivate($this->auth, 'checkToken');
140
-		$this->assertSame([true, 'principals/GX9HSGQrGE'], $result);
141
-	}
142
-
143
-	public function testCheckTokenPasswordNotAuthenticated(): void {
144
-		$this->request->method('getPathInfo')
145
-			->willReturn('/dav/files/GX9HSGQrGE');
146
-
147
-		$share = $this->getMockBuilder(IShare::class)
148
-			->disableOriginalConstructor()
149
-			->getMock();
150
-		$share->method('getPassword')->willReturn('password');
151
-		$share->method('getShareType')->willReturn(42);
152
-
153
-		$this->shareManager->expects($this->once())
154
-			->method('getShareByToken')
155
-			->with('GX9HSGQrGE')
156
-			->willReturn($share);
30
+    private ISession&MockObject $session;
31
+    private IRequest&MockObject $request;
32
+    private IManager&MockObject $shareManager;
33
+    private PublicAuth $auth;
34
+    private IThrottler&MockObject $throttler;
35
+    private LoggerInterface&MockObject $logger;
36
+    private IURLGenerator&MockObject $urlGenerator;
37
+
38
+    private string $oldUser;
39
+
40
+    protected function setUp(): void {
41
+        parent::setUp();
42
+
43
+        $this->session = $this->createMock(ISession::class);
44
+        $this->request = $this->createMock(IRequest::class);
45
+        $this->shareManager = $this->createMock(IManager::class);
46
+        $this->throttler = $this->createMock(IThrottler::class);
47
+        $this->logger = $this->createMock(LoggerInterface::class);
48
+        $this->urlGenerator = $this->createMock(IURLGenerator::class);
49
+
50
+        $this->auth = new PublicAuth(
51
+            $this->request,
52
+            $this->shareManager,
53
+            $this->session,
54
+            $this->throttler,
55
+            $this->logger,
56
+            $this->urlGenerator,
57
+        );
58
+
59
+        // Store current user
60
+        $this->oldUser = \OC_User::getUser();
61
+    }
62
+
63
+    protected function tearDown(): void {
64
+        \OC_User::setIncognitoMode(false);
65
+
66
+        // Set old user
67
+        \OC_User::setUserId($this->oldUser);
68
+        \OC_Util::setupFS($this->oldUser);
69
+
70
+        parent::tearDown();
71
+    }
72
+
73
+    public function testGetToken(): void {
74
+        $this->request->method('getPathInfo')
75
+            ->willReturn('/dav/files/GX9HSGQrGE');
76
+
77
+        $result = $this->invokePrivate($this->auth, 'getToken');
78
+
79
+        $this->assertSame('GX9HSGQrGE', $result);
80
+    }
81
+
82
+    public function testGetTokenInvalid(): void {
83
+        $this->request->method('getPathInfo')
84
+            ->willReturn('/dav/files');
85
+
86
+        $this->expectException(\Sabre\DAV\Exception\NotFound::class);
87
+        $this->invokePrivate($this->auth, 'getToken');
88
+    }
89
+
90
+    public function testCheckTokenValidShare(): void {
91
+        $this->request->method('getPathInfo')
92
+            ->willReturn('/dav/files/GX9HSGQrGE');
93
+
94
+        $share = $this->getMockBuilder(IShare::class)
95
+            ->disableOriginalConstructor()
96
+            ->getMock();
97
+        $share->method('getPassword')->willReturn(null);
98
+
99
+        $this->shareManager->expects($this->once())
100
+            ->method('getShareByToken')
101
+            ->with('GX9HSGQrGE')
102
+            ->willReturn($share);
103
+
104
+        $result = $this->invokePrivate($this->auth, 'checkToken');
105
+        $this->assertSame([true, 'principals/GX9HSGQrGE'], $result);
106
+    }
107
+
108
+    public function testCheckTokenInvalidShare(): void {
109
+        $this->request->method('getPathInfo')
110
+            ->willReturn('/dav/files/GX9HSGQrGE');
111
+
112
+        $this->shareManager
113
+            ->expects($this->once())
114
+            ->method('getShareByToken')
115
+            ->with('GX9HSGQrGE')
116
+            ->will($this->throwException(new ShareNotFound()));
117
+
118
+        $this->expectException(\Sabre\DAV\Exception\NotFound::class);
119
+        $this->invokePrivate($this->auth, 'checkToken');
120
+    }
121
+
122
+    public function testCheckTokenAlreadyAuthenticated(): void {
123
+        $this->request->method('getPathInfo')
124
+            ->willReturn('/dav/files/GX9HSGQrGE');
125
+
126
+        $share = $this->getMockBuilder(IShare::class)
127
+            ->disableOriginalConstructor()
128
+            ->getMock();
129
+        $share->method('getShareType')->willReturn(42);
130
+
131
+        $this->shareManager->expects($this->once())
132
+            ->method('getShareByToken')
133
+            ->with('GX9HSGQrGE')
134
+            ->willReturn($share);
135
+
136
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
137
+        $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
138
+
139
+        $result = $this->invokePrivate($this->auth, 'checkToken');
140
+        $this->assertSame([true, 'principals/GX9HSGQrGE'], $result);
141
+    }
142
+
143
+    public function testCheckTokenPasswordNotAuthenticated(): void {
144
+        $this->request->method('getPathInfo')
145
+            ->willReturn('/dav/files/GX9HSGQrGE');
146
+
147
+        $share = $this->getMockBuilder(IShare::class)
148
+            ->disableOriginalConstructor()
149
+            ->getMock();
150
+        $share->method('getPassword')->willReturn('password');
151
+        $share->method('getShareType')->willReturn(42);
152
+
153
+        $this->shareManager->expects($this->once())
154
+            ->method('getShareByToken')
155
+            ->with('GX9HSGQrGE')
156
+            ->willReturn($share);
157 157
 
158
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(false);
158
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(false);
159 159
 
160
-		$this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class);
161
-		$this->invokePrivate($this->auth, 'checkToken');
162
-	}
160
+        $this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class);
161
+        $this->invokePrivate($this->auth, 'checkToken');
162
+    }
163 163
 
164
-	public function testCheckTokenPasswordAuthenticatedWrongShare(): void {
165
-		$this->request->method('getPathInfo')
166
-			->willReturn('/dav/files/GX9HSGQrGE');
164
+    public function testCheckTokenPasswordAuthenticatedWrongShare(): void {
165
+        $this->request->method('getPathInfo')
166
+            ->willReturn('/dav/files/GX9HSGQrGE');
167 167
 
168
-		$share = $this->getMockBuilder(IShare::class)
169
-			->disableOriginalConstructor()
170
-			->getMock();
171
-		$share->method('getPassword')->willReturn('password');
172
-		$share->method('getShareType')->willReturn(42);
173
-
174
-		$this->shareManager->expects($this->once())
175
-			->method('getShareByToken')
176
-			->with('GX9HSGQrGE')
177
-			->willReturn($share);
178
-
179
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(false);
180
-		$this->session->method('get')->with('public_link_authenticated')->willReturn('43');
181
-
182
-		$this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class);
183
-		$this->invokePrivate($this->auth, 'checkToken');
184
-	}
168
+        $share = $this->getMockBuilder(IShare::class)
169
+            ->disableOriginalConstructor()
170
+            ->getMock();
171
+        $share->method('getPassword')->willReturn('password');
172
+        $share->method('getShareType')->willReturn(42);
173
+
174
+        $this->shareManager->expects($this->once())
175
+            ->method('getShareByToken')
176
+            ->with('GX9HSGQrGE')
177
+            ->willReturn($share);
178
+
179
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(false);
180
+        $this->session->method('get')->with('public_link_authenticated')->willReturn('43');
181
+
182
+        $this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class);
183
+        $this->invokePrivate($this->auth, 'checkToken');
184
+    }
185 185
 
186
-	public function testNoShare(): void {
187
-		$this->request->method('getPathInfo')
188
-			->willReturn('/dav/files/GX9HSGQrGE');
186
+    public function testNoShare(): void {
187
+        $this->request->method('getPathInfo')
188
+            ->willReturn('/dav/files/GX9HSGQrGE');
189 189
 
190
-		$this->shareManager->expects($this->once())
191
-			->method('getShareByToken')
192
-			->with('GX9HSGQrGE')
193
-			->willThrowException(new ShareNotFound());
194
-
195
-		$result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
196
-
197
-		$this->assertFalse($result);
198
-	}
199
-
200
-	public function testShareNoPassword(): void {
201
-		$this->request->method('getPathInfo')
202
-			->willReturn('/dav/files/GX9HSGQrGE');
203
-
204
-		$share = $this->getMockBuilder(IShare::class)
205
-			->disableOriginalConstructor()
206
-			->getMock();
207
-		$share->method('getPassword')->willReturn(null);
208
-
209
-		$this->shareManager->expects($this->once())
210
-			->method('getShareByToken')
211
-			->with('GX9HSGQrGE')
212
-			->willReturn($share);
213
-
214
-		$result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
190
+        $this->shareManager->expects($this->once())
191
+            ->method('getShareByToken')
192
+            ->with('GX9HSGQrGE')
193
+            ->willThrowException(new ShareNotFound());
194
+
195
+        $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
196
+
197
+        $this->assertFalse($result);
198
+    }
199
+
200
+    public function testShareNoPassword(): void {
201
+        $this->request->method('getPathInfo')
202
+            ->willReturn('/dav/files/GX9HSGQrGE');
203
+
204
+        $share = $this->getMockBuilder(IShare::class)
205
+            ->disableOriginalConstructor()
206
+            ->getMock();
207
+        $share->method('getPassword')->willReturn(null);
208
+
209
+        $this->shareManager->expects($this->once())
210
+            ->method('getShareByToken')
211
+            ->with('GX9HSGQrGE')
212
+            ->willReturn($share);
213
+
214
+        $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
215 215
 
216
-		$this->assertTrue($result);
217
-	}
218
-
219
-	public function testSharePasswordFancyShareType(): void {
220
-		$this->request->method('getPathInfo')
221
-			->willReturn('/dav/files/GX9HSGQrGE');
222
-
223
-		$share = $this->getMockBuilder(IShare::class)
224
-			->disableOriginalConstructor()
225
-			->getMock();
226
-		$share->method('getPassword')->willReturn('password');
227
-		$share->method('getShareType')->willReturn(42);
228
-
229
-		$this->shareManager->expects($this->once())
230
-			->method('getShareByToken')
231
-			->with('GX9HSGQrGE')
232
-			->willReturn($share);
233
-
234
-		$result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
235
-
236
-		$this->assertFalse($result);
237
-	}
238
-
239
-
240
-	public function testSharePasswordRemote(): void {
241
-		$this->request->method('getPathInfo')
242
-			->willReturn('/dav/files/GX9HSGQrGE');
243
-
244
-		$share = $this->getMockBuilder(IShare::class)
245
-			->disableOriginalConstructor()
246
-			->getMock();
247
-		$share->method('getPassword')->willReturn('password');
248
-		$share->method('getShareType')->willReturn(IShare::TYPE_REMOTE);
249
-
250
-		$this->shareManager->expects($this->once())
251
-			->method('getShareByToken')
252
-			->with('GX9HSGQrGE')
253
-			->willReturn($share);
254
-
255
-		$result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
256
-
257
-		$this->assertTrue($result);
258
-	}
259
-
260
-	public function testSharePasswordLinkValidPassword(): void {
261
-		$this->request->method('getPathInfo')
262
-			->willReturn('/dav/files/GX9HSGQrGE');
263
-
264
-		$share = $this->getMockBuilder(IShare::class)
265
-			->disableOriginalConstructor()
266
-			->getMock();
267
-		$share->method('getPassword')->willReturn('password');
268
-		$share->method('getShareType')->willReturn(IShare::TYPE_LINK);
269
-
270
-		$this->shareManager->expects($this->once())
271
-			->method('getShareByToken')
272
-			->with('GX9HSGQrGE')
273
-			->willReturn($share);
216
+        $this->assertTrue($result);
217
+    }
218
+
219
+    public function testSharePasswordFancyShareType(): void {
220
+        $this->request->method('getPathInfo')
221
+            ->willReturn('/dav/files/GX9HSGQrGE');
222
+
223
+        $share = $this->getMockBuilder(IShare::class)
224
+            ->disableOriginalConstructor()
225
+            ->getMock();
226
+        $share->method('getPassword')->willReturn('password');
227
+        $share->method('getShareType')->willReturn(42);
228
+
229
+        $this->shareManager->expects($this->once())
230
+            ->method('getShareByToken')
231
+            ->with('GX9HSGQrGE')
232
+            ->willReturn($share);
233
+
234
+        $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
235
+
236
+        $this->assertFalse($result);
237
+    }
238
+
239
+
240
+    public function testSharePasswordRemote(): void {
241
+        $this->request->method('getPathInfo')
242
+            ->willReturn('/dav/files/GX9HSGQrGE');
243
+
244
+        $share = $this->getMockBuilder(IShare::class)
245
+            ->disableOriginalConstructor()
246
+            ->getMock();
247
+        $share->method('getPassword')->willReturn('password');
248
+        $share->method('getShareType')->willReturn(IShare::TYPE_REMOTE);
249
+
250
+        $this->shareManager->expects($this->once())
251
+            ->method('getShareByToken')
252
+            ->with('GX9HSGQrGE')
253
+            ->willReturn($share);
254
+
255
+        $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
256
+
257
+        $this->assertTrue($result);
258
+    }
259
+
260
+    public function testSharePasswordLinkValidPassword(): void {
261
+        $this->request->method('getPathInfo')
262
+            ->willReturn('/dav/files/GX9HSGQrGE');
263
+
264
+        $share = $this->getMockBuilder(IShare::class)
265
+            ->disableOriginalConstructor()
266
+            ->getMock();
267
+        $share->method('getPassword')->willReturn('password');
268
+        $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
269
+
270
+        $this->shareManager->expects($this->once())
271
+            ->method('getShareByToken')
272
+            ->with('GX9HSGQrGE')
273
+            ->willReturn($share);
274 274
 
275
-		$this->shareManager->expects($this->once())
276
-			->method('checkPassword')->with(
277
-				$this->equalTo($share),
278
-				$this->equalTo('password')
279
-			)->willReturn(true);
275
+        $this->shareManager->expects($this->once())
276
+            ->method('checkPassword')->with(
277
+                $this->equalTo($share),
278
+                $this->equalTo('password')
279
+            )->willReturn(true);
280 280
 
281
-		$result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
282
-
283
-		$this->assertTrue($result);
284
-	}
281
+        $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
282
+
283
+        $this->assertTrue($result);
284
+    }
285 285
 
286
-	public function testSharePasswordMailValidPassword(): void {
287
-		$this->request->method('getPathInfo')
288
-			->willReturn('/dav/files/GX9HSGQrGE');
289
-
290
-		$share = $this->getMockBuilder(IShare::class)
291
-			->disableOriginalConstructor()
292
-			->getMock();
293
-		$share->method('getPassword')->willReturn('password');
294
-		$share->method('getShareType')->willReturn(IShare::TYPE_EMAIL);
295
-
296
-		$this->shareManager->expects($this->once())
297
-			->method('getShareByToken')
298
-			->with('GX9HSGQrGE')
299
-			->willReturn($share);
300
-
301
-		$this->shareManager->expects($this->once())
302
-			->method('checkPassword')->with(
303
-				$this->equalTo($share),
304
-				$this->equalTo('password')
305
-			)->willReturn(true);
306
-
307
-		$result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
308
-
309
-		$this->assertTrue($result);
310
-	}
311
-
312
-	public function testInvalidSharePasswordLinkValidSession(): void {
313
-		$this->request->method('getPathInfo')
314
-			->willReturn('/dav/files/GX9HSGQrGE');
315
-
316
-		$share = $this->getMockBuilder(IShare::class)
317
-			->disableOriginalConstructor()
318
-			->getMock();
319
-		$share->method('getPassword')->willReturn('password');
320
-		$share->method('getShareType')->willReturn(IShare::TYPE_LINK);
321
-		$share->method('getId')->willReturn('42');
322
-
323
-		$this->shareManager->expects($this->once())
324
-			->method('getShareByToken')
325
-			->with('GX9HSGQrGE')
326
-			->willReturn($share);
327
-
328
-		$this->shareManager->expects($this->once())
329
-			->method('checkPassword')
330
-			->with(
331
-				$this->equalTo($share),
332
-				$this->equalTo('password')
333
-			)->willReturn(false);
334
-
335
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
336
-		$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
337
-
338
-		$result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
339
-
340
-		$this->assertTrue($result);
341
-	}
342
-
343
-	public function testSharePasswordLinkInvalidSession(): void {
344
-		$this->request->method('getPathInfo')
345
-			->willReturn('/dav/files/GX9HSGQrGE');
346
-
347
-		$share = $this->getMockBuilder(IShare::class)
348
-			->disableOriginalConstructor()
349
-			->getMock();
350
-		$share->method('getPassword')->willReturn('password');
351
-		$share->method('getShareType')->willReturn(IShare::TYPE_LINK);
352
-		$share->method('getId')->willReturn('42');
353
-
354
-		$this->shareManager->expects($this->once())
355
-			->method('getShareByToken')
356
-			->with('GX9HSGQrGE')
357
-			->willReturn($share);
358
-
359
-		$this->shareManager->expects($this->once())
360
-			->method('checkPassword')
361
-			->with(
362
-				$this->equalTo($share),
363
-				$this->equalTo('password')
364
-			)->willReturn(false);
365
-
366
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
367
-		$this->session->method('get')->with('public_link_authenticated')->willReturn('43');
368
-
369
-		$result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
370
-
371
-		$this->assertFalse($result);
372
-	}
373
-
374
-
375
-	public function testSharePasswordMailInvalidSession(): void {
376
-		$this->request->method('getPathInfo')
377
-			->willReturn('/dav/files/GX9HSGQrGE');
378
-
379
-		$share = $this->getMockBuilder(IShare::class)
380
-			->disableOriginalConstructor()
381
-			->getMock();
382
-		$share->method('getPassword')->willReturn('password');
383
-		$share->method('getShareType')->willReturn(IShare::TYPE_EMAIL);
384
-		$share->method('getId')->willReturn('42');
385
-
386
-		$this->shareManager->expects($this->once())
387
-			->method('getShareByToken')
388
-			->with('GX9HSGQrGE')
389
-			->willReturn($share);
390
-
391
-		$this->shareManager->expects($this->once())
392
-			->method('checkPassword')
393
-			->with(
394
-				$this->equalTo($share),
395
-				$this->equalTo('password')
396
-			)->willReturn(false);
397
-
398
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
399
-		$this->session->method('get')->with('public_link_authenticated')->willReturn('43');
400
-
401
-		$result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
402
-
403
-		$this->assertFalse($result);
404
-	}
286
+    public function testSharePasswordMailValidPassword(): void {
287
+        $this->request->method('getPathInfo')
288
+            ->willReturn('/dav/files/GX9HSGQrGE');
289
+
290
+        $share = $this->getMockBuilder(IShare::class)
291
+            ->disableOriginalConstructor()
292
+            ->getMock();
293
+        $share->method('getPassword')->willReturn('password');
294
+        $share->method('getShareType')->willReturn(IShare::TYPE_EMAIL);
295
+
296
+        $this->shareManager->expects($this->once())
297
+            ->method('getShareByToken')
298
+            ->with('GX9HSGQrGE')
299
+            ->willReturn($share);
300
+
301
+        $this->shareManager->expects($this->once())
302
+            ->method('checkPassword')->with(
303
+                $this->equalTo($share),
304
+                $this->equalTo('password')
305
+            )->willReturn(true);
306
+
307
+        $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
308
+
309
+        $this->assertTrue($result);
310
+    }
311
+
312
+    public function testInvalidSharePasswordLinkValidSession(): void {
313
+        $this->request->method('getPathInfo')
314
+            ->willReturn('/dav/files/GX9HSGQrGE');
315
+
316
+        $share = $this->getMockBuilder(IShare::class)
317
+            ->disableOriginalConstructor()
318
+            ->getMock();
319
+        $share->method('getPassword')->willReturn('password');
320
+        $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
321
+        $share->method('getId')->willReturn('42');
322
+
323
+        $this->shareManager->expects($this->once())
324
+            ->method('getShareByToken')
325
+            ->with('GX9HSGQrGE')
326
+            ->willReturn($share);
327
+
328
+        $this->shareManager->expects($this->once())
329
+            ->method('checkPassword')
330
+            ->with(
331
+                $this->equalTo($share),
332
+                $this->equalTo('password')
333
+            )->willReturn(false);
334
+
335
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
336
+        $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
337
+
338
+        $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
339
+
340
+        $this->assertTrue($result);
341
+    }
342
+
343
+    public function testSharePasswordLinkInvalidSession(): void {
344
+        $this->request->method('getPathInfo')
345
+            ->willReturn('/dav/files/GX9HSGQrGE');
346
+
347
+        $share = $this->getMockBuilder(IShare::class)
348
+            ->disableOriginalConstructor()
349
+            ->getMock();
350
+        $share->method('getPassword')->willReturn('password');
351
+        $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
352
+        $share->method('getId')->willReturn('42');
353
+
354
+        $this->shareManager->expects($this->once())
355
+            ->method('getShareByToken')
356
+            ->with('GX9HSGQrGE')
357
+            ->willReturn($share);
358
+
359
+        $this->shareManager->expects($this->once())
360
+            ->method('checkPassword')
361
+            ->with(
362
+                $this->equalTo($share),
363
+                $this->equalTo('password')
364
+            )->willReturn(false);
365
+
366
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
367
+        $this->session->method('get')->with('public_link_authenticated')->willReturn('43');
368
+
369
+        $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
370
+
371
+        $this->assertFalse($result);
372
+    }
373
+
374
+
375
+    public function testSharePasswordMailInvalidSession(): void {
376
+        $this->request->method('getPathInfo')
377
+            ->willReturn('/dav/files/GX9HSGQrGE');
378
+
379
+        $share = $this->getMockBuilder(IShare::class)
380
+            ->disableOriginalConstructor()
381
+            ->getMock();
382
+        $share->method('getPassword')->willReturn('password');
383
+        $share->method('getShareType')->willReturn(IShare::TYPE_EMAIL);
384
+        $share->method('getId')->willReturn('42');
385
+
386
+        $this->shareManager->expects($this->once())
387
+            ->method('getShareByToken')
388
+            ->with('GX9HSGQrGE')
389
+            ->willReturn($share);
390
+
391
+        $this->shareManager->expects($this->once())
392
+            ->method('checkPassword')
393
+            ->with(
394
+                $this->equalTo($share),
395
+                $this->equalTo('password')
396
+            )->willReturn(false);
397
+
398
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
399
+        $this->session->method('get')->with('public_link_authenticated')->willReturn('43');
400
+
401
+        $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']);
402
+
403
+        $this->assertFalse($result);
404
+    }
405 405
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/PublicAuth.php 2 patches
Indentation   +188 added lines, -188 removed lines patch added patch discarded remove patch
@@ -36,192 +36,192 @@
 block discarded – undo
36 36
  * @package OCA\DAV\Connector
37 37
  */
38 38
 class PublicAuth extends AbstractBasic {
39
-	private const BRUTEFORCE_ACTION = 'public_dav_auth';
40
-	public const DAV_AUTHENTICATED = 'public_link_authenticated';
41
-
42
-	private ?IShare $share = null;
43
-
44
-	public function __construct(
45
-		private IRequest $request,
46
-		private IManager $shareManager,
47
-		private ISession $session,
48
-		private IThrottler $throttler,
49
-		private LoggerInterface $logger,
50
-		private IURLGenerator $urlGenerator,
51
-	) {
52
-		// setup realm
53
-		$defaults = new Defaults();
54
-		$this->realm = $defaults->getName();
55
-	}
56
-
57
-	/**
58
-	 * @throws NotAuthenticated
59
-	 * @throws MaxDelayReached
60
-	 * @throws ServiceUnavailable
61
-	 */
62
-	public function check(RequestInterface $request, ResponseInterface $response): array {
63
-		try {
64
-			$this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), self::BRUTEFORCE_ACTION);
65
-
66
-			if (count($_COOKIE) > 0 && !$this->request->passesStrictCookieCheck() && $this->getShare()->getPassword() !== null) {
67
-				throw new PreconditionFailed('Strict cookie check failed');
68
-			}
69
-
70
-			$auth = new HTTP\Auth\Basic(
71
-				$this->realm,
72
-				$request,
73
-				$response
74
-			);
75
-
76
-			$userpass = $auth->getCredentials();
77
-			// If authentication provided, checking its validity
78
-			if ($userpass && !$this->validateUserPass($userpass[0], $userpass[1])) {
79
-				return [false, 'Username or password was incorrect'];
80
-			}
81
-
82
-			return $this->checkToken();
83
-		} catch (NotAuthenticated|MaxDelayReached $e) {
84
-			$this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
85
-			throw $e;
86
-		} catch (PreconditionFailed $e) {
87
-			$response->setHeader(
88
-				'Location',
89
-				$this->urlGenerator->linkToRoute(
90
-					'files_sharing.share.showShare',
91
-					[ 'token' => $this->getToken() ],
92
-				),
93
-			);
94
-			throw $e;
95
-		} catch (\Exception $e) {
96
-			$class = get_class($e);
97
-			$msg = $e->getMessage();
98
-			$this->logger->error($e->getMessage(), ['exception' => $e]);
99
-			throw new ServiceUnavailable("$class: $msg");
100
-		}
101
-	}
102
-
103
-	/**
104
-	 * Extract token from request url
105
-	 * @throws NotFound
106
-	 */
107
-	private function getToken(): string {
108
-		$path = $this->request->getPathInfo() ?: '';
109
-		// ['', 'dav', 'files', 'token']
110
-		$splittedPath = explode('/', $path);
111
-
112
-		if (count($splittedPath) < 4 || $splittedPath[3] === '') {
113
-			throw new NotFound();
114
-		}
115
-
116
-		return $splittedPath[3];
117
-	}
118
-
119
-	/**
120
-	 * Check token validity
121
-	 *
122
-	 * @throws NotFound
123
-	 * @throws NotAuthenticated
124
-	 */
125
-	private function checkToken(): array {
126
-		$token = $this->getToken();
127
-
128
-		try {
129
-			/** @var IShare $share */
130
-			$share = $this->shareManager->getShareByToken($token);
131
-		} catch (ShareNotFound $e) {
132
-			$this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
133
-			throw new NotFound();
134
-		}
135
-
136
-		$this->share = $share;
137
-		\OC_User::setIncognitoMode(true);
138
-
139
-		// If already authenticated
140
-		if ($this->session->exists(self::DAV_AUTHENTICATED)
141
-			&& $this->session->get(self::DAV_AUTHENTICATED) === $share->getId()) {
142
-			return [true, $this->principalPrefix . $token];
143
-		}
144
-
145
-		// If the share is protected but user is not authenticated
146
-		if ($share->getPassword() !== null) {
147
-			$this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
148
-			throw new NotAuthenticated();
149
-		}
150
-
151
-		return [true, $this->principalPrefix . $token];
152
-	}
153
-
154
-	/**
155
-	 * Validates a username and password
156
-	 *
157
-	 * This method should return true or false depending on if login
158
-	 * succeeded.
159
-	 *
160
-	 * @param string $username
161
-	 * @param string $password
162
-	 *
163
-	 * @return bool
164
-	 * @throws NotAuthenticated
165
-	 */
166
-	protected function validateUserPass($username, $password) {
167
-		$this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), self::BRUTEFORCE_ACTION);
168
-
169
-		try {
170
-			$share = $this->getShare();
171
-		} catch (ShareNotFound $e) {
172
-			$this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
173
-			return false;
174
-		}
175
-
176
-		\OC_User::setIncognitoMode(true);
177
-
178
-		// check if the share is password protected
179
-		if ($share->getPassword() !== null) {
180
-			if ($share->getShareType() === IShare::TYPE_LINK
181
-				|| $share->getShareType() === IShare::TYPE_EMAIL
182
-				|| $share->getShareType() === IShare::TYPE_CIRCLE) {
183
-				if ($this->shareManager->checkPassword($share, $password)) {
184
-					// If not set, set authenticated session cookie
185
-					if (!$this->session->exists(self::DAV_AUTHENTICATED)
186
-						|| $this->session->get(self::DAV_AUTHENTICATED) !== $share->getId()) {
187
-						$this->session->set(self::DAV_AUTHENTICATED, $share->getId());
188
-					}
189
-					return true;
190
-				}
191
-
192
-				if ($this->session->exists(PublicAuth::DAV_AUTHENTICATED)
193
-					&& $this->session->get(PublicAuth::DAV_AUTHENTICATED) === $share->getId()) {
194
-					return true;
195
-				}
196
-
197
-				if (in_array('XMLHttpRequest', explode(',', $this->request->getHeader('X-Requested-With')))) {
198
-					// do not re-authenticate over ajax, use dummy auth name to prevent browser popup
199
-					http_response_code(401);
200
-					header('WWW-Authenticate: DummyBasic realm="' . $this->realm . '"');
201
-					throw new NotAuthenticated('Cannot authenticate over ajax calls');
202
-				}
203
-
204
-				$this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
205
-				return false;
206
-			} elseif ($share->getShareType() === IShare::TYPE_REMOTE) {
207
-				return true;
208
-			}
209
-
210
-			$this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
211
-			return false;
212
-		}
213
-
214
-		return true;
215
-	}
216
-
217
-	public function getShare(): IShare {
218
-		$token = $this->getToken();
219
-
220
-		if ($this->share === null) {
221
-			$share = $this->shareManager->getShareByToken($token);
222
-			$this->share = $share;
223
-		}
224
-
225
-		return $this->share;
226
-	}
39
+    private const BRUTEFORCE_ACTION = 'public_dav_auth';
40
+    public const DAV_AUTHENTICATED = 'public_link_authenticated';
41
+
42
+    private ?IShare $share = null;
43
+
44
+    public function __construct(
45
+        private IRequest $request,
46
+        private IManager $shareManager,
47
+        private ISession $session,
48
+        private IThrottler $throttler,
49
+        private LoggerInterface $logger,
50
+        private IURLGenerator $urlGenerator,
51
+    ) {
52
+        // setup realm
53
+        $defaults = new Defaults();
54
+        $this->realm = $defaults->getName();
55
+    }
56
+
57
+    /**
58
+     * @throws NotAuthenticated
59
+     * @throws MaxDelayReached
60
+     * @throws ServiceUnavailable
61
+     */
62
+    public function check(RequestInterface $request, ResponseInterface $response): array {
63
+        try {
64
+            $this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), self::BRUTEFORCE_ACTION);
65
+
66
+            if (count($_COOKIE) > 0 && !$this->request->passesStrictCookieCheck() && $this->getShare()->getPassword() !== null) {
67
+                throw new PreconditionFailed('Strict cookie check failed');
68
+            }
69
+
70
+            $auth = new HTTP\Auth\Basic(
71
+                $this->realm,
72
+                $request,
73
+                $response
74
+            );
75
+
76
+            $userpass = $auth->getCredentials();
77
+            // If authentication provided, checking its validity
78
+            if ($userpass && !$this->validateUserPass($userpass[0], $userpass[1])) {
79
+                return [false, 'Username or password was incorrect'];
80
+            }
81
+
82
+            return $this->checkToken();
83
+        } catch (NotAuthenticated|MaxDelayReached $e) {
84
+            $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
85
+            throw $e;
86
+        } catch (PreconditionFailed $e) {
87
+            $response->setHeader(
88
+                'Location',
89
+                $this->urlGenerator->linkToRoute(
90
+                    'files_sharing.share.showShare',
91
+                    [ 'token' => $this->getToken() ],
92
+                ),
93
+            );
94
+            throw $e;
95
+        } catch (\Exception $e) {
96
+            $class = get_class($e);
97
+            $msg = $e->getMessage();
98
+            $this->logger->error($e->getMessage(), ['exception' => $e]);
99
+            throw new ServiceUnavailable("$class: $msg");
100
+        }
101
+    }
102
+
103
+    /**
104
+     * Extract token from request url
105
+     * @throws NotFound
106
+     */
107
+    private function getToken(): string {
108
+        $path = $this->request->getPathInfo() ?: '';
109
+        // ['', 'dav', 'files', 'token']
110
+        $splittedPath = explode('/', $path);
111
+
112
+        if (count($splittedPath) < 4 || $splittedPath[3] === '') {
113
+            throw new NotFound();
114
+        }
115
+
116
+        return $splittedPath[3];
117
+    }
118
+
119
+    /**
120
+     * Check token validity
121
+     *
122
+     * @throws NotFound
123
+     * @throws NotAuthenticated
124
+     */
125
+    private function checkToken(): array {
126
+        $token = $this->getToken();
127
+
128
+        try {
129
+            /** @var IShare $share */
130
+            $share = $this->shareManager->getShareByToken($token);
131
+        } catch (ShareNotFound $e) {
132
+            $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
133
+            throw new NotFound();
134
+        }
135
+
136
+        $this->share = $share;
137
+        \OC_User::setIncognitoMode(true);
138
+
139
+        // If already authenticated
140
+        if ($this->session->exists(self::DAV_AUTHENTICATED)
141
+            && $this->session->get(self::DAV_AUTHENTICATED) === $share->getId()) {
142
+            return [true, $this->principalPrefix . $token];
143
+        }
144
+
145
+        // If the share is protected but user is not authenticated
146
+        if ($share->getPassword() !== null) {
147
+            $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
148
+            throw new NotAuthenticated();
149
+        }
150
+
151
+        return [true, $this->principalPrefix . $token];
152
+    }
153
+
154
+    /**
155
+     * Validates a username and password
156
+     *
157
+     * This method should return true or false depending on if login
158
+     * succeeded.
159
+     *
160
+     * @param string $username
161
+     * @param string $password
162
+     *
163
+     * @return bool
164
+     * @throws NotAuthenticated
165
+     */
166
+    protected function validateUserPass($username, $password) {
167
+        $this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), self::BRUTEFORCE_ACTION);
168
+
169
+        try {
170
+            $share = $this->getShare();
171
+        } catch (ShareNotFound $e) {
172
+            $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
173
+            return false;
174
+        }
175
+
176
+        \OC_User::setIncognitoMode(true);
177
+
178
+        // check if the share is password protected
179
+        if ($share->getPassword() !== null) {
180
+            if ($share->getShareType() === IShare::TYPE_LINK
181
+                || $share->getShareType() === IShare::TYPE_EMAIL
182
+                || $share->getShareType() === IShare::TYPE_CIRCLE) {
183
+                if ($this->shareManager->checkPassword($share, $password)) {
184
+                    // If not set, set authenticated session cookie
185
+                    if (!$this->session->exists(self::DAV_AUTHENTICATED)
186
+                        || $this->session->get(self::DAV_AUTHENTICATED) !== $share->getId()) {
187
+                        $this->session->set(self::DAV_AUTHENTICATED, $share->getId());
188
+                    }
189
+                    return true;
190
+                }
191
+
192
+                if ($this->session->exists(PublicAuth::DAV_AUTHENTICATED)
193
+                    && $this->session->get(PublicAuth::DAV_AUTHENTICATED) === $share->getId()) {
194
+                    return true;
195
+                }
196
+
197
+                if (in_array('XMLHttpRequest', explode(',', $this->request->getHeader('X-Requested-With')))) {
198
+                    // do not re-authenticate over ajax, use dummy auth name to prevent browser popup
199
+                    http_response_code(401);
200
+                    header('WWW-Authenticate: DummyBasic realm="' . $this->realm . '"');
201
+                    throw new NotAuthenticated('Cannot authenticate over ajax calls');
202
+                }
203
+
204
+                $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
205
+                return false;
206
+            } elseif ($share->getShareType() === IShare::TYPE_REMOTE) {
207
+                return true;
208
+            }
209
+
210
+            $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
211
+            return false;
212
+        }
213
+
214
+        return true;
215
+    }
216
+
217
+    public function getShare(): IShare {
218
+        $token = $this->getToken();
219
+
220
+        if ($this->share === null) {
221
+            $share = $this->shareManager->getShareByToken($token);
222
+            $this->share = $share;
223
+        }
224
+
225
+        return $this->share;
226
+    }
227 227
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 			}
81 81
 
82 82
 			return $this->checkToken();
83
-		} catch (NotAuthenticated|MaxDelayReached $e) {
83
+		} catch (NotAuthenticated | MaxDelayReached $e) {
84 84
 			$this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
85 85
 			throw $e;
86 86
 		} catch (PreconditionFailed $e) {
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 				'Location',
89 89
 				$this->urlGenerator->linkToRoute(
90 90
 					'files_sharing.share.showShare',
91
-					[ 'token' => $this->getToken() ],
91
+					['token' => $this->getToken()],
92 92
 				),
93 93
 			);
94 94
 			throw $e;
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 		// If already authenticated
140 140
 		if ($this->session->exists(self::DAV_AUTHENTICATED)
141 141
 			&& $this->session->get(self::DAV_AUTHENTICATED) === $share->getId()) {
142
-			return [true, $this->principalPrefix . $token];
142
+			return [true, $this->principalPrefix.$token];
143 143
 		}
144 144
 
145 145
 		// If the share is protected but user is not authenticated
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 			throw new NotAuthenticated();
149 149
 		}
150 150
 
151
-		return [true, $this->principalPrefix . $token];
151
+		return [true, $this->principalPrefix.$token];
152 152
 	}
153 153
 
154 154
 	/**
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 				if (in_array('XMLHttpRequest', explode(',', $this->request->getHeader('X-Requested-With')))) {
198 198
 					// do not re-authenticate over ajax, use dummy auth name to prevent browser popup
199 199
 					http_response_code(401);
200
-					header('WWW-Authenticate: DummyBasic realm="' . $this->realm . '"');
200
+					header('WWW-Authenticate: DummyBasic realm="'.$this->realm.'"');
201 201
 					throw new NotAuthenticated('Cannot authenticate over ajax calls');
202 202
 				}
203 203
 
Please login to merge, or discard this patch.
apps/files_sharing/tests/Controller/ShareControllerTest.php 2 patches
Indentation   +758 added lines, -758 removed lines patch added patch discarded remove patch
@@ -54,762 +54,762 @@
 block discarded – undo
54 54
  */
55 55
 class ShareControllerTest extends \Test\TestCase {
56 56
 
57
-	private string $user;
58
-	private string $oldUser;
59
-	private string $appName = 'files_sharing';
60
-	private ShareController $shareController;
61
-
62
-	private IL10N&MockObject $l10n;
63
-	private IConfig&MockObject $config;
64
-	private ISession&MockObject $session;
65
-	private Defaults&MockObject $defaults;
66
-	private IAppConfig&MockObject $appConfig;
67
-	private Manager&MockObject $shareManager;
68
-	private IPreview&MockObject $previewManager;
69
-	private IUserManager&MockObject $userManager;
70
-	private IInitialState&MockObject $initialState;
71
-	private IURLGenerator&MockObject $urlGenerator;
72
-	private ISecureRandom&MockObject $secureRandom;
73
-	private IAccountManager&MockObject $accountManager;
74
-	private IEventDispatcher&MockObject $eventDispatcher;
75
-	private FederatedShareProvider&MockObject $federatedShareProvider;
76
-	private IPublicShareTemplateFactory&MockObject $publicShareTemplateFactory;
77
-
78
-	protected function setUp(): void {
79
-		parent::setUp();
80
-		$this->appName = 'files_sharing';
81
-
82
-		$this->shareManager = $this->createMock(Manager::class);
83
-		$this->urlGenerator = $this->createMock(IURLGenerator::class);
84
-		$this->session = $this->createMock(ISession::class);
85
-		$this->previewManager = $this->createMock(IPreview::class);
86
-		$this->config = $this->createMock(IConfig::class);
87
-		$this->appConfig = $this->createMock(IAppConfig::class);
88
-		$this->userManager = $this->createMock(IUserManager::class);
89
-		$this->initialState = $this->createMock(IInitialState::class);
90
-		$this->federatedShareProvider = $this->createMock(FederatedShareProvider::class);
91
-		$this->federatedShareProvider->expects($this->any())
92
-			->method('isOutgoingServer2serverShareEnabled')->willReturn(true);
93
-		$this->federatedShareProvider->expects($this->any())
94
-			->method('isIncomingServer2serverShareEnabled')->willReturn(true);
95
-		$this->accountManager = $this->createMock(IAccountManager::class);
96
-		$this->eventDispatcher = $this->createMock(IEventDispatcher::class);
97
-		$this->l10n = $this->createMock(IL10N::class);
98
-		$this->secureRandom = $this->createMock(ISecureRandom::class);
99
-		$this->defaults = $this->createMock(Defaults::class);
100
-		$this->publicShareTemplateFactory = $this->createMock(IPublicShareTemplateFactory::class);
101
-		$this->publicShareTemplateFactory
102
-			->expects($this->any())
103
-			->method('getProvider')
104
-			->willReturn(
105
-				new DefaultPublicShareTemplateProvider(
106
-					$this->userManager,
107
-					$this->accountManager,
108
-					$this->previewManager,
109
-					$this->federatedShareProvider,
110
-					$this->urlGenerator,
111
-					$this->eventDispatcher,
112
-					$this->l10n,
113
-					$this->defaults,
114
-					$this->config,
115
-					$this->createMock(IRequest::class),
116
-					$this->initialState,
117
-					$this->appConfig,
118
-				)
119
-			);
120
-
121
-		$this->shareController = new ShareController(
122
-			$this->appName,
123
-			$this->createMock(IRequest::class),
124
-			$this->config,
125
-			$this->urlGenerator,
126
-			$this->userManager,
127
-			$this->createMock(IManager::class),
128
-			$this->shareManager,
129
-			$this->session,
130
-			$this->previewManager,
131
-			$this->createMock(IRootFolder::class),
132
-			$this->federatedShareProvider,
133
-			$this->accountManager,
134
-			$this->eventDispatcher,
135
-			$this->l10n,
136
-			$this->secureRandom,
137
-			$this->defaults,
138
-			$this->publicShareTemplateFactory,
139
-		);
140
-
141
-
142
-		// Store current user
143
-		$this->oldUser = \OC_User::getUser();
144
-
145
-		// Create a dummy user
146
-		$this->user = Server::get(ISecureRandom::class)->generate(12, ISecureRandom::CHAR_LOWER);
147
-
148
-		Server::get(IUserManager::class)->createUser($this->user, $this->user);
149
-		\OC_Util::tearDownFS();
150
-		$this->loginAsUser($this->user);
151
-	}
152
-
153
-	protected function tearDown(): void {
154
-		\OC_Util::tearDownFS();
155
-		\OC_User::setUserId('');
156
-		Filesystem::tearDown();
157
-		$user = Server::get(IUserManager::class)->get($this->user);
158
-		if ($user !== null) {
159
-			$user->delete();
160
-		}
161
-		\OC_User::setIncognitoMode(false);
162
-
163
-		Server::get(ISession::class)->set('public_link_authenticated', '');
164
-
165
-		// Set old user
166
-		\OC_User::setUserId($this->oldUser);
167
-		\OC_Util::setupFS($this->oldUser);
168
-		parent::tearDown();
169
-	}
170
-
171
-	public function testShowShareInvalidToken(): void {
172
-		$this->shareController->setToken('invalidtoken');
173
-
174
-		$this->shareManager
175
-			->expects($this->once())
176
-			->method('getShareByToken')
177
-			->with('invalidtoken')
178
-			->will($this->throwException(new ShareNotFound()));
179
-
180
-		$this->expectException(NotFoundException::class);
181
-
182
-		// Test without a not existing token
183
-		$this->shareController->showShare();
184
-	}
185
-
186
-	public function testShowShareNotAuthenticated(): void {
187
-		$this->shareController->setToken('validtoken');
188
-
189
-		$share = Server::get(\OCP\Share\IManager::class)->newShare();
190
-		$share->setPassword('password');
191
-
192
-		$this->shareManager
193
-			->expects($this->once())
194
-			->method('getShareByToken')
195
-			->with('validtoken')
196
-			->willReturn($share);
197
-
198
-		$this->expectException(NotFoundException::class);
199
-
200
-		// Test without a not existing token
201
-		$this->shareController->showShare();
202
-	}
203
-
204
-
205
-	public function testShowShare(): void {
206
-		$note = 'personal note';
207
-		$filename = 'file1.txt';
208
-
209
-		$this->shareController->setToken('token');
210
-
211
-		$owner = $this->createMock(IUser::class);
212
-		$owner->method('getDisplayName')->willReturn('ownerDisplay');
213
-		$owner->method('getUID')->willReturn('ownerUID');
214
-		$owner->method('isEnabled')->willReturn(true);
215
-
216
-		$initiator = $this->createMock(IUser::class);
217
-		$initiator->method('getDisplayName')->willReturn('initiatorDisplay');
218
-		$initiator->method('getUID')->willReturn('initiatorUID');
219
-		$initiator->method('isEnabled')->willReturn(true);
220
-
221
-		$file = $this->createMock(File::class);
222
-		$file->method('getName')->willReturn($filename);
223
-		$file->method('getMimetype')->willReturn('text/plain');
224
-		$file->method('getSize')->willReturn(33);
225
-		$file->method('isReadable')->willReturn(true);
226
-		$file->method('isShareable')->willReturn(true);
227
-		$file->method('getId')->willReturn(111);
228
-
229
-		$accountName = $this->createMock(IAccountProperty::class);
230
-		$accountName->method('getScope')
231
-			->willReturn(IAccountManager::SCOPE_PUBLISHED);
232
-		$account = $this->createMock(IAccount::class);
233
-		$account->method('getProperty')
234
-			->with(IAccountManager::PROPERTY_DISPLAYNAME)
235
-			->willReturn($accountName);
236
-		$this->accountManager->expects($this->once())
237
-			->method('getAccount')
238
-			->with($owner)
239
-			->willReturn($account);
240
-
241
-		/** @var Manager */
242
-		$manager = Server::get(Manager::class);
243
-		$share = $manager->newShare();
244
-		$share->setId(42)
245
-			->setPermissions(Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE)
246
-			->setPassword('password')
247
-			->setShareOwner('ownerUID')
248
-			->setSharedBy('initiatorUID')
249
-			->setNode($file)
250
-			->setNote($note)
251
-			->setTarget("/$filename")
252
-			->setToken('token');
253
-
254
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
255
-		$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
256
-
257
-		$this->urlGenerator->expects(self::atLeast(2))
258
-			->method('linkToRouteAbsolute')
259
-			->willReturnMap([
260
-				// every file has the show show share url in the opengraph url prop
261
-				['files_sharing.sharecontroller.showShare', ['token' => 'token'], 'shareUrl'],
262
-				// this share is not an image to the default preview is used
263
-				['files_sharing.PublicPreview.getPreview', ['x' => 256, 'y' => 256, 'file' => $share->getTarget(), 'token' => 'token'], 'previewUrl'],
264
-			]);
265
-
266
-		$this->urlGenerator->expects($this->once())
267
-			->method('getAbsoluteURL')
268
-			->willReturnMap([
269
-				['/public.php/dav/files/token/?accept=zip', 'downloadUrl'],
270
-			]);
271
-
272
-		$this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
273
-
274
-		$this->config->method('getSystemValue')
275
-			->willReturnMap(
276
-				[
277
-					['max_filesize_animated_gifs_public_sharing', 10, 10],
278
-					['enable_previews', true, true],
279
-					['preview_max_x', 1024, 1024],
280
-					['preview_max_y', 1024, 1024],
281
-				]
282
-			);
283
-
284
-		$this->shareManager
285
-			->expects($this->once())
286
-			->method('getShareByToken')
287
-			->with('token')
288
-			->willReturn($share);
289
-
290
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
291
-			if ($uid === 'ownerUID') {
292
-				return $owner;
293
-			}
294
-			if ($uid === 'initiatorUID') {
295
-				return $initiator;
296
-			}
297
-			return null;
298
-		});
299
-
300
-		$this->eventDispatcher->method('dispatchTyped')->with(
301
-			$this->callback(function ($event) use ($share) {
302
-				if ($event instanceof BeforeTemplateRenderedEvent) {
303
-					return $event->getShare() === $share;
304
-				} else {
305
-					return true;
306
-				}
307
-			})
308
-		);
309
-
310
-		$this->l10n->expects($this->any())
311
-			->method('t')
312
-			->willReturnCallback(function ($text, $parameters) {
313
-				return vsprintf($text, $parameters);
314
-			});
315
-
316
-		$this->defaults->expects(self::any())
317
-			->method('getProductName')
318
-			->willReturn('Nextcloud');
319
-
320
-		// Ensure the correct initial state is setup
321
-		// Shared node is a file so this is a single file share:
322
-		$view = 'public-file-share';
323
-		// Set up initial state
324
-		$initialState = [];
325
-		$this->initialState->expects(self::any())
326
-			->method('provideInitialState')
327
-			->willReturnCallback(function ($key, $value) use (&$initialState): void {
328
-				$initialState[$key] = $value;
329
-			});
330
-		$expectedInitialState = [
331
-			'isPublic' => true,
332
-			'sharingToken' => 'token',
333
-			'sharePermissions' => (Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE),
334
-			'filename' => $filename,
335
-			'view' => $view,
336
-			'fileId' => 111,
337
-			'owner' => 'ownerUID',
338
-			'ownerDisplayName' => 'ownerDisplay',
339
-		];
340
-
341
-		$response = $this->shareController->showShare();
342
-
343
-		$this->assertEquals($expectedInitialState, $initialState);
344
-
345
-		$csp = new ContentSecurityPolicy();
346
-		$csp->addAllowedFrameDomain('\'self\'');
347
-		$expectedResponse = new PublicTemplateResponse('files', 'index');
348
-		$expectedResponse->setParams(['pageTitle' => $filename]);
349
-		$expectedResponse->setContentSecurityPolicy($csp);
350
-		$expectedResponse->setHeaderTitle($filename);
351
-		$expectedResponse->setHeaderDetails('shared by ownerDisplay');
352
-		$expectedResponse->setHeaderActions([
353
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', 'downloadUrl', 0, '33'),
354
-			new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', 'owner', 'ownerDisplay', $filename),
355
-			new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', 'downloadUrl'),
356
-		]);
357
-
358
-		$this->assertEquals($expectedResponse, $response);
359
-	}
360
-
361
-	public function testShowFileDropShare(): void {
362
-		$filename = 'folder1';
363
-
364
-		$this->shareController->setToken('token');
365
-
366
-		$owner = $this->createMock(IUser::class);
367
-		$owner->method('getDisplayName')->willReturn('ownerDisplay');
368
-		$owner->method('getUID')->willReturn('ownerUID');
369
-		$owner->method('isEnabled')->willReturn(true);
370
-
371
-		$initiator = $this->createMock(IUser::class);
372
-		$initiator->method('getDisplayName')->willReturn('initiatorDisplay');
373
-		$initiator->method('getUID')->willReturn('initiatorUID');
374
-		$initiator->method('isEnabled')->willReturn(true);
375
-
376
-		$file = $this->createMock(Folder::class);
377
-		$file->method('isReadable')->willReturn(true);
378
-		$file->method('isShareable')->willReturn(true);
379
-		$file->method('getId')->willReturn(1234);
380
-		$file->method('getName')->willReturn($filename);
381
-
382
-		$accountName = $this->createMock(IAccountProperty::class);
383
-		$accountName->method('getScope')
384
-			->willReturn(IAccountManager::SCOPE_PUBLISHED);
385
-		$account = $this->createMock(IAccount::class);
386
-		$account->method('getProperty')
387
-			->with(IAccountManager::PROPERTY_DISPLAYNAME)
388
-			->willReturn($accountName);
389
-		$this->accountManager->expects($this->once())
390
-			->method('getAccount')
391
-			->with($owner)
392
-			->willReturn($account);
393
-
394
-		/** @var Manager */
395
-		$manager = Server::get(Manager::class);
396
-		$share = $manager->newShare();
397
-		$share->setId(42)
398
-			->setPermissions(Constants::PERMISSION_CREATE)
399
-			->setPassword('password')
400
-			->setShareOwner('ownerUID')
401
-			->setSharedBy('initiatorUID')
402
-			->setNode($file)
403
-			->setTarget("/$filename")
404
-			->setToken('token');
405
-
406
-		$this->appConfig
407
-			->expects($this->once())
408
-			->method('getValueString')
409
-			->with('core', 'shareapi_public_link_disclaimertext', '')
410
-			->willReturn('My disclaimer text');
411
-
412
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
413
-		$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
414
-
415
-		$this->urlGenerator->expects(self::atLeastOnce())
416
-			->method('linkToRouteAbsolute')
417
-			->willReturnMap([
418
-				// every file has the show show share url in the opengraph url prop
419
-				['files_sharing.sharecontroller.showShare', ['token' => 'token'], 'shareUrl'],
420
-				// there is no preview or folders so no other link for opengraph
421
-			]);
422
-
423
-		$this->config->method('getSystemValue')
424
-			->willReturnMap(
425
-				[
426
-					['max_filesize_animated_gifs_public_sharing', 10, 10],
427
-					['enable_previews', true, true],
428
-					['preview_max_x', 1024, 1024],
429
-					['preview_max_y', 1024, 1024],
430
-				]
431
-			);
432
-
433
-		$this->shareManager
434
-			->expects($this->once())
435
-			->method('getShareByToken')
436
-			->with('token')
437
-			->willReturn($share);
438
-
439
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
440
-			if ($uid === 'ownerUID') {
441
-				return $owner;
442
-			}
443
-			if ($uid === 'initiatorUID') {
444
-				return $initiator;
445
-			}
446
-			return null;
447
-		});
448
-
449
-		$this->eventDispatcher->method('dispatchTyped')->with(
450
-			$this->callback(function ($event) use ($share) {
451
-				if ($event instanceof BeforeTemplateRenderedEvent) {
452
-					return $event->getShare() === $share;
453
-				} else {
454
-					return true;
455
-				}
456
-			})
457
-		);
458
-
459
-		$this->l10n->expects($this->any())
460
-			->method('t')
461
-			->willReturnCallback(function ($text, $parameters) {
462
-				return vsprintf($text, $parameters);
463
-			});
464
-
465
-		// Set up initial state
466
-		$initialState = [];
467
-		$this->initialState->expects(self::any())
468
-			->method('provideInitialState')
469
-			->willReturnCallback(function ($key, $value) use (&$initialState): void {
470
-				$initialState[$key] = $value;
471
-			});
472
-		$expectedInitialState = [
473
-			'isPublic' => true,
474
-			'sharingToken' => 'token',
475
-			'sharePermissions' => Constants::PERMISSION_CREATE,
476
-			'filename' => $filename,
477
-			'view' => 'public-file-drop',
478
-			'disclaimer' => 'My disclaimer text',
479
-			'owner' => 'ownerUID',
480
-			'ownerDisplayName' => 'ownerDisplay',
481
-		];
482
-
483
-		$response = $this->shareController->showShare();
484
-
485
-		$this->assertEquals($expectedInitialState, $initialState);
486
-
487
-		$csp = new ContentSecurityPolicy();
488
-		$csp->addAllowedFrameDomain('\'self\'');
489
-		$expectedResponse = new PublicTemplateResponse('files', 'index');
490
-		$expectedResponse->setParams(['pageTitle' => $filename]);
491
-		$expectedResponse->setContentSecurityPolicy($csp);
492
-		$expectedResponse->setHeaderTitle($filename);
493
-		$expectedResponse->setHeaderDetails('shared by ownerDisplay');
494
-		$expectedResponse->setHeaderActions([
495
-			new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', 'shareUrl'),
496
-		]);
497
-
498
-		$this->assertEquals($expectedResponse, $response);
499
-	}
500
-
501
-	public function testShowShareWithPrivateName(): void {
502
-		$note = 'personal note';
503
-		$filename = 'file1.txt';
504
-
505
-		$this->shareController->setToken('token');
506
-
507
-		$owner = $this->createMock(IUser::class);
508
-		$owner->method('getDisplayName')->willReturn('ownerDisplay');
509
-		$owner->method('getUID')->willReturn('ownerUID');
510
-		$owner->method('isEnabled')->willReturn(true);
511
-
512
-		$initiator = $this->createMock(IUser::class);
513
-		$initiator->method('getDisplayName')->willReturn('initiatorDisplay');
514
-		$initiator->method('getUID')->willReturn('initiatorUID');
515
-		$initiator->method('isEnabled')->willReturn(true);
516
-
517
-		$file = $this->createMock(File::class);
518
-		$file->method('getName')->willReturn($filename);
519
-		$file->method('getMimetype')->willReturn('text/plain');
520
-		$file->method('getSize')->willReturn(33);
521
-		$file->method('isReadable')->willReturn(true);
522
-		$file->method('isShareable')->willReturn(true);
523
-		$file->method('getId')->willReturn(111);
524
-
525
-		$accountName = $this->createMock(IAccountProperty::class);
526
-		$accountName->method('getScope')
527
-			->willReturn(IAccountManager::SCOPE_LOCAL);
528
-		$account = $this->createMock(IAccount::class);
529
-		$account->method('getProperty')
530
-			->with(IAccountManager::PROPERTY_DISPLAYNAME)
531
-			->willReturn($accountName);
532
-		$this->accountManager->expects($this->once())
533
-			->method('getAccount')
534
-			->with($owner)
535
-			->willReturn($account);
536
-
537
-		/** @var IShare */
538
-		$share = Server::get(Manager::class)->newShare();
539
-		$share->setId(42);
540
-		$share->setPassword('password')
541
-			->setShareOwner('ownerUID')
542
-			->setSharedBy('initiatorUID')
543
-			->setNode($file)
544
-			->setNote($note)
545
-			->setToken('token')
546
-			->setPermissions(Constants::PERMISSION_ALL & ~Constants::PERMISSION_SHARE)
547
-			->setTarget("/$filename");
548
-
549
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
550
-		$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
551
-
552
-		$this->urlGenerator->expects(self::atLeast(2))
553
-			->method('linkToRouteAbsolute')
554
-			->willReturnMap([
555
-				// every file has the show show share url in the opengraph url prop
556
-				['files_sharing.sharecontroller.showShare', ['token' => 'token'], 'shareUrl'],
557
-				// this share is not an image to the default preview is used
558
-				['files_sharing.PublicPreview.getPreview', ['x' => 256, 'y' => 256, 'file' => $share->getTarget(), 'token' => 'token'], 'previewUrl'],
559
-			]);
560
-
561
-		$this->urlGenerator->expects($this->once())
562
-			->method('getAbsoluteURL')
563
-			->willReturnMap([
564
-				['/public.php/dav/files/token/?accept=zip', 'downloadUrl'],
565
-			]);
566
-
567
-		$this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
568
-
569
-		$this->config->method('getSystemValue')
570
-			->willReturnMap(
571
-				[
572
-					['max_filesize_animated_gifs_public_sharing', 10, 10],
573
-					['enable_previews', true, true],
574
-					['preview_max_x', 1024, 1024],
575
-					['preview_max_y', 1024, 1024],
576
-				]
577
-			);
578
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
579
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
580
-
581
-		$this->shareManager
582
-			->expects($this->once())
583
-			->method('getShareByToken')
584
-			->with('token')
585
-			->willReturn($share);
586
-
587
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
588
-			if ($uid === 'ownerUID') {
589
-				return $owner;
590
-			}
591
-			if ($uid === 'initiatorUID') {
592
-				return $initiator;
593
-			}
594
-			return null;
595
-		});
596
-
597
-		$this->eventDispatcher->method('dispatchTyped')->with(
598
-			$this->callback(function ($event) use ($share) {
599
-				if ($event instanceof BeforeTemplateRenderedEvent) {
600
-					return $event->getShare() === $share;
601
-				} else {
602
-					return true;
603
-				}
604
-			})
605
-		);
606
-
607
-		$this->l10n->expects($this->any())
608
-			->method('t')
609
-			->will($this->returnCallback(function ($text, $parameters) {
610
-				return vsprintf($text, $parameters);
611
-			}));
612
-
613
-		$this->defaults->expects(self::any())
614
-			->method('getProductName')
615
-			->willReturn('Nextcloud');
616
-
617
-		$response = $this->shareController->showShare();
618
-
619
-		$csp = new ContentSecurityPolicy();
620
-		$csp->addAllowedFrameDomain('\'self\'');
621
-		$expectedResponse = new PublicTemplateResponse('files', 'index');
622
-		$expectedResponse->setParams(['pageTitle' => $filename]);
623
-		$expectedResponse->setContentSecurityPolicy($csp);
624
-		$expectedResponse->setHeaderTitle($filename);
625
-		$expectedResponse->setHeaderDetails('');
626
-		$expectedResponse->setHeaderActions([
627
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', 'downloadUrl', 0, '33'),
628
-			new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', 'owner', 'ownerDisplay', $filename),
629
-			new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', 'downloadUrl'),
630
-		]);
631
-
632
-		$this->assertEquals($expectedResponse, $response);
633
-	}
634
-
635
-
636
-	public function testShowShareInvalid(): void {
637
-		$this->expectException(NotFoundException::class);
638
-
639
-		$filename = 'file1.txt';
640
-		$this->shareController->setToken('token');
641
-
642
-		$owner = $this->getMockBuilder(IUser::class)->getMock();
643
-		$owner->method('getDisplayName')->willReturn('ownerDisplay');
644
-		$owner->method('getUID')->willReturn('ownerUID');
645
-
646
-		$file = $this->getMockBuilder('OCP\Files\File')->getMock();
647
-		$file->method('getName')->willReturn($filename);
648
-		$file->method('getMimetype')->willReturn('text/plain');
649
-		$file->method('getSize')->willReturn(33);
650
-		$file->method('isShareable')->willReturn(false);
651
-		$file->method('isReadable')->willReturn(true);
652
-
653
-		$share = Server::get(\OCP\Share\IManager::class)->newShare();
654
-		$share->setId(42);
655
-		$share->setPassword('password')
656
-			->setShareOwner('ownerUID')
657
-			->setNode($file)
658
-			->setTarget("/$filename");
659
-
660
-		$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
661
-		$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
662
-
663
-		$this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
664
-
665
-		$this->config->method('getSystemValue')
666
-			->willReturnMap(
667
-				[
668
-					['max_filesize_animated_gifs_public_sharing', 10, 10],
669
-					['enable_previews', true, true],
670
-				]
671
-			);
672
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
673
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
674
-
675
-		$this->shareManager
676
-			->expects($this->once())
677
-			->method('getShareByToken')
678
-			->with('token')
679
-			->willReturn($share);
680
-
681
-		$this->userManager->method('get')->with('ownerUID')->willReturn($owner);
682
-
683
-		$this->shareController->showShare();
684
-	}
685
-
686
-	public function testDownloadShareWithCreateOnlyShare(): void {
687
-		$share = $this->getMockBuilder(IShare::class)->getMock();
688
-		$share->method('getPassword')->willReturn('password');
689
-		$share
690
-			->expects($this->once())
691
-			->method('getPermissions')
692
-			->willReturn(Constants::PERMISSION_CREATE);
693
-
694
-		$this->shareManager
695
-			->expects($this->once())
696
-			->method('getShareByToken')
697
-			->with('validtoken')
698
-			->willReturn($share);
699
-
700
-		// Test with a password protected share and no authentication
701
-		$response = $this->shareController->downloadShare('validtoken');
702
-		$expectedResponse = new DataResponse('Share has no read permission');
703
-		$this->assertEquals($expectedResponse, $response);
704
-	}
705
-
706
-	public function testDownloadShareWithoutDownloadPermission(): void {
707
-		$attributes = $this->createMock(IAttributes::class);
708
-		$attributes->expects(self::once())
709
-			->method('getAttribute')
710
-			->with('permissions', 'download')
711
-			->willReturn(false);
712
-
713
-		$share = $this->createMock(IShare::class);
714
-		$share->method('getPassword')->willReturn('password');
715
-		$share->expects(self::once())
716
-			->method('getPermissions')
717
-			->willReturn(Constants::PERMISSION_READ);
718
-		$share->expects(self::once())
719
-			->method('getAttributes')
720
-			->willReturn($attributes);
721
-
722
-		$this->shareManager
723
-			->expects(self::once())
724
-			->method('getShareByToken')
725
-			->with('validtoken')
726
-			->willReturn($share);
727
-
728
-		// Test with a password protected share and no authentication
729
-		$response = $this->shareController->downloadShare('validtoken');
730
-		$expectedResponse = new DataResponse('Share has no download permission');
731
-		$this->assertEquals($expectedResponse, $response);
732
-	}
733
-
734
-	public function testDisabledOwner(): void {
735
-		$this->shareController->setToken('token');
736
-
737
-		$owner = $this->getMockBuilder(IUser::class)->getMock();
738
-		$owner->method('isEnabled')->willReturn(false);
739
-
740
-		$initiator = $this->createMock(IUser::class);
741
-		$initiator->method('isEnabled')->willReturn(false);
742
-
743
-		/* @var MockObject|Folder $folder */
744
-		$folder = $this->createMock(Folder::class);
745
-
746
-		$share = Server::get(\OCP\Share\IManager::class)->newShare();
747
-		$share->setId(42);
748
-		$share->setPermissions(Constants::PERMISSION_CREATE)
749
-			->setShareOwner('ownerUID')
750
-			->setSharedBy('initiatorUID')
751
-			->setNode($folder)
752
-			->setTarget('/share');
753
-
754
-		$this->shareManager
755
-			->expects($this->once())
756
-			->method('getShareByToken')
757
-			->with('token')
758
-			->willReturn($share);
759
-
760
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
761
-			if ($uid === 'ownerUID') {
762
-				return $owner;
763
-			}
764
-			if ($uid === 'initiatorUID') {
765
-				return $initiator;
766
-			}
767
-			return null;
768
-		});
769
-
770
-		$this->expectException(NotFoundException::class);
771
-
772
-		$this->shareController->showShare();
773
-	}
774
-
775
-	public function testDisabledInitiator(): void {
776
-		$this->shareController->setToken('token');
777
-
778
-		$owner = $this->getMockBuilder(IUser::class)->getMock();
779
-		$owner->method('isEnabled')->willReturn(false);
780
-
781
-		$initiator = $this->createMock(IUser::class);
782
-		$initiator->method('isEnabled')->willReturn(true);
783
-
784
-		/* @var MockObject|Folder $folder */
785
-		$folder = $this->createMock(Folder::class);
786
-
787
-		$share = Server::get(\OCP\Share\IManager::class)->newShare();
788
-		$share->setId(42);
789
-		$share->setPermissions(Constants::PERMISSION_CREATE)
790
-			->setShareOwner('ownerUID')
791
-			->setSharedBy('initiatorUID')
792
-			->setNode($folder)
793
-			->setTarget('/share');
794
-
795
-		$this->shareManager
796
-			->expects($this->once())
797
-			->method('getShareByToken')
798
-			->with('token')
799
-			->willReturn($share);
800
-
801
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
802
-			if ($uid === 'ownerUID') {
803
-				return $owner;
804
-			}
805
-			if ($uid === 'initiatorUID') {
806
-				return $initiator;
807
-			}
808
-			return null;
809
-		});
810
-
811
-		$this->expectException(NotFoundException::class);
812
-
813
-		$this->shareController->showShare();
814
-	}
57
+    private string $user;
58
+    private string $oldUser;
59
+    private string $appName = 'files_sharing';
60
+    private ShareController $shareController;
61
+
62
+    private IL10N&MockObject $l10n;
63
+    private IConfig&MockObject $config;
64
+    private ISession&MockObject $session;
65
+    private Defaults&MockObject $defaults;
66
+    private IAppConfig&MockObject $appConfig;
67
+    private Manager&MockObject $shareManager;
68
+    private IPreview&MockObject $previewManager;
69
+    private IUserManager&MockObject $userManager;
70
+    private IInitialState&MockObject $initialState;
71
+    private IURLGenerator&MockObject $urlGenerator;
72
+    private ISecureRandom&MockObject $secureRandom;
73
+    private IAccountManager&MockObject $accountManager;
74
+    private IEventDispatcher&MockObject $eventDispatcher;
75
+    private FederatedShareProvider&MockObject $federatedShareProvider;
76
+    private IPublicShareTemplateFactory&MockObject $publicShareTemplateFactory;
77
+
78
+    protected function setUp(): void {
79
+        parent::setUp();
80
+        $this->appName = 'files_sharing';
81
+
82
+        $this->shareManager = $this->createMock(Manager::class);
83
+        $this->urlGenerator = $this->createMock(IURLGenerator::class);
84
+        $this->session = $this->createMock(ISession::class);
85
+        $this->previewManager = $this->createMock(IPreview::class);
86
+        $this->config = $this->createMock(IConfig::class);
87
+        $this->appConfig = $this->createMock(IAppConfig::class);
88
+        $this->userManager = $this->createMock(IUserManager::class);
89
+        $this->initialState = $this->createMock(IInitialState::class);
90
+        $this->federatedShareProvider = $this->createMock(FederatedShareProvider::class);
91
+        $this->federatedShareProvider->expects($this->any())
92
+            ->method('isOutgoingServer2serverShareEnabled')->willReturn(true);
93
+        $this->federatedShareProvider->expects($this->any())
94
+            ->method('isIncomingServer2serverShareEnabled')->willReturn(true);
95
+        $this->accountManager = $this->createMock(IAccountManager::class);
96
+        $this->eventDispatcher = $this->createMock(IEventDispatcher::class);
97
+        $this->l10n = $this->createMock(IL10N::class);
98
+        $this->secureRandom = $this->createMock(ISecureRandom::class);
99
+        $this->defaults = $this->createMock(Defaults::class);
100
+        $this->publicShareTemplateFactory = $this->createMock(IPublicShareTemplateFactory::class);
101
+        $this->publicShareTemplateFactory
102
+            ->expects($this->any())
103
+            ->method('getProvider')
104
+            ->willReturn(
105
+                new DefaultPublicShareTemplateProvider(
106
+                    $this->userManager,
107
+                    $this->accountManager,
108
+                    $this->previewManager,
109
+                    $this->federatedShareProvider,
110
+                    $this->urlGenerator,
111
+                    $this->eventDispatcher,
112
+                    $this->l10n,
113
+                    $this->defaults,
114
+                    $this->config,
115
+                    $this->createMock(IRequest::class),
116
+                    $this->initialState,
117
+                    $this->appConfig,
118
+                )
119
+            );
120
+
121
+        $this->shareController = new ShareController(
122
+            $this->appName,
123
+            $this->createMock(IRequest::class),
124
+            $this->config,
125
+            $this->urlGenerator,
126
+            $this->userManager,
127
+            $this->createMock(IManager::class),
128
+            $this->shareManager,
129
+            $this->session,
130
+            $this->previewManager,
131
+            $this->createMock(IRootFolder::class),
132
+            $this->federatedShareProvider,
133
+            $this->accountManager,
134
+            $this->eventDispatcher,
135
+            $this->l10n,
136
+            $this->secureRandom,
137
+            $this->defaults,
138
+            $this->publicShareTemplateFactory,
139
+        );
140
+
141
+
142
+        // Store current user
143
+        $this->oldUser = \OC_User::getUser();
144
+
145
+        // Create a dummy user
146
+        $this->user = Server::get(ISecureRandom::class)->generate(12, ISecureRandom::CHAR_LOWER);
147
+
148
+        Server::get(IUserManager::class)->createUser($this->user, $this->user);
149
+        \OC_Util::tearDownFS();
150
+        $this->loginAsUser($this->user);
151
+    }
152
+
153
+    protected function tearDown(): void {
154
+        \OC_Util::tearDownFS();
155
+        \OC_User::setUserId('');
156
+        Filesystem::tearDown();
157
+        $user = Server::get(IUserManager::class)->get($this->user);
158
+        if ($user !== null) {
159
+            $user->delete();
160
+        }
161
+        \OC_User::setIncognitoMode(false);
162
+
163
+        Server::get(ISession::class)->set('public_link_authenticated', '');
164
+
165
+        // Set old user
166
+        \OC_User::setUserId($this->oldUser);
167
+        \OC_Util::setupFS($this->oldUser);
168
+        parent::tearDown();
169
+    }
170
+
171
+    public function testShowShareInvalidToken(): void {
172
+        $this->shareController->setToken('invalidtoken');
173
+
174
+        $this->shareManager
175
+            ->expects($this->once())
176
+            ->method('getShareByToken')
177
+            ->with('invalidtoken')
178
+            ->will($this->throwException(new ShareNotFound()));
179
+
180
+        $this->expectException(NotFoundException::class);
181
+
182
+        // Test without a not existing token
183
+        $this->shareController->showShare();
184
+    }
185
+
186
+    public function testShowShareNotAuthenticated(): void {
187
+        $this->shareController->setToken('validtoken');
188
+
189
+        $share = Server::get(\OCP\Share\IManager::class)->newShare();
190
+        $share->setPassword('password');
191
+
192
+        $this->shareManager
193
+            ->expects($this->once())
194
+            ->method('getShareByToken')
195
+            ->with('validtoken')
196
+            ->willReturn($share);
197
+
198
+        $this->expectException(NotFoundException::class);
199
+
200
+        // Test without a not existing token
201
+        $this->shareController->showShare();
202
+    }
203
+
204
+
205
+    public function testShowShare(): void {
206
+        $note = 'personal note';
207
+        $filename = 'file1.txt';
208
+
209
+        $this->shareController->setToken('token');
210
+
211
+        $owner = $this->createMock(IUser::class);
212
+        $owner->method('getDisplayName')->willReturn('ownerDisplay');
213
+        $owner->method('getUID')->willReturn('ownerUID');
214
+        $owner->method('isEnabled')->willReturn(true);
215
+
216
+        $initiator = $this->createMock(IUser::class);
217
+        $initiator->method('getDisplayName')->willReturn('initiatorDisplay');
218
+        $initiator->method('getUID')->willReturn('initiatorUID');
219
+        $initiator->method('isEnabled')->willReturn(true);
220
+
221
+        $file = $this->createMock(File::class);
222
+        $file->method('getName')->willReturn($filename);
223
+        $file->method('getMimetype')->willReturn('text/plain');
224
+        $file->method('getSize')->willReturn(33);
225
+        $file->method('isReadable')->willReturn(true);
226
+        $file->method('isShareable')->willReturn(true);
227
+        $file->method('getId')->willReturn(111);
228
+
229
+        $accountName = $this->createMock(IAccountProperty::class);
230
+        $accountName->method('getScope')
231
+            ->willReturn(IAccountManager::SCOPE_PUBLISHED);
232
+        $account = $this->createMock(IAccount::class);
233
+        $account->method('getProperty')
234
+            ->with(IAccountManager::PROPERTY_DISPLAYNAME)
235
+            ->willReturn($accountName);
236
+        $this->accountManager->expects($this->once())
237
+            ->method('getAccount')
238
+            ->with($owner)
239
+            ->willReturn($account);
240
+
241
+        /** @var Manager */
242
+        $manager = Server::get(Manager::class);
243
+        $share = $manager->newShare();
244
+        $share->setId(42)
245
+            ->setPermissions(Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE)
246
+            ->setPassword('password')
247
+            ->setShareOwner('ownerUID')
248
+            ->setSharedBy('initiatorUID')
249
+            ->setNode($file)
250
+            ->setNote($note)
251
+            ->setTarget("/$filename")
252
+            ->setToken('token');
253
+
254
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
255
+        $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
256
+
257
+        $this->urlGenerator->expects(self::atLeast(2))
258
+            ->method('linkToRouteAbsolute')
259
+            ->willReturnMap([
260
+                // every file has the show show share url in the opengraph url prop
261
+                ['files_sharing.sharecontroller.showShare', ['token' => 'token'], 'shareUrl'],
262
+                // this share is not an image to the default preview is used
263
+                ['files_sharing.PublicPreview.getPreview', ['x' => 256, 'y' => 256, 'file' => $share->getTarget(), 'token' => 'token'], 'previewUrl'],
264
+            ]);
265
+
266
+        $this->urlGenerator->expects($this->once())
267
+            ->method('getAbsoluteURL')
268
+            ->willReturnMap([
269
+                ['/public.php/dav/files/token/?accept=zip', 'downloadUrl'],
270
+            ]);
271
+
272
+        $this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
273
+
274
+        $this->config->method('getSystemValue')
275
+            ->willReturnMap(
276
+                [
277
+                    ['max_filesize_animated_gifs_public_sharing', 10, 10],
278
+                    ['enable_previews', true, true],
279
+                    ['preview_max_x', 1024, 1024],
280
+                    ['preview_max_y', 1024, 1024],
281
+                ]
282
+            );
283
+
284
+        $this->shareManager
285
+            ->expects($this->once())
286
+            ->method('getShareByToken')
287
+            ->with('token')
288
+            ->willReturn($share);
289
+
290
+        $this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
291
+            if ($uid === 'ownerUID') {
292
+                return $owner;
293
+            }
294
+            if ($uid === 'initiatorUID') {
295
+                return $initiator;
296
+            }
297
+            return null;
298
+        });
299
+
300
+        $this->eventDispatcher->method('dispatchTyped')->with(
301
+            $this->callback(function ($event) use ($share) {
302
+                if ($event instanceof BeforeTemplateRenderedEvent) {
303
+                    return $event->getShare() === $share;
304
+                } else {
305
+                    return true;
306
+                }
307
+            })
308
+        );
309
+
310
+        $this->l10n->expects($this->any())
311
+            ->method('t')
312
+            ->willReturnCallback(function ($text, $parameters) {
313
+                return vsprintf($text, $parameters);
314
+            });
315
+
316
+        $this->defaults->expects(self::any())
317
+            ->method('getProductName')
318
+            ->willReturn('Nextcloud');
319
+
320
+        // Ensure the correct initial state is setup
321
+        // Shared node is a file so this is a single file share:
322
+        $view = 'public-file-share';
323
+        // Set up initial state
324
+        $initialState = [];
325
+        $this->initialState->expects(self::any())
326
+            ->method('provideInitialState')
327
+            ->willReturnCallback(function ($key, $value) use (&$initialState): void {
328
+                $initialState[$key] = $value;
329
+            });
330
+        $expectedInitialState = [
331
+            'isPublic' => true,
332
+            'sharingToken' => 'token',
333
+            'sharePermissions' => (Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE),
334
+            'filename' => $filename,
335
+            'view' => $view,
336
+            'fileId' => 111,
337
+            'owner' => 'ownerUID',
338
+            'ownerDisplayName' => 'ownerDisplay',
339
+        ];
340
+
341
+        $response = $this->shareController->showShare();
342
+
343
+        $this->assertEquals($expectedInitialState, $initialState);
344
+
345
+        $csp = new ContentSecurityPolicy();
346
+        $csp->addAllowedFrameDomain('\'self\'');
347
+        $expectedResponse = new PublicTemplateResponse('files', 'index');
348
+        $expectedResponse->setParams(['pageTitle' => $filename]);
349
+        $expectedResponse->setContentSecurityPolicy($csp);
350
+        $expectedResponse->setHeaderTitle($filename);
351
+        $expectedResponse->setHeaderDetails('shared by ownerDisplay');
352
+        $expectedResponse->setHeaderActions([
353
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', 'downloadUrl', 0, '33'),
354
+            new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', 'owner', 'ownerDisplay', $filename),
355
+            new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', 'downloadUrl'),
356
+        ]);
357
+
358
+        $this->assertEquals($expectedResponse, $response);
359
+    }
360
+
361
+    public function testShowFileDropShare(): void {
362
+        $filename = 'folder1';
363
+
364
+        $this->shareController->setToken('token');
365
+
366
+        $owner = $this->createMock(IUser::class);
367
+        $owner->method('getDisplayName')->willReturn('ownerDisplay');
368
+        $owner->method('getUID')->willReturn('ownerUID');
369
+        $owner->method('isEnabled')->willReturn(true);
370
+
371
+        $initiator = $this->createMock(IUser::class);
372
+        $initiator->method('getDisplayName')->willReturn('initiatorDisplay');
373
+        $initiator->method('getUID')->willReturn('initiatorUID');
374
+        $initiator->method('isEnabled')->willReturn(true);
375
+
376
+        $file = $this->createMock(Folder::class);
377
+        $file->method('isReadable')->willReturn(true);
378
+        $file->method('isShareable')->willReturn(true);
379
+        $file->method('getId')->willReturn(1234);
380
+        $file->method('getName')->willReturn($filename);
381
+
382
+        $accountName = $this->createMock(IAccountProperty::class);
383
+        $accountName->method('getScope')
384
+            ->willReturn(IAccountManager::SCOPE_PUBLISHED);
385
+        $account = $this->createMock(IAccount::class);
386
+        $account->method('getProperty')
387
+            ->with(IAccountManager::PROPERTY_DISPLAYNAME)
388
+            ->willReturn($accountName);
389
+        $this->accountManager->expects($this->once())
390
+            ->method('getAccount')
391
+            ->with($owner)
392
+            ->willReturn($account);
393
+
394
+        /** @var Manager */
395
+        $manager = Server::get(Manager::class);
396
+        $share = $manager->newShare();
397
+        $share->setId(42)
398
+            ->setPermissions(Constants::PERMISSION_CREATE)
399
+            ->setPassword('password')
400
+            ->setShareOwner('ownerUID')
401
+            ->setSharedBy('initiatorUID')
402
+            ->setNode($file)
403
+            ->setTarget("/$filename")
404
+            ->setToken('token');
405
+
406
+        $this->appConfig
407
+            ->expects($this->once())
408
+            ->method('getValueString')
409
+            ->with('core', 'shareapi_public_link_disclaimertext', '')
410
+            ->willReturn('My disclaimer text');
411
+
412
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
413
+        $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
414
+
415
+        $this->urlGenerator->expects(self::atLeastOnce())
416
+            ->method('linkToRouteAbsolute')
417
+            ->willReturnMap([
418
+                // every file has the show show share url in the opengraph url prop
419
+                ['files_sharing.sharecontroller.showShare', ['token' => 'token'], 'shareUrl'],
420
+                // there is no preview or folders so no other link for opengraph
421
+            ]);
422
+
423
+        $this->config->method('getSystemValue')
424
+            ->willReturnMap(
425
+                [
426
+                    ['max_filesize_animated_gifs_public_sharing', 10, 10],
427
+                    ['enable_previews', true, true],
428
+                    ['preview_max_x', 1024, 1024],
429
+                    ['preview_max_y', 1024, 1024],
430
+                ]
431
+            );
432
+
433
+        $this->shareManager
434
+            ->expects($this->once())
435
+            ->method('getShareByToken')
436
+            ->with('token')
437
+            ->willReturn($share);
438
+
439
+        $this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
440
+            if ($uid === 'ownerUID') {
441
+                return $owner;
442
+            }
443
+            if ($uid === 'initiatorUID') {
444
+                return $initiator;
445
+            }
446
+            return null;
447
+        });
448
+
449
+        $this->eventDispatcher->method('dispatchTyped')->with(
450
+            $this->callback(function ($event) use ($share) {
451
+                if ($event instanceof BeforeTemplateRenderedEvent) {
452
+                    return $event->getShare() === $share;
453
+                } else {
454
+                    return true;
455
+                }
456
+            })
457
+        );
458
+
459
+        $this->l10n->expects($this->any())
460
+            ->method('t')
461
+            ->willReturnCallback(function ($text, $parameters) {
462
+                return vsprintf($text, $parameters);
463
+            });
464
+
465
+        // Set up initial state
466
+        $initialState = [];
467
+        $this->initialState->expects(self::any())
468
+            ->method('provideInitialState')
469
+            ->willReturnCallback(function ($key, $value) use (&$initialState): void {
470
+                $initialState[$key] = $value;
471
+            });
472
+        $expectedInitialState = [
473
+            'isPublic' => true,
474
+            'sharingToken' => 'token',
475
+            'sharePermissions' => Constants::PERMISSION_CREATE,
476
+            'filename' => $filename,
477
+            'view' => 'public-file-drop',
478
+            'disclaimer' => 'My disclaimer text',
479
+            'owner' => 'ownerUID',
480
+            'ownerDisplayName' => 'ownerDisplay',
481
+        ];
482
+
483
+        $response = $this->shareController->showShare();
484
+
485
+        $this->assertEquals($expectedInitialState, $initialState);
486
+
487
+        $csp = new ContentSecurityPolicy();
488
+        $csp->addAllowedFrameDomain('\'self\'');
489
+        $expectedResponse = new PublicTemplateResponse('files', 'index');
490
+        $expectedResponse->setParams(['pageTitle' => $filename]);
491
+        $expectedResponse->setContentSecurityPolicy($csp);
492
+        $expectedResponse->setHeaderTitle($filename);
493
+        $expectedResponse->setHeaderDetails('shared by ownerDisplay');
494
+        $expectedResponse->setHeaderActions([
495
+            new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', 'shareUrl'),
496
+        ]);
497
+
498
+        $this->assertEquals($expectedResponse, $response);
499
+    }
500
+
501
+    public function testShowShareWithPrivateName(): void {
502
+        $note = 'personal note';
503
+        $filename = 'file1.txt';
504
+
505
+        $this->shareController->setToken('token');
506
+
507
+        $owner = $this->createMock(IUser::class);
508
+        $owner->method('getDisplayName')->willReturn('ownerDisplay');
509
+        $owner->method('getUID')->willReturn('ownerUID');
510
+        $owner->method('isEnabled')->willReturn(true);
511
+
512
+        $initiator = $this->createMock(IUser::class);
513
+        $initiator->method('getDisplayName')->willReturn('initiatorDisplay');
514
+        $initiator->method('getUID')->willReturn('initiatorUID');
515
+        $initiator->method('isEnabled')->willReturn(true);
516
+
517
+        $file = $this->createMock(File::class);
518
+        $file->method('getName')->willReturn($filename);
519
+        $file->method('getMimetype')->willReturn('text/plain');
520
+        $file->method('getSize')->willReturn(33);
521
+        $file->method('isReadable')->willReturn(true);
522
+        $file->method('isShareable')->willReturn(true);
523
+        $file->method('getId')->willReturn(111);
524
+
525
+        $accountName = $this->createMock(IAccountProperty::class);
526
+        $accountName->method('getScope')
527
+            ->willReturn(IAccountManager::SCOPE_LOCAL);
528
+        $account = $this->createMock(IAccount::class);
529
+        $account->method('getProperty')
530
+            ->with(IAccountManager::PROPERTY_DISPLAYNAME)
531
+            ->willReturn($accountName);
532
+        $this->accountManager->expects($this->once())
533
+            ->method('getAccount')
534
+            ->with($owner)
535
+            ->willReturn($account);
536
+
537
+        /** @var IShare */
538
+        $share = Server::get(Manager::class)->newShare();
539
+        $share->setId(42);
540
+        $share->setPassword('password')
541
+            ->setShareOwner('ownerUID')
542
+            ->setSharedBy('initiatorUID')
543
+            ->setNode($file)
544
+            ->setNote($note)
545
+            ->setToken('token')
546
+            ->setPermissions(Constants::PERMISSION_ALL & ~Constants::PERMISSION_SHARE)
547
+            ->setTarget("/$filename");
548
+
549
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
550
+        $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
551
+
552
+        $this->urlGenerator->expects(self::atLeast(2))
553
+            ->method('linkToRouteAbsolute')
554
+            ->willReturnMap([
555
+                // every file has the show show share url in the opengraph url prop
556
+                ['files_sharing.sharecontroller.showShare', ['token' => 'token'], 'shareUrl'],
557
+                // this share is not an image to the default preview is used
558
+                ['files_sharing.PublicPreview.getPreview', ['x' => 256, 'y' => 256, 'file' => $share->getTarget(), 'token' => 'token'], 'previewUrl'],
559
+            ]);
560
+
561
+        $this->urlGenerator->expects($this->once())
562
+            ->method('getAbsoluteURL')
563
+            ->willReturnMap([
564
+                ['/public.php/dav/files/token/?accept=zip', 'downloadUrl'],
565
+            ]);
566
+
567
+        $this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
568
+
569
+        $this->config->method('getSystemValue')
570
+            ->willReturnMap(
571
+                [
572
+                    ['max_filesize_animated_gifs_public_sharing', 10, 10],
573
+                    ['enable_previews', true, true],
574
+                    ['preview_max_x', 1024, 1024],
575
+                    ['preview_max_y', 1024, 1024],
576
+                ]
577
+            );
578
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
579
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
580
+
581
+        $this->shareManager
582
+            ->expects($this->once())
583
+            ->method('getShareByToken')
584
+            ->with('token')
585
+            ->willReturn($share);
586
+
587
+        $this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
588
+            if ($uid === 'ownerUID') {
589
+                return $owner;
590
+            }
591
+            if ($uid === 'initiatorUID') {
592
+                return $initiator;
593
+            }
594
+            return null;
595
+        });
596
+
597
+        $this->eventDispatcher->method('dispatchTyped')->with(
598
+            $this->callback(function ($event) use ($share) {
599
+                if ($event instanceof BeforeTemplateRenderedEvent) {
600
+                    return $event->getShare() === $share;
601
+                } else {
602
+                    return true;
603
+                }
604
+            })
605
+        );
606
+
607
+        $this->l10n->expects($this->any())
608
+            ->method('t')
609
+            ->will($this->returnCallback(function ($text, $parameters) {
610
+                return vsprintf($text, $parameters);
611
+            }));
612
+
613
+        $this->defaults->expects(self::any())
614
+            ->method('getProductName')
615
+            ->willReturn('Nextcloud');
616
+
617
+        $response = $this->shareController->showShare();
618
+
619
+        $csp = new ContentSecurityPolicy();
620
+        $csp->addAllowedFrameDomain('\'self\'');
621
+        $expectedResponse = new PublicTemplateResponse('files', 'index');
622
+        $expectedResponse->setParams(['pageTitle' => $filename]);
623
+        $expectedResponse->setContentSecurityPolicy($csp);
624
+        $expectedResponse->setHeaderTitle($filename);
625
+        $expectedResponse->setHeaderDetails('');
626
+        $expectedResponse->setHeaderActions([
627
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', 'downloadUrl', 0, '33'),
628
+            new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', 'owner', 'ownerDisplay', $filename),
629
+            new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', 'downloadUrl'),
630
+        ]);
631
+
632
+        $this->assertEquals($expectedResponse, $response);
633
+    }
634
+
635
+
636
+    public function testShowShareInvalid(): void {
637
+        $this->expectException(NotFoundException::class);
638
+
639
+        $filename = 'file1.txt';
640
+        $this->shareController->setToken('token');
641
+
642
+        $owner = $this->getMockBuilder(IUser::class)->getMock();
643
+        $owner->method('getDisplayName')->willReturn('ownerDisplay');
644
+        $owner->method('getUID')->willReturn('ownerUID');
645
+
646
+        $file = $this->getMockBuilder('OCP\Files\File')->getMock();
647
+        $file->method('getName')->willReturn($filename);
648
+        $file->method('getMimetype')->willReturn('text/plain');
649
+        $file->method('getSize')->willReturn(33);
650
+        $file->method('isShareable')->willReturn(false);
651
+        $file->method('isReadable')->willReturn(true);
652
+
653
+        $share = Server::get(\OCP\Share\IManager::class)->newShare();
654
+        $share->setId(42);
655
+        $share->setPassword('password')
656
+            ->setShareOwner('ownerUID')
657
+            ->setNode($file)
658
+            ->setTarget("/$filename");
659
+
660
+        $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
661
+        $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
662
+
663
+        $this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
664
+
665
+        $this->config->method('getSystemValue')
666
+            ->willReturnMap(
667
+                [
668
+                    ['max_filesize_animated_gifs_public_sharing', 10, 10],
669
+                    ['enable_previews', true, true],
670
+                ]
671
+            );
672
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
673
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
674
+
675
+        $this->shareManager
676
+            ->expects($this->once())
677
+            ->method('getShareByToken')
678
+            ->with('token')
679
+            ->willReturn($share);
680
+
681
+        $this->userManager->method('get')->with('ownerUID')->willReturn($owner);
682
+
683
+        $this->shareController->showShare();
684
+    }
685
+
686
+    public function testDownloadShareWithCreateOnlyShare(): void {
687
+        $share = $this->getMockBuilder(IShare::class)->getMock();
688
+        $share->method('getPassword')->willReturn('password');
689
+        $share
690
+            ->expects($this->once())
691
+            ->method('getPermissions')
692
+            ->willReturn(Constants::PERMISSION_CREATE);
693
+
694
+        $this->shareManager
695
+            ->expects($this->once())
696
+            ->method('getShareByToken')
697
+            ->with('validtoken')
698
+            ->willReturn($share);
699
+
700
+        // Test with a password protected share and no authentication
701
+        $response = $this->shareController->downloadShare('validtoken');
702
+        $expectedResponse = new DataResponse('Share has no read permission');
703
+        $this->assertEquals($expectedResponse, $response);
704
+    }
705
+
706
+    public function testDownloadShareWithoutDownloadPermission(): void {
707
+        $attributes = $this->createMock(IAttributes::class);
708
+        $attributes->expects(self::once())
709
+            ->method('getAttribute')
710
+            ->with('permissions', 'download')
711
+            ->willReturn(false);
712
+
713
+        $share = $this->createMock(IShare::class);
714
+        $share->method('getPassword')->willReturn('password');
715
+        $share->expects(self::once())
716
+            ->method('getPermissions')
717
+            ->willReturn(Constants::PERMISSION_READ);
718
+        $share->expects(self::once())
719
+            ->method('getAttributes')
720
+            ->willReturn($attributes);
721
+
722
+        $this->shareManager
723
+            ->expects(self::once())
724
+            ->method('getShareByToken')
725
+            ->with('validtoken')
726
+            ->willReturn($share);
727
+
728
+        // Test with a password protected share and no authentication
729
+        $response = $this->shareController->downloadShare('validtoken');
730
+        $expectedResponse = new DataResponse('Share has no download permission');
731
+        $this->assertEquals($expectedResponse, $response);
732
+    }
733
+
734
+    public function testDisabledOwner(): void {
735
+        $this->shareController->setToken('token');
736
+
737
+        $owner = $this->getMockBuilder(IUser::class)->getMock();
738
+        $owner->method('isEnabled')->willReturn(false);
739
+
740
+        $initiator = $this->createMock(IUser::class);
741
+        $initiator->method('isEnabled')->willReturn(false);
742
+
743
+        /* @var MockObject|Folder $folder */
744
+        $folder = $this->createMock(Folder::class);
745
+
746
+        $share = Server::get(\OCP\Share\IManager::class)->newShare();
747
+        $share->setId(42);
748
+        $share->setPermissions(Constants::PERMISSION_CREATE)
749
+            ->setShareOwner('ownerUID')
750
+            ->setSharedBy('initiatorUID')
751
+            ->setNode($folder)
752
+            ->setTarget('/share');
753
+
754
+        $this->shareManager
755
+            ->expects($this->once())
756
+            ->method('getShareByToken')
757
+            ->with('token')
758
+            ->willReturn($share);
759
+
760
+        $this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
761
+            if ($uid === 'ownerUID') {
762
+                return $owner;
763
+            }
764
+            if ($uid === 'initiatorUID') {
765
+                return $initiator;
766
+            }
767
+            return null;
768
+        });
769
+
770
+        $this->expectException(NotFoundException::class);
771
+
772
+        $this->shareController->showShare();
773
+    }
774
+
775
+    public function testDisabledInitiator(): void {
776
+        $this->shareController->setToken('token');
777
+
778
+        $owner = $this->getMockBuilder(IUser::class)->getMock();
779
+        $owner->method('isEnabled')->willReturn(false);
780
+
781
+        $initiator = $this->createMock(IUser::class);
782
+        $initiator->method('isEnabled')->willReturn(true);
783
+
784
+        /* @var MockObject|Folder $folder */
785
+        $folder = $this->createMock(Folder::class);
786
+
787
+        $share = Server::get(\OCP\Share\IManager::class)->newShare();
788
+        $share->setId(42);
789
+        $share->setPermissions(Constants::PERMISSION_CREATE)
790
+            ->setShareOwner('ownerUID')
791
+            ->setSharedBy('initiatorUID')
792
+            ->setNode($folder)
793
+            ->setTarget('/share');
794
+
795
+        $this->shareManager
796
+            ->expects($this->once())
797
+            ->method('getShareByToken')
798
+            ->with('token')
799
+            ->willReturn($share);
800
+
801
+        $this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
802
+            if ($uid === 'ownerUID') {
803
+                return $owner;
804
+            }
805
+            if ($uid === 'initiatorUID') {
806
+                return $initiator;
807
+            }
808
+            return null;
809
+        });
810
+
811
+        $this->expectException(NotFoundException::class);
812
+
813
+        $this->shareController->showShare();
814
+    }
815 815
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 			->with('token')
288 288
 			->willReturn($share);
289 289
 
290
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
290
+		$this->userManager->method('get')->willReturnCallback(function(string $uid) use ($owner, $initiator) {
291 291
 			if ($uid === 'ownerUID') {
292 292
 				return $owner;
293 293
 			}
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
 		});
299 299
 
300 300
 		$this->eventDispatcher->method('dispatchTyped')->with(
301
-			$this->callback(function ($event) use ($share) {
301
+			$this->callback(function($event) use ($share) {
302 302
 				if ($event instanceof BeforeTemplateRenderedEvent) {
303 303
 					return $event->getShare() === $share;
304 304
 				} else {
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 
310 310
 		$this->l10n->expects($this->any())
311 311
 			->method('t')
312
-			->willReturnCallback(function ($text, $parameters) {
312
+			->willReturnCallback(function($text, $parameters) {
313 313
 				return vsprintf($text, $parameters);
314 314
 			});
315 315
 
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 		$initialState = [];
325 325
 		$this->initialState->expects(self::any())
326 326
 			->method('provideInitialState')
327
-			->willReturnCallback(function ($key, $value) use (&$initialState): void {
327
+			->willReturnCallback(function($key, $value) use (&$initialState): void {
328 328
 				$initialState[$key] = $value;
329 329
 			});
330 330
 		$expectedInitialState = [
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
 			->with('token')
437 437
 			->willReturn($share);
438 438
 
439
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
439
+		$this->userManager->method('get')->willReturnCallback(function(string $uid) use ($owner, $initiator) {
440 440
 			if ($uid === 'ownerUID') {
441 441
 				return $owner;
442 442
 			}
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
 		});
448 448
 
449 449
 		$this->eventDispatcher->method('dispatchTyped')->with(
450
-			$this->callback(function ($event) use ($share) {
450
+			$this->callback(function($event) use ($share) {
451 451
 				if ($event instanceof BeforeTemplateRenderedEvent) {
452 452
 					return $event->getShare() === $share;
453 453
 				} else {
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 
459 459
 		$this->l10n->expects($this->any())
460 460
 			->method('t')
461
-			->willReturnCallback(function ($text, $parameters) {
461
+			->willReturnCallback(function($text, $parameters) {
462 462
 				return vsprintf($text, $parameters);
463 463
 			});
464 464
 
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
 		$initialState = [];
467 467
 		$this->initialState->expects(self::any())
468 468
 			->method('provideInitialState')
469
-			->willReturnCallback(function ($key, $value) use (&$initialState): void {
469
+			->willReturnCallback(function($key, $value) use (&$initialState): void {
470 470
 				$initialState[$key] = $value;
471 471
 			});
472 472
 		$expectedInitialState = [
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
 			->with('token')
585 585
 			->willReturn($share);
586 586
 
587
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
587
+		$this->userManager->method('get')->willReturnCallback(function(string $uid) use ($owner, $initiator) {
588 588
 			if ($uid === 'ownerUID') {
589 589
 				return $owner;
590 590
 			}
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 		});
596 596
 
597 597
 		$this->eventDispatcher->method('dispatchTyped')->with(
598
-			$this->callback(function ($event) use ($share) {
598
+			$this->callback(function($event) use ($share) {
599 599
 				if ($event instanceof BeforeTemplateRenderedEvent) {
600 600
 					return $event->getShare() === $share;
601 601
 				} else {
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
 
607 607
 		$this->l10n->expects($this->any())
608 608
 			->method('t')
609
-			->will($this->returnCallback(function ($text, $parameters) {
609
+			->will($this->returnCallback(function($text, $parameters) {
610 610
 				return vsprintf($text, $parameters);
611 611
 			}));
612 612
 
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 			->with('token')
758 758
 			->willReturn($share);
759 759
 
760
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
760
+		$this->userManager->method('get')->willReturnCallback(function(string $uid) use ($owner, $initiator) {
761 761
 			if ($uid === 'ownerUID') {
762 762
 				return $owner;
763 763
 			}
@@ -798,7 +798,7 @@  discard block
 block discarded – undo
798 798
 			->with('token')
799 799
 			->willReturn($share);
800 800
 
801
-		$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
801
+		$this->userManager->method('get')->willReturnCallback(function(string $uid) use ($owner, $initiator) {
802 802
 			if ($uid === 'ownerUID') {
803 803
 				return $owner;
804 804
 			}
Please login to merge, or discard this patch.
apps/files_sharing/lib/DefaultPublicShareTemplateProvider.php 2 patches
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -38,222 +38,222 @@
 block discarded – undo
38 38
 
39 39
 class DefaultPublicShareTemplateProvider implements IPublicShareTemplateProvider {
40 40
 
41
-	public function __construct(
42
-		private IUserManager $userManager,
43
-		private IAccountManager $accountManager,
44
-		private IPreview $previewManager,
45
-		protected FederatedShareProvider $federatedShareProvider,
46
-		private IUrlGenerator $urlGenerator,
47
-		private IEventDispatcher $eventDispatcher,
48
-		private IL10N $l10n,
49
-		private Defaults $defaults,
50
-		private IConfig $config,
51
-		private IRequest $request,
52
-		private IInitialState $initialState,
53
-		private IAppConfig $appConfig,
54
-	) {
55
-	}
41
+    public function __construct(
42
+        private IUserManager $userManager,
43
+        private IAccountManager $accountManager,
44
+        private IPreview $previewManager,
45
+        protected FederatedShareProvider $federatedShareProvider,
46
+        private IUrlGenerator $urlGenerator,
47
+        private IEventDispatcher $eventDispatcher,
48
+        private IL10N $l10n,
49
+        private Defaults $defaults,
50
+        private IConfig $config,
51
+        private IRequest $request,
52
+        private IInitialState $initialState,
53
+        private IAppConfig $appConfig,
54
+    ) {
55
+    }
56 56
 
57
-	public function shouldRespond(IShare $share): bool {
58
-		return true;
59
-	}
57
+    public function shouldRespond(IShare $share): bool {
58
+        return true;
59
+    }
60 60
 
61
-	public function renderPage(IShare $share, string $token, string $path): TemplateResponse {
62
-		$shareNode = $share->getNode();
63
-		$ownerName = '';
64
-		$ownerId = '';
61
+    public function renderPage(IShare $share, string $token, string $path): TemplateResponse {
62
+        $shareNode = $share->getNode();
63
+        $ownerName = '';
64
+        $ownerId = '';
65 65
 
66
-		// Only make the share owner public if they allowed to show their name
67
-		$owner = $this->userManager->get($share->getShareOwner());
68
-		if ($owner instanceof IUser) {
69
-			$ownerAccount = $this->accountManager->getAccount($owner);
66
+        // Only make the share owner public if they allowed to show their name
67
+        $owner = $this->userManager->get($share->getShareOwner());
68
+        if ($owner instanceof IUser) {
69
+            $ownerAccount = $this->accountManager->getAccount($owner);
70 70
 
71
-			$ownerNameProperty = $ownerAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME);
72
-			if ($ownerNameProperty->getScope() === IAccountManager::SCOPE_PUBLISHED) {
73
-				$ownerId = $owner->getUID();
74
-				$ownerName = $owner->getDisplayName();
75
-				$this->initialState->provideInitialState('owner', $ownerId);
76
-				$this->initialState->provideInitialState('ownerDisplayName', $ownerName);
77
-			}
78
-		}
71
+            $ownerNameProperty = $ownerAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME);
72
+            if ($ownerNameProperty->getScope() === IAccountManager::SCOPE_PUBLISHED) {
73
+                $ownerId = $owner->getUID();
74
+                $ownerName = $owner->getDisplayName();
75
+                $this->initialState->provideInitialState('owner', $ownerId);
76
+                $this->initialState->provideInitialState('ownerDisplayName', $ownerName);
77
+            }
78
+        }
79 79
 
80
-		$view = 'public-share';
81
-		if ($shareNode instanceof File) {
82
-			$view = 'public-file-share';
83
-			$this->initialState->provideInitialState('fileId', $shareNode->getId());
84
-		} elseif (($share->getPermissions() & Constants::PERMISSION_CREATE)
85
-			&& !($share->getPermissions() & Constants::PERMISSION_READ)
86
-		) {
87
-			// share is a folder with create but no read permissions -> file drop only
88
-			$view = 'public-file-drop';
89
-			// Only needed for file drops
90
-			$this->initialState->provideInitialState(
91
-				'disclaimer',
92
-				$this->appConfig->getValueString('core', 'shareapi_public_link_disclaimertext'),
93
-			);
94
-		}
95
-		// Set up initial state
96
-		$this->initialState->provideInitialState('isPublic', true);
97
-		$this->initialState->provideInitialState('sharingToken', $token);
98
-		$this->initialState->provideInitialState('sharePermissions', $share->getPermissions());
99
-		$this->initialState->provideInitialState('filename', $shareNode->getName());
100
-		$this->initialState->provideInitialState('view', $view);
80
+        $view = 'public-share';
81
+        if ($shareNode instanceof File) {
82
+            $view = 'public-file-share';
83
+            $this->initialState->provideInitialState('fileId', $shareNode->getId());
84
+        } elseif (($share->getPermissions() & Constants::PERMISSION_CREATE)
85
+            && !($share->getPermissions() & Constants::PERMISSION_READ)
86
+        ) {
87
+            // share is a folder with create but no read permissions -> file drop only
88
+            $view = 'public-file-drop';
89
+            // Only needed for file drops
90
+            $this->initialState->provideInitialState(
91
+                'disclaimer',
92
+                $this->appConfig->getValueString('core', 'shareapi_public_link_disclaimertext'),
93
+            );
94
+        }
95
+        // Set up initial state
96
+        $this->initialState->provideInitialState('isPublic', true);
97
+        $this->initialState->provideInitialState('sharingToken', $token);
98
+        $this->initialState->provideInitialState('sharePermissions', $share->getPermissions());
99
+        $this->initialState->provideInitialState('filename', $shareNode->getName());
100
+        $this->initialState->provideInitialState('view', $view);
101 101
 
102
-		// Load scripts and styles for UI
103
-		Util::addInitScript('files', 'init');
104
-		Util::addInitScript(Application::APP_ID, 'init');
105
-		Util::addInitScript(Application::APP_ID, 'init-public');
106
-		Util::addScript('files', 'main');
102
+        // Load scripts and styles for UI
103
+        Util::addInitScript('files', 'init');
104
+        Util::addInitScript(Application::APP_ID, 'init');
105
+        Util::addInitScript(Application::APP_ID, 'init-public');
106
+        Util::addScript('files', 'main');
107 107
 
108
-		// Add file-request script if needed
109
-		$attributes = $share->getAttributes();
110
-		$isFileRequest = $attributes?->getAttribute('fileRequest', 'enabled') === true;
111
-		if ($isFileRequest) {
112
-			Util::addScript(Application::APP_ID, 'public-file-request');
113
-		}
108
+        // Add file-request script if needed
109
+        $attributes = $share->getAttributes();
110
+        $isFileRequest = $attributes?->getAttribute('fileRequest', 'enabled') === true;
111
+        if ($isFileRequest) {
112
+            Util::addScript(Application::APP_ID, 'public-file-request');
113
+        }
114 114
 
115
-		// Load Viewer scripts
116
-		if (class_exists(LoadViewer::class)) {
117
-			$this->eventDispatcher->dispatchTyped(new LoadViewer());
118
-		}
115
+        // Load Viewer scripts
116
+        if (class_exists(LoadViewer::class)) {
117
+            $this->eventDispatcher->dispatchTyped(new LoadViewer());
118
+        }
119 119
 
120
-		// Allow external apps to register their scripts
121
-		$this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($share));
120
+        // Allow external apps to register their scripts
121
+        $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($share));
122 122
 
123
-		$this->addMetaHeaders($share);
123
+        $this->addMetaHeaders($share);
124 124
 
125
-		// CSP to allow office
126
-		$csp = new ContentSecurityPolicy();
127
-		$csp->addAllowedFrameDomain('\'self\'');
125
+        // CSP to allow office
126
+        $csp = new ContentSecurityPolicy();
127
+        $csp->addAllowedFrameDomain('\'self\'');
128 128
 
129
-		$response = new PublicTemplateResponse(
130
-			'files',
131
-			'index',
132
-		);
133
-		$response->setContentSecurityPolicy($csp);
129
+        $response = new PublicTemplateResponse(
130
+            'files',
131
+            'index',
132
+        );
133
+        $response->setContentSecurityPolicy($csp);
134 134
 
135
-		// If the share has a label, use it as the title
136
-		if ($share->getLabel() !== '') {
137
-			$response->setHeaderTitle($share->getLabel());
138
-			$response->setParams(['pageTitle' => $share->getLabel()]);
139
-		} else {
140
-			$response->setHeaderTitle($shareNode->getName());
141
-			$response->setParams(['pageTitle' => $shareNode->getName()]);
142
-		}
135
+        // If the share has a label, use it as the title
136
+        if ($share->getLabel() !== '') {
137
+            $response->setHeaderTitle($share->getLabel());
138
+            $response->setParams(['pageTitle' => $share->getLabel()]);
139
+        } else {
140
+            $response->setHeaderTitle($shareNode->getName());
141
+            $response->setParams(['pageTitle' => $shareNode->getName()]);
142
+        }
143 143
 
144
-		if ($ownerName !== '') {
145
-			$response->setHeaderDetails($this->l10n->t('shared by %s', [$ownerName]));
146
-		}
144
+        if ($ownerName !== '') {
145
+            $response->setHeaderDetails($this->l10n->t('shared by %s', [$ownerName]));
146
+        }
147 147
 
148
-		// Create the header action menu
149
-		$headerActions = [];
150
-		if ($view !== 'public-file-drop' && !$share->getHideDownload()) {
151
-			// The download URL is used for the "download" header action as well as in some cases for the direct link
152
-			$downloadUrl = $this->urlGenerator->getAbsoluteURL('/public.php/dav/files/' . $token . '/?accept=zip');
148
+        // Create the header action menu
149
+        $headerActions = [];
150
+        if ($view !== 'public-file-drop' && !$share->getHideDownload()) {
151
+            // The download URL is used for the "download" header action as well as in some cases for the direct link
152
+            $downloadUrl = $this->urlGenerator->getAbsoluteURL('/public.php/dav/files/' . $token . '/?accept=zip');
153 153
 
154
-			// If not a file drop, then add the download header action
155
-			$headerActions[] = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $downloadUrl, 0, (string)$shareNode->getSize());
154
+            // If not a file drop, then add the download header action
155
+            $headerActions[] = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $downloadUrl, 0, (string)$shareNode->getSize());
156 156
 
157
-			// If remote sharing is enabled also add the remote share action to the menu
158
-			if ($this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
159
-				$headerActions[] = new ExternalShareMenuAction(
160
-					// TRANSLATORS The placeholder refers to the software product name as in 'Add to your Nextcloud'
161
-					$this->l10n->t('Add to your %s', [$this->defaults->getProductName()]),
162
-					'icon-external',
163
-					$ownerId,
164
-					$ownerName,
165
-					$shareNode->getName(),
166
-				);
167
-			}
168
-		}
157
+            // If remote sharing is enabled also add the remote share action to the menu
158
+            if ($this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
159
+                $headerActions[] = new ExternalShareMenuAction(
160
+                    // TRANSLATORS The placeholder refers to the software product name as in 'Add to your Nextcloud'
161
+                    $this->l10n->t('Add to your %s', [$this->defaults->getProductName()]),
162
+                    'icon-external',
163
+                    $ownerId,
164
+                    $ownerName,
165
+                    $shareNode->getName(),
166
+                );
167
+            }
168
+        }
169 169
 
170
-		$shareUrl = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
171
-		// By default use the share link as the direct link
172
-		$directLink = $shareUrl;
173
-		// Add the direct link header actions
174
-		if ($shareNode->getMimePart() === 'image') {
175
-			// If this is a file and especially an image directly point to the image preview
176
-			$directLink = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
177
-		} elseif (($share->getPermissions() & Constants::PERMISSION_READ) && !$share->getHideDownload()) {
178
-			// Can read and no download restriction, so just download it
179
-			$directLink = $downloadUrl ?? $shareUrl;
180
-		}
181
-		$headerActions[] = new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $directLink);
182
-		$response->setHeaderActions($headerActions);
170
+        $shareUrl = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
171
+        // By default use the share link as the direct link
172
+        $directLink = $shareUrl;
173
+        // Add the direct link header actions
174
+        if ($shareNode->getMimePart() === 'image') {
175
+            // If this is a file and especially an image directly point to the image preview
176
+            $directLink = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
177
+        } elseif (($share->getPermissions() & Constants::PERMISSION_READ) && !$share->getHideDownload()) {
178
+            // Can read and no download restriction, so just download it
179
+            $directLink = $downloadUrl ?? $shareUrl;
180
+        }
181
+        $headerActions[] = new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $directLink);
182
+        $response->setHeaderActions($headerActions);
183 183
 
184
-		return $response;
185
-	}
184
+        return $response;
185
+    }
186 186
 
187
-	/**
188
-	 * Add OpenGraph headers to response for preview
189
-	 * @param IShare $share The share for which to add the headers
190
-	 */
191
-	protected function addMetaHeaders(IShare $share): void {
192
-		$shareNode = $share->getNode();
193
-		$token = $share->getToken();
194
-		$shareUrl = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
187
+    /**
188
+     * Add OpenGraph headers to response for preview
189
+     * @param IShare $share The share for which to add the headers
190
+     */
191
+    protected function addMetaHeaders(IShare $share): void {
192
+        $shareNode = $share->getNode();
193
+        $token = $share->getToken();
194
+        $shareUrl = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
195 195
 
196
-		// Handle preview generation for OpenGraph
197
-		$hasImagePreview = false;
198
-		if ($this->previewManager->isMimeSupported($shareNode->getMimetype())) {
199
-			// For images we can use direct links
200
-			if ($shareNode->getMimePart() === 'image') {
201
-				$hasImagePreview = true;
202
-				$ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
203
-				// Whatsapp is kind of picky about their size requirements
204
-				if ($this->request->isUserAgent(['/^WhatsApp/'])) {
205
-					$ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
206
-						'token' => $token,
207
-						'x' => 256,
208
-						'y' => 256,
209
-						'a' => true,
210
-					]);
211
-				}
212
-			} else {
213
-				// For normal files use preview API
214
-				$ogPreview = $this->urlGenerator->linkToRouteAbsolute(
215
-					'files_sharing.PublicPreview.getPreview',
216
-					[
217
-						'x' => 256,
218
-						'y' => 256,
219
-						'file' => $share->getTarget(),
220
-						'token' => $token,
221
-					],
222
-				);
223
-			}
224
-		} else {
225
-			// No preview supported, so we just add the favicon
226
-			$ogPreview = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
227
-		}
196
+        // Handle preview generation for OpenGraph
197
+        $hasImagePreview = false;
198
+        if ($this->previewManager->isMimeSupported($shareNode->getMimetype())) {
199
+            // For images we can use direct links
200
+            if ($shareNode->getMimePart() === 'image') {
201
+                $hasImagePreview = true;
202
+                $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
203
+                // Whatsapp is kind of picky about their size requirements
204
+                if ($this->request->isUserAgent(['/^WhatsApp/'])) {
205
+                    $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
206
+                        'token' => $token,
207
+                        'x' => 256,
208
+                        'y' => 256,
209
+                        'a' => true,
210
+                    ]);
211
+                }
212
+            } else {
213
+                // For normal files use preview API
214
+                $ogPreview = $this->urlGenerator->linkToRouteAbsolute(
215
+                    'files_sharing.PublicPreview.getPreview',
216
+                    [
217
+                        'x' => 256,
218
+                        'y' => 256,
219
+                        'file' => $share->getTarget(),
220
+                        'token' => $token,
221
+                    ],
222
+                );
223
+            }
224
+        } else {
225
+            // No preview supported, so we just add the favicon
226
+            $ogPreview = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
227
+        }
228 228
 
229
-		$title = $shareNode->getName();
230
-		$siteName = $this->defaults->getName();
231
-		$description = $siteName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '');
229
+        $title = $shareNode->getName();
230
+        $siteName = $this->defaults->getName();
231
+        $description = $siteName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '');
232 232
 
233
-		// OpenGraph Support: http://ogp.me/
234
-		Util::addHeader('meta', ['property' => 'og:title', 'content' => $title]);
235
-		Util::addHeader('meta', ['property' => 'og:description', 'content' => $description]);
236
-		Util::addHeader('meta', ['property' => 'og:site_name', 'content' => $siteName]);
237
-		Util::addHeader('meta', ['property' => 'og:url', 'content' => $shareUrl]);
238
-		Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
239
-		Util::addHeader('meta', ['property' => 'og:image', 'content' => $ogPreview]); // recommended to always have the image
240
-		if ($shareNode->getMimePart() === 'image') {
241
-			Util::addHeader('meta', ['property' => 'og:image:type', 'content' => $shareNode->getMimeType()]);
242
-		} elseif ($shareNode->getMimePart() === 'audio') {
243
-			$audio = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadshare', ['token' => $token]);
244
-			Util::addHeader('meta', ['property' => 'og:audio', 'content' => $audio]);
245
-			Util::addHeader('meta', ['property' => 'og:audio:type', 'content' => $shareNode->getMimeType()]);
246
-		} elseif ($shareNode->getMimePart() === 'video') {
247
-			$video = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadshare', ['token' => $token]);
248
-			Util::addHeader('meta', ['property' => 'og:video', 'content' => $video]);
249
-			Util::addHeader('meta', ['property' => 'og:video:type', 'content' => $shareNode->getMimeType()]);
250
-		}
233
+        // OpenGraph Support: http://ogp.me/
234
+        Util::addHeader('meta', ['property' => 'og:title', 'content' => $title]);
235
+        Util::addHeader('meta', ['property' => 'og:description', 'content' => $description]);
236
+        Util::addHeader('meta', ['property' => 'og:site_name', 'content' => $siteName]);
237
+        Util::addHeader('meta', ['property' => 'og:url', 'content' => $shareUrl]);
238
+        Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
239
+        Util::addHeader('meta', ['property' => 'og:image', 'content' => $ogPreview]); // recommended to always have the image
240
+        if ($shareNode->getMimePart() === 'image') {
241
+            Util::addHeader('meta', ['property' => 'og:image:type', 'content' => $shareNode->getMimeType()]);
242
+        } elseif ($shareNode->getMimePart() === 'audio') {
243
+            $audio = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadshare', ['token' => $token]);
244
+            Util::addHeader('meta', ['property' => 'og:audio', 'content' => $audio]);
245
+            Util::addHeader('meta', ['property' => 'og:audio:type', 'content' => $shareNode->getMimeType()]);
246
+        } elseif ($shareNode->getMimePart() === 'video') {
247
+            $video = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadshare', ['token' => $token]);
248
+            Util::addHeader('meta', ['property' => 'og:video', 'content' => $video]);
249
+            Util::addHeader('meta', ['property' => 'og:video:type', 'content' => $shareNode->getMimeType()]);
250
+        }
251 251
 
252 252
 
253
-		// Twitter Support: https://developer.x.com/en/docs/x-for-websites/cards/overview/markup
254
-		Util::addHeader('meta', ['property' => 'twitter:title', 'content' => $title]);
255
-		Util::addHeader('meta', ['property' => 'twitter:description', 'content' => $description]);
256
-		Util::addHeader('meta', ['property' => 'twitter:card', 'content' => $hasImagePreview ? 'summary_large_image' : 'summary']);
257
-		Util::addHeader('meta', ['property' => 'twitter:image', 'content' => $ogPreview]);
258
-	}
253
+        // Twitter Support: https://developer.x.com/en/docs/x-for-websites/cards/overview/markup
254
+        Util::addHeader('meta', ['property' => 'twitter:title', 'content' => $title]);
255
+        Util::addHeader('meta', ['property' => 'twitter:description', 'content' => $description]);
256
+        Util::addHeader('meta', ['property' => 'twitter:card', 'content' => $hasImagePreview ? 'summary_large_image' : 'summary']);
257
+        Util::addHeader('meta', ['property' => 'twitter:image', 'content' => $ogPreview]);
258
+    }
259 259
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -149,10 +149,10 @@  discard block
 block discarded – undo
149 149
 		$headerActions = [];
150 150
 		if ($view !== 'public-file-drop' && !$share->getHideDownload()) {
151 151
 			// The download URL is used for the "download" header action as well as in some cases for the direct link
152
-			$downloadUrl = $this->urlGenerator->getAbsoluteURL('/public.php/dav/files/' . $token . '/?accept=zip');
152
+			$downloadUrl = $this->urlGenerator->getAbsoluteURL('/public.php/dav/files/'.$token.'/?accept=zip');
153 153
 
154 154
 			// If not a file drop, then add the download header action
155
-			$headerActions[] = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $downloadUrl, 0, (string)$shareNode->getSize());
155
+			$headerActions[] = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $downloadUrl, 0, (string) $shareNode->getSize());
156 156
 
157 157
 			// If remote sharing is enabled also add the remote share action to the menu
158 158
 			if ($this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 
229 229
 		$title = $shareNode->getName();
230 230
 		$siteName = $this->defaults->getName();
231
-		$description = $siteName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '');
231
+		$description = $siteName.($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : '');
232 232
 
233 233
 		// OpenGraph Support: http://ogp.me/
234 234
 		Util::addHeader('meta', ['property' => 'og:title', 'content' => $title]);
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1150 added lines, -1150 removed lines patch added patch discarded remove patch
@@ -39,1156 +39,1156 @@
 block discarded – undo
39 39
  * OC_autoload!
40 40
  */
41 41
 class OC {
42
-	/**
43
-	 * Associative array for autoloading. classname => filename
44
-	 */
45
-	public static array $CLASSPATH = [];
46
-	/**
47
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
48
-	 */
49
-	public static string $SERVERROOT = '';
50
-	/**
51
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
52
-	 */
53
-	private static string $SUBURI = '';
54
-	/**
55
-	 * the Nextcloud root path for http requests (e.g. /nextcloud)
56
-	 */
57
-	public static string $WEBROOT = '';
58
-	/**
59
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
60
-	 * web path in 'url'
61
-	 */
62
-	public static array $APPSROOTS = [];
63
-
64
-	public static string $configDir;
65
-
66
-	/**
67
-	 * requested app
68
-	 */
69
-	public static string $REQUESTEDAPP = '';
70
-
71
-	/**
72
-	 * check if Nextcloud runs in cli mode
73
-	 */
74
-	public static bool $CLI = false;
75
-
76
-	public static \OC\Autoloader $loader;
77
-
78
-	public static \Composer\Autoload\ClassLoader $composerAutoloader;
79
-
80
-	public static \OC\Server $server;
81
-
82
-	private static \OC\Config $config;
83
-
84
-	/**
85
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
86
-	 *                           the app path list is empty or contains an invalid path
87
-	 */
88
-	public static function initPaths(): void {
89
-		if (defined('PHPUNIT_CONFIG_DIR')) {
90
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
91
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
92
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
93
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
94
-			self::$configDir = rtrim($dir, '/') . '/';
95
-		} else {
96
-			self::$configDir = OC::$SERVERROOT . '/config/';
97
-		}
98
-		self::$config = new \OC\Config(self::$configDir);
99
-
100
-		OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT)));
101
-		/**
102
-		 * FIXME: The following lines are required because we can't yet instantiate
103
-		 *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
104
-		 */
105
-		$params = [
106
-			'server' => [
107
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
108
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
109
-			],
110
-		];
111
-		if (isset($_SERVER['REMOTE_ADDR'])) {
112
-			$params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
113
-		}
114
-		$fakeRequest = new \OC\AppFramework\Http\Request(
115
-			$params,
116
-			new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
117
-			new \OC\AllConfig(new \OC\SystemConfig(self::$config))
118
-		);
119
-		$scriptName = $fakeRequest->getScriptName();
120
-		if (substr($scriptName, -1) == '/') {
121
-			$scriptName .= 'index.php';
122
-			//make sure suburi follows the same rules as scriptName
123
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
124
-				if (substr(OC::$SUBURI, -1) != '/') {
125
-					OC::$SUBURI = OC::$SUBURI . '/';
126
-				}
127
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
128
-			}
129
-		}
130
-
131
-		if (OC::$CLI) {
132
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
133
-		} else {
134
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
135
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
136
-
137
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
138
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
139
-				}
140
-			} else {
141
-				// The scriptName is not ending with OC::$SUBURI
142
-				// This most likely means that we are calling from CLI.
143
-				// However some cron jobs still need to generate
144
-				// a web URL, so we use overwritewebroot as a fallback.
145
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
146
-			}
147
-
148
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
149
-			// slash which is required by URL generation.
150
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
151
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
152
-				header('Location: ' . \OC::$WEBROOT . '/');
153
-				exit();
154
-			}
155
-		}
156
-
157
-		// search the apps folder
158
-		$config_paths = self::$config->getValue('apps_paths', []);
159
-		if (!empty($config_paths)) {
160
-			foreach ($config_paths as $paths) {
161
-				if (isset($paths['url']) && isset($paths['path'])) {
162
-					$paths['url'] = rtrim($paths['url'], '/');
163
-					$paths['path'] = rtrim($paths['path'], '/');
164
-					OC::$APPSROOTS[] = $paths;
165
-				}
166
-			}
167
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
168
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
169
-		}
170
-
171
-		if (empty(OC::$APPSROOTS)) {
172
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
173
-				. '. You can also configure the location in the config.php file.');
174
-		}
175
-		$paths = [];
176
-		foreach (OC::$APPSROOTS as $path) {
177
-			$paths[] = $path['path'];
178
-			if (!is_dir($path['path'])) {
179
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
180
-					. ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
181
-			}
182
-		}
183
-
184
-		// set the right include path
185
-		set_include_path(
186
-			implode(PATH_SEPARATOR, $paths)
187
-		);
188
-	}
189
-
190
-	public static function checkConfig(): void {
191
-		// Create config if it does not already exist
192
-		$configFilePath = self::$configDir . '/config.php';
193
-		if (!file_exists($configFilePath)) {
194
-			@touch($configFilePath);
195
-		}
196
-
197
-		// Check if config is writable
198
-		$configFileWritable = is_writable($configFilePath);
199
-		$configReadOnly = Server::get(IConfig::class)->getSystemValueBool('config_is_read_only');
200
-		if (!$configFileWritable && !$configReadOnly
201
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
202
-			$urlGenerator = Server::get(IURLGenerator::class);
203
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
204
-
205
-			if (self::$CLI) {
206
-				echo $l->t('Cannot write into "config" directory!') . "\n";
207
-				echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n";
208
-				echo "\n";
209
-				echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n";
210
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n";
211
-				exit;
212
-			} else {
213
-				Server::get(ITemplateManager::class)->printErrorPage(
214
-					$l->t('Cannot write into "config" directory!'),
215
-					$l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
216
-					. $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
217
-					. $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
218
-					503
219
-				);
220
-			}
221
-		}
222
-	}
223
-
224
-	public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
225
-		if (defined('OC_CONSOLE')) {
226
-			return;
227
-		}
228
-		// Redirect to installer if not installed
229
-		if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
230
-			if (OC::$CLI) {
231
-				throw new Exception('Not installed');
232
-			} else {
233
-				$url = OC::$WEBROOT . '/index.php';
234
-				header('Location: ' . $url);
235
-			}
236
-			exit();
237
-		}
238
-	}
239
-
240
-	public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
241
-		// Allow ajax update script to execute without being stopped
242
-		if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
243
-			// send http status 503
244
-			http_response_code(503);
245
-			header('X-Nextcloud-Maintenance-Mode: 1');
246
-			header('Retry-After: 120');
247
-
248
-			// render error page
249
-			$template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest');
250
-			\OCP\Util::addScript('core', 'maintenance');
251
-			\OCP\Util::addStyle('core', 'guest');
252
-			$template->printPage();
253
-			die();
254
-		}
255
-	}
256
-
257
-	/**
258
-	 * Prints the upgrade page
259
-	 */
260
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
261
-		$cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', '');
262
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
263
-		$tooBig = false;
264
-		if (!$disableWebUpdater) {
265
-			$apps = Server::get(\OCP\App\IAppManager::class);
266
-			if ($apps->isEnabledForAnyone('user_ldap')) {
267
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
268
-
269
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
270
-					->from('ldap_user_mapping')
271
-					->executeQuery();
272
-				$row = $result->fetch();
273
-				$result->closeCursor();
274
-
275
-				$tooBig = ($row['user_count'] > 50);
276
-			}
277
-			if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) {
278
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
279
-
280
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
281
-					->from('user_saml_users')
282
-					->executeQuery();
283
-				$row = $result->fetch();
284
-				$result->closeCursor();
285
-
286
-				$tooBig = ($row['user_count'] > 50);
287
-			}
288
-			if (!$tooBig) {
289
-				// count users
290
-				$totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51);
291
-				$tooBig = ($totalUsers > 50);
292
-			}
293
-		}
294
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
295
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
296
-
297
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
298
-			// send http status 503
299
-			http_response_code(503);
300
-			header('Retry-After: 120');
301
-
302
-			$serverVersion = \OCP\Server::get(\OCP\ServerVersion::class);
303
-
304
-			// render error page
305
-			$template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest');
306
-			$template->assign('productName', 'nextcloud'); // for now
307
-			$template->assign('version', $serverVersion->getVersionString());
308
-			$template->assign('tooBig', $tooBig);
309
-			$template->assign('cliUpgradeLink', $cliUpgradeLink);
310
-
311
-			$template->printPage();
312
-			die();
313
-		}
314
-
315
-		// check whether this is a core update or apps update
316
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
317
-		$currentVersion = implode('.', \OCP\Util::getVersion());
318
-
319
-		// if not a core upgrade, then it's apps upgrade
320
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
321
-
322
-		$oldTheme = $systemConfig->getValue('theme');
323
-		$systemConfig->setValue('theme', '');
324
-		\OCP\Util::addScript('core', 'common');
325
-		\OCP\Util::addScript('core', 'main');
326
-		\OCP\Util::addTranslations('core');
327
-		\OCP\Util::addScript('core', 'update');
328
-
329
-		/** @var \OC\App\AppManager $appManager */
330
-		$appManager = Server::get(\OCP\App\IAppManager::class);
331
-
332
-		$tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest');
333
-		$tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString());
334
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
335
-
336
-		// get third party apps
337
-		$ocVersion = \OCP\Util::getVersion();
338
-		$ocVersion = implode('.', $ocVersion);
339
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
340
-		$incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []);
341
-		$incompatibleShippedApps = [];
342
-		$incompatibleDisabledApps = [];
343
-		foreach ($incompatibleApps as $appInfo) {
344
-			if ($appManager->isShipped($appInfo['id'])) {
345
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
346
-			}
347
-			if (!in_array($appInfo['id'], $incompatibleOverwrites)) {
348
-				$incompatibleDisabledApps[] = $appInfo;
349
-			}
350
-		}
351
-
352
-		if (!empty($incompatibleShippedApps)) {
353
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('core');
354
-			$hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
355
-			throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
356
-		}
357
-
358
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
359
-		$tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps);
360
-		try {
361
-			$defaults = new \OC_Defaults();
362
-			$tmpl->assign('productName', $defaults->getName());
363
-		} catch (Throwable $error) {
364
-			$tmpl->assign('productName', 'Nextcloud');
365
-		}
366
-		$tmpl->assign('oldTheme', $oldTheme);
367
-		$tmpl->printPage();
368
-	}
369
-
370
-	public static function initSession(): void {
371
-		$request = Server::get(IRequest::class);
372
-
373
-		// TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
374
-		// TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
375
-		// TODO: for further information.
376
-		// $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
377
-		// if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
378
-		// setcookie('cookie_test', 'test', time() + 3600);
379
-		// // Do not initialize the session if a request is authenticated directly
380
-		// // unless there is a session cookie already sent along
381
-		// return;
382
-		// }
383
-
384
-		if ($request->getServerProtocol() === 'https') {
385
-			ini_set('session.cookie_secure', 'true');
386
-		}
387
-
388
-		// prevents javascript from accessing php session cookies
389
-		ini_set('session.cookie_httponly', 'true');
390
-
391
-		// Do not initialize sessions for 'status.php' requests
392
-		// Monitoring endpoints can quickly flood session handlers
393
-		// and 'status.php' doesn't require sessions anyway
394
-		if (str_ends_with($request->getScriptName(), '/status.php')) {
395
-			return;
396
-		}
397
-
398
-		// set the cookie path to the Nextcloud directory
399
-		$cookie_path = OC::$WEBROOT ? : '/';
400
-		ini_set('session.cookie_path', $cookie_path);
401
-
402
-		// Let the session name be changed in the initSession Hook
403
-		$sessionName = OC_Util::getInstanceId();
404
-
405
-		try {
406
-			$logger = null;
407
-			if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) {
408
-				$logger = logger('core');
409
-			}
410
-
411
-			// set the session name to the instance id - which is unique
412
-			$session = new \OC\Session\Internal(
413
-				$sessionName,
414
-				$logger,
415
-			);
416
-
417
-			$cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
418
-			$session = $cryptoWrapper->wrapSession($session);
419
-			self::$server->setSession($session);
420
-
421
-			// if session can't be started break with http 500 error
422
-		} catch (Exception $e) {
423
-			Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
424
-			//show the user a detailed error page
425
-			Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500);
426
-			die();
427
-		}
428
-
429
-		//try to set the session lifetime
430
-		$sessionLifeTime = self::getSessionLifeTime();
431
-
432
-		// session timeout
433
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
-			if (isset($_COOKIE[session_name()])) {
435
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
436
-			}
437
-			Server::get(IUserSession::class)->logout();
438
-		}
439
-
440
-		if (!self::hasSessionRelaxedExpiry()) {
441
-			$session->set('LAST_ACTIVITY', time());
442
-		}
443
-		$session->close();
444
-	}
445
-
446
-	private static function getSessionLifeTime(): int {
447
-		return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
448
-	}
449
-
450
-	/**
451
-	 * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
452
-	 */
453
-	public static function hasSessionRelaxedExpiry(): bool {
454
-		return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
455
-	}
456
-
457
-	/**
458
-	 * Try to set some values to the required Nextcloud default
459
-	 */
460
-	public static function setRequiredIniValues(): void {
461
-		// Don't display errors and log them
462
-		@ini_set('display_errors', '0');
463
-		@ini_set('log_errors', '1');
464
-
465
-		// Try to configure php to enable big file uploads.
466
-		// This doesn't work always depending on the webserver and php configuration.
467
-		// Let's try to overwrite some defaults if they are smaller than 1 hour
468
-
469
-		if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
470
-			@ini_set('max_execution_time', strval(3600));
471
-		}
472
-
473
-		if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
474
-			@ini_set('max_input_time', strval(3600));
475
-		}
476
-
477
-		// Try to set the maximum execution time to the largest time limit we have
478
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
479
-			@set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
480
-		}
481
-
482
-		@ini_set('default_charset', 'UTF-8');
483
-		@ini_set('gd.jpeg_ignore_warning', '1');
484
-	}
485
-
486
-	/**
487
-	 * Send the same site cookies
488
-	 */
489
-	private static function sendSameSiteCookies(): void {
490
-		$cookieParams = session_get_cookie_params();
491
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
492
-		$policies = [
493
-			'lax',
494
-			'strict',
495
-		];
496
-
497
-		// Append __Host to the cookie if it meets the requirements
498
-		$cookiePrefix = '';
499
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
500
-			$cookiePrefix = '__Host-';
501
-		}
502
-
503
-		foreach ($policies as $policy) {
504
-			header(
505
-				sprintf(
506
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507
-					$cookiePrefix,
508
-					$policy,
509
-					$cookieParams['path'],
510
-					$policy
511
-				),
512
-				false
513
-			);
514
-		}
515
-	}
516
-
517
-	/**
518
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
519
-	 * be set in every request if cookies are sent to add a second level of
520
-	 * defense against CSRF.
521
-	 *
522
-	 * If the cookie is not sent this will set the cookie and reload the page.
523
-	 * We use an additional cookie since we want to protect logout CSRF and
524
-	 * also we can't directly interfere with PHP's session mechanism.
525
-	 */
526
-	private static function performSameSiteCookieProtection(IConfig $config): void {
527
-		$request = Server::get(IRequest::class);
528
-
529
-		// Some user agents are notorious and don't really properly follow HTTP
530
-		// specifications. For those, have an automated opt-out. Since the protection
531
-		// for remote.php is applied in base.php as starting point we need to opt out
532
-		// here.
533
-		$incompatibleUserAgents = $config->getSystemValue('csrf.optout');
534
-
535
-		// Fallback, if csrf.optout is unset
536
-		if (!is_array($incompatibleUserAgents)) {
537
-			$incompatibleUserAgents = [
538
-				// OS X Finder
539
-				'/^WebDAVFS/',
540
-				// Windows webdav drive
541
-				'/^Microsoft-WebDAV-MiniRedir/',
542
-			];
543
-		}
544
-
545
-		if ($request->isUserAgent($incompatibleUserAgents)) {
546
-			return;
547
-		}
548
-
549
-		if (count($_COOKIE) > 0) {
550
-			$requestUri = $request->getScriptName();
551
-			$processingScript = explode('/', $requestUri);
552
-			$processingScript = $processingScript[count($processingScript) - 1];
553
-
554
-			if ($processingScript === 'index.php' // index.php routes are handled in the middleware
555
-				|| $processingScript === 'cron.php' // and cron.php does not need any authentication at all
556
-				|| $processingScript === 'public.php' // For public.php, auth for password protected shares is done in the PublicAuth plugin
557
-			) {
558
-				return;
559
-			}
560
-
561
-			// All other endpoints require the lax and the strict cookie
562
-			if (!$request->passesStrictCookieCheck()) {
563
-				logger('core')->warning('Request does not pass strict cookie check');
564
-				self::sendSameSiteCookies();
565
-				// Debug mode gets access to the resources without strict cookie
566
-				// due to the fact that the SabreDAV browser also lives there.
567
-				if (!$config->getSystemValueBool('debug', false)) {
568
-					http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
569
-					header('Content-Type: application/json');
570
-					echo json_encode(['error' => 'Strict Cookie has not been found in request']);
571
-					exit();
572
-				}
573
-			}
574
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
575
-			self::sendSameSiteCookies();
576
-		}
577
-	}
578
-
579
-	public static function init(): void {
580
-		// First handle PHP configuration and copy auth headers to the expected
581
-		// $_SERVER variable before doing anything Server object related
582
-		self::setRequiredIniValues();
583
-		self::handleAuthHeaders();
584
-
585
-		// prevent any XML processing from loading external entities
586
-		libxml_set_external_entity_loader(static function () {
587
-			return null;
588
-		});
589
-
590
-		// Set default timezone before the Server object is booted
591
-		if (!date_default_timezone_set('UTC')) {
592
-			throw new \RuntimeException('Could not set timezone to UTC');
593
-		}
594
-
595
-		// calculate the root directories
596
-		OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4));
597
-
598
-		// register autoloader
599
-		$loaderStart = microtime(true);
600
-		require_once __DIR__ . '/autoloader.php';
601
-		self::$loader = new \OC\Autoloader([
602
-			OC::$SERVERROOT . '/lib/private/legacy',
603
-		]);
604
-		if (defined('PHPUNIT_RUN')) {
605
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
606
-		}
607
-		spl_autoload_register([self::$loader, 'load']);
608
-		$loaderEnd = microtime(true);
609
-
610
-		self::$CLI = (php_sapi_name() == 'cli');
611
-
612
-		// Add default composer PSR-4 autoloader, ensure apcu to be disabled
613
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
614
-		self::$composerAutoloader->setApcuPrefix(null);
615
-
616
-
617
-		try {
618
-			self::initPaths();
619
-			// setup 3rdparty autoloader
620
-			$vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
621
-			if (!file_exists($vendorAutoLoad)) {
622
-				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".');
623
-			}
624
-			require_once $vendorAutoLoad;
625
-		} catch (\RuntimeException $e) {
626
-			if (!self::$CLI) {
627
-				http_response_code(503);
628
-			}
629
-			// we can't use the template error page here, because this needs the
630
-			// DI container which isn't available yet
631
-			print($e->getMessage());
632
-			exit();
633
-		}
634
-
635
-		// setup the basic server
636
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
637
-		self::$server->boot();
638
-
639
-		try {
640
-			$profiler = new BuiltInProfiler(
641
-				Server::get(IConfig::class),
642
-				Server::get(IRequest::class),
643
-			);
644
-			$profiler->start();
645
-		} catch (\Throwable $e) {
646
-			logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
647
-		}
648
-
649
-		if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
650
-			\OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
651
-		}
652
-
653
-		$eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
654
-		$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
655
-		$eventLogger->start('boot', 'Initialize');
656
-
657
-		// Override php.ini and log everything if we're troubleshooting
658
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
659
-			error_reporting(E_ALL);
660
-		}
661
-
662
-		$systemConfig = Server::get(\OC\SystemConfig::class);
663
-		self::registerAutoloaderCache($systemConfig);
664
-
665
-		// initialize intl fallback if necessary
666
-		OC_Util::isSetLocaleWorking();
667
-
668
-		$config = Server::get(IConfig::class);
669
-		if (!defined('PHPUNIT_RUN')) {
670
-			$errorHandler = new OC\Log\ErrorHandler(
671
-				\OCP\Server::get(\Psr\Log\LoggerInterface::class),
672
-			);
673
-			$exceptionHandler = [$errorHandler, 'onException'];
674
-			if ($config->getSystemValueBool('debug', false)) {
675
-				set_error_handler([$errorHandler, 'onAll'], E_ALL);
676
-				if (\OC::$CLI) {
677
-					$exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
678
-				}
679
-			} else {
680
-				set_error_handler([$errorHandler, 'onError']);
681
-			}
682
-			register_shutdown_function([$errorHandler, 'onShutdown']);
683
-			set_exception_handler($exceptionHandler);
684
-		}
685
-
686
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
687
-		$bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
688
-		$bootstrapCoordinator->runInitialRegistration();
689
-
690
-		$eventLogger->start('init_session', 'Initialize session');
691
-
692
-		// Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
693
-		// see https://github.com/nextcloud/server/pull/2619
694
-		if (!function_exists('simplexml_load_file')) {
695
-			throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
696
-		}
697
-
698
-		$appManager = Server::get(\OCP\App\IAppManager::class);
699
-		if ($systemConfig->getValue('installed', false)) {
700
-			$appManager->loadApps(['session']);
701
-		}
702
-		if (!self::$CLI) {
703
-			self::initSession();
704
-		}
705
-		$eventLogger->end('init_session');
706
-		self::checkConfig();
707
-		self::checkInstalled($systemConfig);
708
-
709
-		OC_Response::addSecurityHeaders();
710
-
711
-		self::performSameSiteCookieProtection($config);
712
-
713
-		if (!defined('OC_CONSOLE')) {
714
-			$eventLogger->start('check_server', 'Run a few configuration checks');
715
-			$errors = OC_Util::checkServer($systemConfig);
716
-			if (count($errors) > 0) {
717
-				if (!self::$CLI) {
718
-					http_response_code(503);
719
-					Util::addStyle('guest');
720
-					try {
721
-						Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
722
-						exit;
723
-					} catch (\Exception $e) {
724
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
725
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
726
-					}
727
-				}
728
-
729
-				// Convert l10n string into regular string for usage in database
730
-				$staticErrors = [];
731
-				foreach ($errors as $error) {
732
-					echo $error['error'] . "\n";
733
-					echo $error['hint'] . "\n\n";
734
-					$staticErrors[] = [
735
-						'error' => (string)$error['error'],
736
-						'hint' => (string)$error['hint'],
737
-					];
738
-				}
739
-
740
-				try {
741
-					$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
742
-				} catch (\Exception $e) {
743
-					echo('Writing to database failed');
744
-				}
745
-				exit(1);
746
-			} elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
747
-				$config->deleteAppValue('core', 'cronErrors');
748
-			}
749
-			$eventLogger->end('check_server');
750
-		}
751
-
752
-		// User and Groups
753
-		if (!$systemConfig->getValue('installed', false)) {
754
-			self::$server->getSession()->set('user_id', '');
755
-		}
756
-
757
-		$eventLogger->start('setup_backends', 'Setup group and user backends');
758
-		Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
759
-		Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
760
-
761
-		// Subscribe to the hook
762
-		\OCP\Util::connectHook(
763
-			'\OCA\Files_Sharing\API\Server2Server',
764
-			'preLoginNameUsedAsUserName',
765
-			'\OC\User\Database',
766
-			'preLoginNameUsedAsUserName'
767
-		);
768
-
769
-		//setup extra user backends
770
-		if (!\OCP\Util::needUpgrade()) {
771
-			OC_User::setupBackends();
772
-		} else {
773
-			// Run upgrades in incognito mode
774
-			OC_User::setIncognitoMode(true);
775
-		}
776
-		$eventLogger->end('setup_backends');
777
-
778
-		self::registerCleanupHooks($systemConfig);
779
-		self::registerShareHooks($systemConfig);
780
-		self::registerEncryptionWrapperAndHooks();
781
-		self::registerAccountHooks();
782
-		self::registerResourceCollectionHooks();
783
-		self::registerFileReferenceEventListener();
784
-		self::registerRenderReferenceEventListener();
785
-		self::registerAppRestrictionsHooks();
786
-
787
-		// Make sure that the application class is not loaded before the database is setup
788
-		if ($systemConfig->getValue('installed', false)) {
789
-			$appManager->loadApp('settings');
790
-			/* Build core application to make sure that listeners are registered */
791
-			Server::get(\OC\Core\Application::class);
792
-		}
793
-
794
-		//make sure temporary files are cleaned up
795
-		$tmpManager = Server::get(\OCP\ITempManager::class);
796
-		register_shutdown_function([$tmpManager, 'clean']);
797
-		$lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
798
-		register_shutdown_function([$lockProvider, 'releaseAll']);
799
-
800
-		// Check whether the sample configuration has been copied
801
-		if ($systemConfig->getValue('copied_sample_config', false)) {
802
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
803
-			Server::get(ITemplateManager::class)->printErrorPage(
804
-				$l->t('Sample configuration detected'),
805
-				$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'),
806
-				503
807
-			);
808
-			return;
809
-		}
810
-
811
-		$request = Server::get(IRequest::class);
812
-		$host = $request->getInsecureServerHost();
813
-		/**
814
-		 * if the host passed in headers isn't trusted
815
-		 * FIXME: Should not be in here at all :see_no_evil:
816
-		 */
817
-		if (!OC::$CLI
818
-			&& !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
819
-			&& $config->getSystemValueBool('installed', false)
820
-		) {
821
-			// Allow access to CSS resources
822
-			$isScssRequest = false;
823
-			if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
824
-				$isScssRequest = true;
825
-			}
826
-
827
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
828
-				http_response_code(400);
829
-				header('Content-Type: application/json');
830
-				echo '{"error": "Trusted domain error.", "code": 15}';
831
-				exit();
832
-			}
833
-
834
-			if (!$isScssRequest) {
835
-				http_response_code(400);
836
-				Server::get(LoggerInterface::class)->info(
837
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
838
-					[
839
-						'app' => 'core',
840
-						'remoteAddress' => $request->getRemoteAddress(),
841
-						'host' => $host,
842
-					]
843
-				);
844
-
845
-				$tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
846
-				$tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
847
-				$tmpl->printPage();
848
-
849
-				exit();
850
-			}
851
-		}
852
-		$eventLogger->end('boot');
853
-		$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
854
-		$eventLogger->start('runtime', 'Runtime');
855
-		$eventLogger->start('request', 'Full request after boot');
856
-		register_shutdown_function(function () use ($eventLogger) {
857
-			$eventLogger->end('request');
858
-		});
859
-
860
-		register_shutdown_function(function () {
861
-			$memoryPeak = memory_get_peak_usage();
862
-			$logLevel = match (true) {
863
-				$memoryPeak > 500_000_000 => ILogger::FATAL,
864
-				$memoryPeak > 400_000_000 => ILogger::ERROR,
865
-				$memoryPeak > 300_000_000 => ILogger::WARN,
866
-				default => null,
867
-			};
868
-			if ($logLevel !== null) {
869
-				$message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
870
-				$logger = Server::get(LoggerInterface::class);
871
-				$logger->log($logLevel, $message, ['app' => 'core']);
872
-			}
873
-		});
874
-	}
875
-
876
-	/**
877
-	 * register hooks for the cleanup of cache and bruteforce protection
878
-	 */
879
-	public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
880
-		//don't try to do this before we are properly setup
881
-		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
882
-			// NOTE: This will be replaced to use OCP
883
-			$userSession = Server::get(\OC\User\Session::class);
884
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
885
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
886
-					// reset brute force delay for this IP address and username
887
-					$uid = $userSession->getUser()->getUID();
888
-					$request = Server::get(IRequest::class);
889
-					$throttler = Server::get(IThrottler::class);
890
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
891
-				}
892
-
893
-				try {
894
-					$cache = new \OC\Cache\File();
895
-					$cache->gc();
896
-				} catch (\OC\ServerNotAvailableException $e) {
897
-					// not a GC exception, pass it on
898
-					throw $e;
899
-				} catch (\OC\ForbiddenException $e) {
900
-					// filesystem blocked for this request, ignore
901
-				} catch (\Exception $e) {
902
-					// a GC exception should not prevent users from using OC,
903
-					// so log the exception
904
-					Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
905
-						'app' => 'core',
906
-						'exception' => $e,
907
-					]);
908
-				}
909
-			});
910
-		}
911
-	}
912
-
913
-	private static function registerEncryptionWrapperAndHooks(): void {
914
-		/** @var \OC\Encryption\Manager */
915
-		$manager = Server::get(\OCP\Encryption\IManager::class);
916
-		Server::get(IEventDispatcher::class)->addListener(
917
-			BeforeFileSystemSetupEvent::class,
918
-			$manager->setupStorage(...),
919
-		);
920
-
921
-		$enabled = $manager->isEnabled();
922
-		if ($enabled) {
923
-			\OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class));
924
-		}
925
-	}
926
-
927
-	private static function registerAccountHooks(): void {
928
-		/** @var IEventDispatcher $dispatcher */
929
-		$dispatcher = Server::get(IEventDispatcher::class);
930
-		$dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
931
-	}
932
-
933
-	private static function registerAppRestrictionsHooks(): void {
934
-		/** @var \OC\Group\Manager $groupManager */
935
-		$groupManager = Server::get(\OCP\IGroupManager::class);
936
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
937
-			$appManager = Server::get(\OCP\App\IAppManager::class);
938
-			$apps = $appManager->getEnabledAppsForGroup($group);
939
-			foreach ($apps as $appId) {
940
-				$restrictions = $appManager->getAppRestriction($appId);
941
-				if (empty($restrictions)) {
942
-					continue;
943
-				}
944
-				$key = array_search($group->getGID(), $restrictions);
945
-				unset($restrictions[$key]);
946
-				$restrictions = array_values($restrictions);
947
-				if (empty($restrictions)) {
948
-					$appManager->disableApp($appId);
949
-				} else {
950
-					$appManager->enableAppForGroups($appId, $restrictions);
951
-				}
952
-			}
953
-		});
954
-	}
955
-
956
-	private static function registerResourceCollectionHooks(): void {
957
-		\OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
958
-	}
959
-
960
-	private static function registerFileReferenceEventListener(): void {
961
-		\OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
962
-	}
963
-
964
-	private static function registerRenderReferenceEventListener() {
965
-		\OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
966
-	}
967
-
968
-	/**
969
-	 * register hooks for sharing
970
-	 */
971
-	public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
972
-		if ($systemConfig->getValue('installed')) {
973
-
974
-			$dispatcher = Server::get(IEventDispatcher::class);
975
-			$dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
976
-			$dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
977
-			$dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
978
-		}
979
-	}
980
-
981
-	protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
982
-		// The class loader takes an optional low-latency cache, which MUST be
983
-		// namespaced. The instanceid is used for namespacing, but might be
984
-		// unavailable at this point. Furthermore, it might not be possible to
985
-		// generate an instanceid via \OC_Util::getInstanceId() because the
986
-		// config file may not be writable. As such, we only register a class
987
-		// loader cache if instanceid is available without trying to create one.
988
-		$instanceId = $systemConfig->getValue('instanceid', null);
989
-		if ($instanceId) {
990
-			try {
991
-				$memcacheFactory = Server::get(\OCP\ICacheFactory::class);
992
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
993
-			} catch (\Exception $ex) {
994
-			}
995
-		}
996
-	}
997
-
998
-	/**
999
-	 * Handle the request
1000
-	 */
1001
-	public static function handleRequest(): void {
1002
-		Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
1003
-		$systemConfig = Server::get(\OC\SystemConfig::class);
1004
-
1005
-		// Check if Nextcloud is installed or in maintenance (update) mode
1006
-		if (!$systemConfig->getValue('installed', false)) {
1007
-			\OC::$server->getSession()->clear();
1008
-			$controller = Server::get(\OC\Core\Controller\SetupController::class);
1009
-			$controller->run($_POST);
1010
-			exit();
1011
-		}
1012
-
1013
-		$request = Server::get(IRequest::class);
1014
-		$requestPath = $request->getRawPathInfo();
1015
-		if ($requestPath === '/heartbeat') {
1016
-			return;
1017
-		}
1018
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1019
-			self::checkMaintenanceMode($systemConfig);
1020
-
1021
-			if (\OCP\Util::needUpgrade()) {
1022
-				if (function_exists('opcache_reset')) {
1023
-					opcache_reset();
1024
-				}
1025
-				if (!((bool)$systemConfig->getValue('maintenance', false))) {
1026
-					self::printUpgradePage($systemConfig);
1027
-					exit();
1028
-				}
1029
-			}
1030
-		}
1031
-
1032
-		$appManager = Server::get(\OCP\App\IAppManager::class);
1033
-
1034
-		// Always load authentication apps
1035
-		$appManager->loadApps(['authentication']);
1036
-		$appManager->loadApps(['extended_authentication']);
1037
-
1038
-		// Load minimum set of apps
1039
-		if (!\OCP\Util::needUpgrade()
1040
-			&& !((bool)$systemConfig->getValue('maintenance', false))) {
1041
-			// For logged-in users: Load everything
1042
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1043
-				$appManager->loadApps();
1044
-			} else {
1045
-				// For guests: Load only filesystem and logging
1046
-				$appManager->loadApps(['filesystem', 'logging']);
1047
-
1048
-				// Don't try to login when a client is trying to get a OAuth token.
1049
-				// OAuth needs to support basic auth too, so the login is not valid
1050
-				// inside Nextcloud and the Login exception would ruin it.
1051
-				if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1052
-					self::handleLogin($request);
1053
-				}
1054
-			}
1055
-		}
1056
-
1057
-		if (!self::$CLI) {
1058
-			try {
1059
-				if (!\OCP\Util::needUpgrade()) {
1060
-					$appManager->loadApps(['filesystem', 'logging']);
1061
-					$appManager->loadApps();
1062
-				}
1063
-				Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1064
-				return;
1065
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1066
-				//header('HTTP/1.0 404 Not Found');
1067
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1068
-				http_response_code(405);
1069
-				return;
1070
-			}
1071
-		}
1072
-
1073
-		// Handle WebDAV
1074
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1075
-			// not allowed any more to prevent people
1076
-			// mounting this root directly.
1077
-			// Users need to mount remote.php/webdav instead.
1078
-			http_response_code(405);
1079
-			return;
1080
-		}
1081
-
1082
-		// Handle requests for JSON or XML
1083
-		$acceptHeader = $request->getHeader('Accept');
1084
-		if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1085
-			http_response_code(404);
1086
-			return;
1087
-		}
1088
-
1089
-		// Handle resources that can't be found
1090
-		// This prevents browsers from redirecting to the default page and then
1091
-		// attempting to parse HTML as CSS and similar.
1092
-		$destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1093
-		if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1094
-			http_response_code(404);
1095
-			return;
1096
-		}
1097
-
1098
-		// Redirect to the default app or login only as an entry point
1099
-		if ($requestPath === '') {
1100
-			// Someone is logged in
1101
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1102
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1103
-			} else {
1104
-				// Not handled and not logged in
1105
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1106
-			}
1107
-			return;
1108
-		}
1109
-
1110
-		try {
1111
-			Server::get(\OC\Route\Router::class)->match('/error/404');
1112
-		} catch (\Exception $e) {
1113
-			if (!$e instanceof MethodNotAllowedException) {
1114
-				logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1115
-			}
1116
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1117
-			Server::get(ITemplateManager::class)->printErrorPage(
1118
-				'404',
1119
-				$l->t('The page could not be found on the server.'),
1120
-				404
1121
-			);
1122
-		}
1123
-	}
1124
-
1125
-	/**
1126
-	 * Check login: apache auth, auth token, basic auth
1127
-	 */
1128
-	public static function handleLogin(OCP\IRequest $request): bool {
1129
-		if ($request->getHeader('X-Nextcloud-Federation')) {
1130
-			return false;
1131
-		}
1132
-		$userSession = Server::get(\OC\User\Session::class);
1133
-		if (OC_User::handleApacheAuth()) {
1134
-			return true;
1135
-		}
1136
-		if (self::tryAppAPILogin($request)) {
1137
-			return true;
1138
-		}
1139
-		if ($userSession->tryTokenLogin($request)) {
1140
-			return true;
1141
-		}
1142
-		if (isset($_COOKIE['nc_username'])
1143
-			&& isset($_COOKIE['nc_token'])
1144
-			&& isset($_COOKIE['nc_session_id'])
1145
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1146
-			return true;
1147
-		}
1148
-		if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1149
-			return true;
1150
-		}
1151
-		return false;
1152
-	}
1153
-
1154
-	protected static function handleAuthHeaders(): void {
1155
-		//copy http auth headers for apache+php-fcgid work around
1156
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1157
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1158
-		}
1159
-
1160
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1161
-		$vars = [
1162
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1163
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1164
-		];
1165
-		foreach ($vars as $var) {
1166
-			if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1167
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1168
-				if (count($credentials) === 2) {
1169
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1170
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1171
-					break;
1172
-				}
1173
-			}
1174
-		}
1175
-	}
1176
-
1177
-	protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1178
-		if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1179
-			return false;
1180
-		}
1181
-		$appManager = Server::get(OCP\App\IAppManager::class);
1182
-		if (!$appManager->isEnabledForAnyone('app_api')) {
1183
-			return false;
1184
-		}
1185
-		try {
1186
-			$appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1187
-			return $appAPIService->validateExAppRequestToNC($request);
1188
-		} catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1189
-			return false;
1190
-		}
1191
-	}
42
+    /**
43
+     * Associative array for autoloading. classname => filename
44
+     */
45
+    public static array $CLASSPATH = [];
46
+    /**
47
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
48
+     */
49
+    public static string $SERVERROOT = '';
50
+    /**
51
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
52
+     */
53
+    private static string $SUBURI = '';
54
+    /**
55
+     * the Nextcloud root path for http requests (e.g. /nextcloud)
56
+     */
57
+    public static string $WEBROOT = '';
58
+    /**
59
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
60
+     * web path in 'url'
61
+     */
62
+    public static array $APPSROOTS = [];
63
+
64
+    public static string $configDir;
65
+
66
+    /**
67
+     * requested app
68
+     */
69
+    public static string $REQUESTEDAPP = '';
70
+
71
+    /**
72
+     * check if Nextcloud runs in cli mode
73
+     */
74
+    public static bool $CLI = false;
75
+
76
+    public static \OC\Autoloader $loader;
77
+
78
+    public static \Composer\Autoload\ClassLoader $composerAutoloader;
79
+
80
+    public static \OC\Server $server;
81
+
82
+    private static \OC\Config $config;
83
+
84
+    /**
85
+     * @throws \RuntimeException when the 3rdparty directory is missing or
86
+     *                           the app path list is empty or contains an invalid path
87
+     */
88
+    public static function initPaths(): void {
89
+        if (defined('PHPUNIT_CONFIG_DIR')) {
90
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
91
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
92
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
93
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
94
+            self::$configDir = rtrim($dir, '/') . '/';
95
+        } else {
96
+            self::$configDir = OC::$SERVERROOT . '/config/';
97
+        }
98
+        self::$config = new \OC\Config(self::$configDir);
99
+
100
+        OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT)));
101
+        /**
102
+         * FIXME: The following lines are required because we can't yet instantiate
103
+         *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
104
+         */
105
+        $params = [
106
+            'server' => [
107
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
108
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
109
+            ],
110
+        ];
111
+        if (isset($_SERVER['REMOTE_ADDR'])) {
112
+            $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
113
+        }
114
+        $fakeRequest = new \OC\AppFramework\Http\Request(
115
+            $params,
116
+            new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
117
+            new \OC\AllConfig(new \OC\SystemConfig(self::$config))
118
+        );
119
+        $scriptName = $fakeRequest->getScriptName();
120
+        if (substr($scriptName, -1) == '/') {
121
+            $scriptName .= 'index.php';
122
+            //make sure suburi follows the same rules as scriptName
123
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
124
+                if (substr(OC::$SUBURI, -1) != '/') {
125
+                    OC::$SUBURI = OC::$SUBURI . '/';
126
+                }
127
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
128
+            }
129
+        }
130
+
131
+        if (OC::$CLI) {
132
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
133
+        } else {
134
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
135
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
136
+
137
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
138
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
139
+                }
140
+            } else {
141
+                // The scriptName is not ending with OC::$SUBURI
142
+                // This most likely means that we are calling from CLI.
143
+                // However some cron jobs still need to generate
144
+                // a web URL, so we use overwritewebroot as a fallback.
145
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
146
+            }
147
+
148
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
149
+            // slash which is required by URL generation.
150
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
151
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
152
+                header('Location: ' . \OC::$WEBROOT . '/');
153
+                exit();
154
+            }
155
+        }
156
+
157
+        // search the apps folder
158
+        $config_paths = self::$config->getValue('apps_paths', []);
159
+        if (!empty($config_paths)) {
160
+            foreach ($config_paths as $paths) {
161
+                if (isset($paths['url']) && isset($paths['path'])) {
162
+                    $paths['url'] = rtrim($paths['url'], '/');
163
+                    $paths['path'] = rtrim($paths['path'], '/');
164
+                    OC::$APPSROOTS[] = $paths;
165
+                }
166
+            }
167
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
168
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
169
+        }
170
+
171
+        if (empty(OC::$APPSROOTS)) {
172
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
173
+                . '. You can also configure the location in the config.php file.');
174
+        }
175
+        $paths = [];
176
+        foreach (OC::$APPSROOTS as $path) {
177
+            $paths[] = $path['path'];
178
+            if (!is_dir($path['path'])) {
179
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
180
+                    . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
181
+            }
182
+        }
183
+
184
+        // set the right include path
185
+        set_include_path(
186
+            implode(PATH_SEPARATOR, $paths)
187
+        );
188
+    }
189
+
190
+    public static function checkConfig(): void {
191
+        // Create config if it does not already exist
192
+        $configFilePath = self::$configDir . '/config.php';
193
+        if (!file_exists($configFilePath)) {
194
+            @touch($configFilePath);
195
+        }
196
+
197
+        // Check if config is writable
198
+        $configFileWritable = is_writable($configFilePath);
199
+        $configReadOnly = Server::get(IConfig::class)->getSystemValueBool('config_is_read_only');
200
+        if (!$configFileWritable && !$configReadOnly
201
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
202
+            $urlGenerator = Server::get(IURLGenerator::class);
203
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
204
+
205
+            if (self::$CLI) {
206
+                echo $l->t('Cannot write into "config" directory!') . "\n";
207
+                echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n";
208
+                echo "\n";
209
+                echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n";
210
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n";
211
+                exit;
212
+            } else {
213
+                Server::get(ITemplateManager::class)->printErrorPage(
214
+                    $l->t('Cannot write into "config" directory!'),
215
+                    $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
216
+                    . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
217
+                    . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
218
+                    503
219
+                );
220
+            }
221
+        }
222
+    }
223
+
224
+    public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
225
+        if (defined('OC_CONSOLE')) {
226
+            return;
227
+        }
228
+        // Redirect to installer if not installed
229
+        if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
230
+            if (OC::$CLI) {
231
+                throw new Exception('Not installed');
232
+            } else {
233
+                $url = OC::$WEBROOT . '/index.php';
234
+                header('Location: ' . $url);
235
+            }
236
+            exit();
237
+        }
238
+    }
239
+
240
+    public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
241
+        // Allow ajax update script to execute without being stopped
242
+        if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
243
+            // send http status 503
244
+            http_response_code(503);
245
+            header('X-Nextcloud-Maintenance-Mode: 1');
246
+            header('Retry-After: 120');
247
+
248
+            // render error page
249
+            $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest');
250
+            \OCP\Util::addScript('core', 'maintenance');
251
+            \OCP\Util::addStyle('core', 'guest');
252
+            $template->printPage();
253
+            die();
254
+        }
255
+    }
256
+
257
+    /**
258
+     * Prints the upgrade page
259
+     */
260
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
261
+        $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', '');
262
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
263
+        $tooBig = false;
264
+        if (!$disableWebUpdater) {
265
+            $apps = Server::get(\OCP\App\IAppManager::class);
266
+            if ($apps->isEnabledForAnyone('user_ldap')) {
267
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
268
+
269
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
270
+                    ->from('ldap_user_mapping')
271
+                    ->executeQuery();
272
+                $row = $result->fetch();
273
+                $result->closeCursor();
274
+
275
+                $tooBig = ($row['user_count'] > 50);
276
+            }
277
+            if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) {
278
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
279
+
280
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
281
+                    ->from('user_saml_users')
282
+                    ->executeQuery();
283
+                $row = $result->fetch();
284
+                $result->closeCursor();
285
+
286
+                $tooBig = ($row['user_count'] > 50);
287
+            }
288
+            if (!$tooBig) {
289
+                // count users
290
+                $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51);
291
+                $tooBig = ($totalUsers > 50);
292
+            }
293
+        }
294
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
295
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
296
+
297
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
298
+            // send http status 503
299
+            http_response_code(503);
300
+            header('Retry-After: 120');
301
+
302
+            $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class);
303
+
304
+            // render error page
305
+            $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest');
306
+            $template->assign('productName', 'nextcloud'); // for now
307
+            $template->assign('version', $serverVersion->getVersionString());
308
+            $template->assign('tooBig', $tooBig);
309
+            $template->assign('cliUpgradeLink', $cliUpgradeLink);
310
+
311
+            $template->printPage();
312
+            die();
313
+        }
314
+
315
+        // check whether this is a core update or apps update
316
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
317
+        $currentVersion = implode('.', \OCP\Util::getVersion());
318
+
319
+        // if not a core upgrade, then it's apps upgrade
320
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
321
+
322
+        $oldTheme = $systemConfig->getValue('theme');
323
+        $systemConfig->setValue('theme', '');
324
+        \OCP\Util::addScript('core', 'common');
325
+        \OCP\Util::addScript('core', 'main');
326
+        \OCP\Util::addTranslations('core');
327
+        \OCP\Util::addScript('core', 'update');
328
+
329
+        /** @var \OC\App\AppManager $appManager */
330
+        $appManager = Server::get(\OCP\App\IAppManager::class);
331
+
332
+        $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest');
333
+        $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString());
334
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
335
+
336
+        // get third party apps
337
+        $ocVersion = \OCP\Util::getVersion();
338
+        $ocVersion = implode('.', $ocVersion);
339
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
340
+        $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []);
341
+        $incompatibleShippedApps = [];
342
+        $incompatibleDisabledApps = [];
343
+        foreach ($incompatibleApps as $appInfo) {
344
+            if ($appManager->isShipped($appInfo['id'])) {
345
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
346
+            }
347
+            if (!in_array($appInfo['id'], $incompatibleOverwrites)) {
348
+                $incompatibleDisabledApps[] = $appInfo;
349
+            }
350
+        }
351
+
352
+        if (!empty($incompatibleShippedApps)) {
353
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('core');
354
+            $hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
355
+            throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
356
+        }
357
+
358
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
359
+        $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps);
360
+        try {
361
+            $defaults = new \OC_Defaults();
362
+            $tmpl->assign('productName', $defaults->getName());
363
+        } catch (Throwable $error) {
364
+            $tmpl->assign('productName', 'Nextcloud');
365
+        }
366
+        $tmpl->assign('oldTheme', $oldTheme);
367
+        $tmpl->printPage();
368
+    }
369
+
370
+    public static function initSession(): void {
371
+        $request = Server::get(IRequest::class);
372
+
373
+        // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
374
+        // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
375
+        // TODO: for further information.
376
+        // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
377
+        // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
378
+        // setcookie('cookie_test', 'test', time() + 3600);
379
+        // // Do not initialize the session if a request is authenticated directly
380
+        // // unless there is a session cookie already sent along
381
+        // return;
382
+        // }
383
+
384
+        if ($request->getServerProtocol() === 'https') {
385
+            ini_set('session.cookie_secure', 'true');
386
+        }
387
+
388
+        // prevents javascript from accessing php session cookies
389
+        ini_set('session.cookie_httponly', 'true');
390
+
391
+        // Do not initialize sessions for 'status.php' requests
392
+        // Monitoring endpoints can quickly flood session handlers
393
+        // and 'status.php' doesn't require sessions anyway
394
+        if (str_ends_with($request->getScriptName(), '/status.php')) {
395
+            return;
396
+        }
397
+
398
+        // set the cookie path to the Nextcloud directory
399
+        $cookie_path = OC::$WEBROOT ? : '/';
400
+        ini_set('session.cookie_path', $cookie_path);
401
+
402
+        // Let the session name be changed in the initSession Hook
403
+        $sessionName = OC_Util::getInstanceId();
404
+
405
+        try {
406
+            $logger = null;
407
+            if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) {
408
+                $logger = logger('core');
409
+            }
410
+
411
+            // set the session name to the instance id - which is unique
412
+            $session = new \OC\Session\Internal(
413
+                $sessionName,
414
+                $logger,
415
+            );
416
+
417
+            $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
418
+            $session = $cryptoWrapper->wrapSession($session);
419
+            self::$server->setSession($session);
420
+
421
+            // if session can't be started break with http 500 error
422
+        } catch (Exception $e) {
423
+            Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
424
+            //show the user a detailed error page
425
+            Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500);
426
+            die();
427
+        }
428
+
429
+        //try to set the session lifetime
430
+        $sessionLifeTime = self::getSessionLifeTime();
431
+
432
+        // session timeout
433
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
+            if (isset($_COOKIE[session_name()])) {
435
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
436
+            }
437
+            Server::get(IUserSession::class)->logout();
438
+        }
439
+
440
+        if (!self::hasSessionRelaxedExpiry()) {
441
+            $session->set('LAST_ACTIVITY', time());
442
+        }
443
+        $session->close();
444
+    }
445
+
446
+    private static function getSessionLifeTime(): int {
447
+        return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
448
+    }
449
+
450
+    /**
451
+     * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
452
+     */
453
+    public static function hasSessionRelaxedExpiry(): bool {
454
+        return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
455
+    }
456
+
457
+    /**
458
+     * Try to set some values to the required Nextcloud default
459
+     */
460
+    public static function setRequiredIniValues(): void {
461
+        // Don't display errors and log them
462
+        @ini_set('display_errors', '0');
463
+        @ini_set('log_errors', '1');
464
+
465
+        // Try to configure php to enable big file uploads.
466
+        // This doesn't work always depending on the webserver and php configuration.
467
+        // Let's try to overwrite some defaults if they are smaller than 1 hour
468
+
469
+        if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
470
+            @ini_set('max_execution_time', strval(3600));
471
+        }
472
+
473
+        if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
474
+            @ini_set('max_input_time', strval(3600));
475
+        }
476
+
477
+        // Try to set the maximum execution time to the largest time limit we have
478
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
479
+            @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
480
+        }
481
+
482
+        @ini_set('default_charset', 'UTF-8');
483
+        @ini_set('gd.jpeg_ignore_warning', '1');
484
+    }
485
+
486
+    /**
487
+     * Send the same site cookies
488
+     */
489
+    private static function sendSameSiteCookies(): void {
490
+        $cookieParams = session_get_cookie_params();
491
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
492
+        $policies = [
493
+            'lax',
494
+            'strict',
495
+        ];
496
+
497
+        // Append __Host to the cookie if it meets the requirements
498
+        $cookiePrefix = '';
499
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
500
+            $cookiePrefix = '__Host-';
501
+        }
502
+
503
+        foreach ($policies as $policy) {
504
+            header(
505
+                sprintf(
506
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507
+                    $cookiePrefix,
508
+                    $policy,
509
+                    $cookieParams['path'],
510
+                    $policy
511
+                ),
512
+                false
513
+            );
514
+        }
515
+    }
516
+
517
+    /**
518
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
519
+     * be set in every request if cookies are sent to add a second level of
520
+     * defense against CSRF.
521
+     *
522
+     * If the cookie is not sent this will set the cookie and reload the page.
523
+     * We use an additional cookie since we want to protect logout CSRF and
524
+     * also we can't directly interfere with PHP's session mechanism.
525
+     */
526
+    private static function performSameSiteCookieProtection(IConfig $config): void {
527
+        $request = Server::get(IRequest::class);
528
+
529
+        // Some user agents are notorious and don't really properly follow HTTP
530
+        // specifications. For those, have an automated opt-out. Since the protection
531
+        // for remote.php is applied in base.php as starting point we need to opt out
532
+        // here.
533
+        $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
534
+
535
+        // Fallback, if csrf.optout is unset
536
+        if (!is_array($incompatibleUserAgents)) {
537
+            $incompatibleUserAgents = [
538
+                // OS X Finder
539
+                '/^WebDAVFS/',
540
+                // Windows webdav drive
541
+                '/^Microsoft-WebDAV-MiniRedir/',
542
+            ];
543
+        }
544
+
545
+        if ($request->isUserAgent($incompatibleUserAgents)) {
546
+            return;
547
+        }
548
+
549
+        if (count($_COOKIE) > 0) {
550
+            $requestUri = $request->getScriptName();
551
+            $processingScript = explode('/', $requestUri);
552
+            $processingScript = $processingScript[count($processingScript) - 1];
553
+
554
+            if ($processingScript === 'index.php' // index.php routes are handled in the middleware
555
+                || $processingScript === 'cron.php' // and cron.php does not need any authentication at all
556
+                || $processingScript === 'public.php' // For public.php, auth for password protected shares is done in the PublicAuth plugin
557
+            ) {
558
+                return;
559
+            }
560
+
561
+            // All other endpoints require the lax and the strict cookie
562
+            if (!$request->passesStrictCookieCheck()) {
563
+                logger('core')->warning('Request does not pass strict cookie check');
564
+                self::sendSameSiteCookies();
565
+                // Debug mode gets access to the resources without strict cookie
566
+                // due to the fact that the SabreDAV browser also lives there.
567
+                if (!$config->getSystemValueBool('debug', false)) {
568
+                    http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
569
+                    header('Content-Type: application/json');
570
+                    echo json_encode(['error' => 'Strict Cookie has not been found in request']);
571
+                    exit();
572
+                }
573
+            }
574
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
575
+            self::sendSameSiteCookies();
576
+        }
577
+    }
578
+
579
+    public static function init(): void {
580
+        // First handle PHP configuration and copy auth headers to the expected
581
+        // $_SERVER variable before doing anything Server object related
582
+        self::setRequiredIniValues();
583
+        self::handleAuthHeaders();
584
+
585
+        // prevent any XML processing from loading external entities
586
+        libxml_set_external_entity_loader(static function () {
587
+            return null;
588
+        });
589
+
590
+        // Set default timezone before the Server object is booted
591
+        if (!date_default_timezone_set('UTC')) {
592
+            throw new \RuntimeException('Could not set timezone to UTC');
593
+        }
594
+
595
+        // calculate the root directories
596
+        OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4));
597
+
598
+        // register autoloader
599
+        $loaderStart = microtime(true);
600
+        require_once __DIR__ . '/autoloader.php';
601
+        self::$loader = new \OC\Autoloader([
602
+            OC::$SERVERROOT . '/lib/private/legacy',
603
+        ]);
604
+        if (defined('PHPUNIT_RUN')) {
605
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
606
+        }
607
+        spl_autoload_register([self::$loader, 'load']);
608
+        $loaderEnd = microtime(true);
609
+
610
+        self::$CLI = (php_sapi_name() == 'cli');
611
+
612
+        // Add default composer PSR-4 autoloader, ensure apcu to be disabled
613
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
614
+        self::$composerAutoloader->setApcuPrefix(null);
615
+
616
+
617
+        try {
618
+            self::initPaths();
619
+            // setup 3rdparty autoloader
620
+            $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
621
+            if (!file_exists($vendorAutoLoad)) {
622
+                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".');
623
+            }
624
+            require_once $vendorAutoLoad;
625
+        } catch (\RuntimeException $e) {
626
+            if (!self::$CLI) {
627
+                http_response_code(503);
628
+            }
629
+            // we can't use the template error page here, because this needs the
630
+            // DI container which isn't available yet
631
+            print($e->getMessage());
632
+            exit();
633
+        }
634
+
635
+        // setup the basic server
636
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
637
+        self::$server->boot();
638
+
639
+        try {
640
+            $profiler = new BuiltInProfiler(
641
+                Server::get(IConfig::class),
642
+                Server::get(IRequest::class),
643
+            );
644
+            $profiler->start();
645
+        } catch (\Throwable $e) {
646
+            logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
647
+        }
648
+
649
+        if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
650
+            \OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
651
+        }
652
+
653
+        $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
654
+        $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
655
+        $eventLogger->start('boot', 'Initialize');
656
+
657
+        // Override php.ini and log everything if we're troubleshooting
658
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
659
+            error_reporting(E_ALL);
660
+        }
661
+
662
+        $systemConfig = Server::get(\OC\SystemConfig::class);
663
+        self::registerAutoloaderCache($systemConfig);
664
+
665
+        // initialize intl fallback if necessary
666
+        OC_Util::isSetLocaleWorking();
667
+
668
+        $config = Server::get(IConfig::class);
669
+        if (!defined('PHPUNIT_RUN')) {
670
+            $errorHandler = new OC\Log\ErrorHandler(
671
+                \OCP\Server::get(\Psr\Log\LoggerInterface::class),
672
+            );
673
+            $exceptionHandler = [$errorHandler, 'onException'];
674
+            if ($config->getSystemValueBool('debug', false)) {
675
+                set_error_handler([$errorHandler, 'onAll'], E_ALL);
676
+                if (\OC::$CLI) {
677
+                    $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
678
+                }
679
+            } else {
680
+                set_error_handler([$errorHandler, 'onError']);
681
+            }
682
+            register_shutdown_function([$errorHandler, 'onShutdown']);
683
+            set_exception_handler($exceptionHandler);
684
+        }
685
+
686
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
687
+        $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
688
+        $bootstrapCoordinator->runInitialRegistration();
689
+
690
+        $eventLogger->start('init_session', 'Initialize session');
691
+
692
+        // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
693
+        // see https://github.com/nextcloud/server/pull/2619
694
+        if (!function_exists('simplexml_load_file')) {
695
+            throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
696
+        }
697
+
698
+        $appManager = Server::get(\OCP\App\IAppManager::class);
699
+        if ($systemConfig->getValue('installed', false)) {
700
+            $appManager->loadApps(['session']);
701
+        }
702
+        if (!self::$CLI) {
703
+            self::initSession();
704
+        }
705
+        $eventLogger->end('init_session');
706
+        self::checkConfig();
707
+        self::checkInstalled($systemConfig);
708
+
709
+        OC_Response::addSecurityHeaders();
710
+
711
+        self::performSameSiteCookieProtection($config);
712
+
713
+        if (!defined('OC_CONSOLE')) {
714
+            $eventLogger->start('check_server', 'Run a few configuration checks');
715
+            $errors = OC_Util::checkServer($systemConfig);
716
+            if (count($errors) > 0) {
717
+                if (!self::$CLI) {
718
+                    http_response_code(503);
719
+                    Util::addStyle('guest');
720
+                    try {
721
+                        Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
722
+                        exit;
723
+                    } catch (\Exception $e) {
724
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
725
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
726
+                    }
727
+                }
728
+
729
+                // Convert l10n string into regular string for usage in database
730
+                $staticErrors = [];
731
+                foreach ($errors as $error) {
732
+                    echo $error['error'] . "\n";
733
+                    echo $error['hint'] . "\n\n";
734
+                    $staticErrors[] = [
735
+                        'error' => (string)$error['error'],
736
+                        'hint' => (string)$error['hint'],
737
+                    ];
738
+                }
739
+
740
+                try {
741
+                    $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
742
+                } catch (\Exception $e) {
743
+                    echo('Writing to database failed');
744
+                }
745
+                exit(1);
746
+            } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
747
+                $config->deleteAppValue('core', 'cronErrors');
748
+            }
749
+            $eventLogger->end('check_server');
750
+        }
751
+
752
+        // User and Groups
753
+        if (!$systemConfig->getValue('installed', false)) {
754
+            self::$server->getSession()->set('user_id', '');
755
+        }
756
+
757
+        $eventLogger->start('setup_backends', 'Setup group and user backends');
758
+        Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
759
+        Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
760
+
761
+        // Subscribe to the hook
762
+        \OCP\Util::connectHook(
763
+            '\OCA\Files_Sharing\API\Server2Server',
764
+            'preLoginNameUsedAsUserName',
765
+            '\OC\User\Database',
766
+            'preLoginNameUsedAsUserName'
767
+        );
768
+
769
+        //setup extra user backends
770
+        if (!\OCP\Util::needUpgrade()) {
771
+            OC_User::setupBackends();
772
+        } else {
773
+            // Run upgrades in incognito mode
774
+            OC_User::setIncognitoMode(true);
775
+        }
776
+        $eventLogger->end('setup_backends');
777
+
778
+        self::registerCleanupHooks($systemConfig);
779
+        self::registerShareHooks($systemConfig);
780
+        self::registerEncryptionWrapperAndHooks();
781
+        self::registerAccountHooks();
782
+        self::registerResourceCollectionHooks();
783
+        self::registerFileReferenceEventListener();
784
+        self::registerRenderReferenceEventListener();
785
+        self::registerAppRestrictionsHooks();
786
+
787
+        // Make sure that the application class is not loaded before the database is setup
788
+        if ($systemConfig->getValue('installed', false)) {
789
+            $appManager->loadApp('settings');
790
+            /* Build core application to make sure that listeners are registered */
791
+            Server::get(\OC\Core\Application::class);
792
+        }
793
+
794
+        //make sure temporary files are cleaned up
795
+        $tmpManager = Server::get(\OCP\ITempManager::class);
796
+        register_shutdown_function([$tmpManager, 'clean']);
797
+        $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
798
+        register_shutdown_function([$lockProvider, 'releaseAll']);
799
+
800
+        // Check whether the sample configuration has been copied
801
+        if ($systemConfig->getValue('copied_sample_config', false)) {
802
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
803
+            Server::get(ITemplateManager::class)->printErrorPage(
804
+                $l->t('Sample configuration detected'),
805
+                $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'),
806
+                503
807
+            );
808
+            return;
809
+        }
810
+
811
+        $request = Server::get(IRequest::class);
812
+        $host = $request->getInsecureServerHost();
813
+        /**
814
+         * if the host passed in headers isn't trusted
815
+         * FIXME: Should not be in here at all :see_no_evil:
816
+         */
817
+        if (!OC::$CLI
818
+            && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
819
+            && $config->getSystemValueBool('installed', false)
820
+        ) {
821
+            // Allow access to CSS resources
822
+            $isScssRequest = false;
823
+            if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
824
+                $isScssRequest = true;
825
+            }
826
+
827
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
828
+                http_response_code(400);
829
+                header('Content-Type: application/json');
830
+                echo '{"error": "Trusted domain error.", "code": 15}';
831
+                exit();
832
+            }
833
+
834
+            if (!$isScssRequest) {
835
+                http_response_code(400);
836
+                Server::get(LoggerInterface::class)->info(
837
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
838
+                    [
839
+                        'app' => 'core',
840
+                        'remoteAddress' => $request->getRemoteAddress(),
841
+                        'host' => $host,
842
+                    ]
843
+                );
844
+
845
+                $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
846
+                $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
847
+                $tmpl->printPage();
848
+
849
+                exit();
850
+            }
851
+        }
852
+        $eventLogger->end('boot');
853
+        $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
854
+        $eventLogger->start('runtime', 'Runtime');
855
+        $eventLogger->start('request', 'Full request after boot');
856
+        register_shutdown_function(function () use ($eventLogger) {
857
+            $eventLogger->end('request');
858
+        });
859
+
860
+        register_shutdown_function(function () {
861
+            $memoryPeak = memory_get_peak_usage();
862
+            $logLevel = match (true) {
863
+                $memoryPeak > 500_000_000 => ILogger::FATAL,
864
+                $memoryPeak > 400_000_000 => ILogger::ERROR,
865
+                $memoryPeak > 300_000_000 => ILogger::WARN,
866
+                default => null,
867
+            };
868
+            if ($logLevel !== null) {
869
+                $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
870
+                $logger = Server::get(LoggerInterface::class);
871
+                $logger->log($logLevel, $message, ['app' => 'core']);
872
+            }
873
+        });
874
+    }
875
+
876
+    /**
877
+     * register hooks for the cleanup of cache and bruteforce protection
878
+     */
879
+    public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
880
+        //don't try to do this before we are properly setup
881
+        if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
882
+            // NOTE: This will be replaced to use OCP
883
+            $userSession = Server::get(\OC\User\Session::class);
884
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
885
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
886
+                    // reset brute force delay for this IP address and username
887
+                    $uid = $userSession->getUser()->getUID();
888
+                    $request = Server::get(IRequest::class);
889
+                    $throttler = Server::get(IThrottler::class);
890
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
891
+                }
892
+
893
+                try {
894
+                    $cache = new \OC\Cache\File();
895
+                    $cache->gc();
896
+                } catch (\OC\ServerNotAvailableException $e) {
897
+                    // not a GC exception, pass it on
898
+                    throw $e;
899
+                } catch (\OC\ForbiddenException $e) {
900
+                    // filesystem blocked for this request, ignore
901
+                } catch (\Exception $e) {
902
+                    // a GC exception should not prevent users from using OC,
903
+                    // so log the exception
904
+                    Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
905
+                        'app' => 'core',
906
+                        'exception' => $e,
907
+                    ]);
908
+                }
909
+            });
910
+        }
911
+    }
912
+
913
+    private static function registerEncryptionWrapperAndHooks(): void {
914
+        /** @var \OC\Encryption\Manager */
915
+        $manager = Server::get(\OCP\Encryption\IManager::class);
916
+        Server::get(IEventDispatcher::class)->addListener(
917
+            BeforeFileSystemSetupEvent::class,
918
+            $manager->setupStorage(...),
919
+        );
920
+
921
+        $enabled = $manager->isEnabled();
922
+        if ($enabled) {
923
+            \OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class));
924
+        }
925
+    }
926
+
927
+    private static function registerAccountHooks(): void {
928
+        /** @var IEventDispatcher $dispatcher */
929
+        $dispatcher = Server::get(IEventDispatcher::class);
930
+        $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
931
+    }
932
+
933
+    private static function registerAppRestrictionsHooks(): void {
934
+        /** @var \OC\Group\Manager $groupManager */
935
+        $groupManager = Server::get(\OCP\IGroupManager::class);
936
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
937
+            $appManager = Server::get(\OCP\App\IAppManager::class);
938
+            $apps = $appManager->getEnabledAppsForGroup($group);
939
+            foreach ($apps as $appId) {
940
+                $restrictions = $appManager->getAppRestriction($appId);
941
+                if (empty($restrictions)) {
942
+                    continue;
943
+                }
944
+                $key = array_search($group->getGID(), $restrictions);
945
+                unset($restrictions[$key]);
946
+                $restrictions = array_values($restrictions);
947
+                if (empty($restrictions)) {
948
+                    $appManager->disableApp($appId);
949
+                } else {
950
+                    $appManager->enableAppForGroups($appId, $restrictions);
951
+                }
952
+            }
953
+        });
954
+    }
955
+
956
+    private static function registerResourceCollectionHooks(): void {
957
+        \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
958
+    }
959
+
960
+    private static function registerFileReferenceEventListener(): void {
961
+        \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
962
+    }
963
+
964
+    private static function registerRenderReferenceEventListener() {
965
+        \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
966
+    }
967
+
968
+    /**
969
+     * register hooks for sharing
970
+     */
971
+    public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
972
+        if ($systemConfig->getValue('installed')) {
973
+
974
+            $dispatcher = Server::get(IEventDispatcher::class);
975
+            $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
976
+            $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
977
+            $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
978
+        }
979
+    }
980
+
981
+    protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
982
+        // The class loader takes an optional low-latency cache, which MUST be
983
+        // namespaced. The instanceid is used for namespacing, but might be
984
+        // unavailable at this point. Furthermore, it might not be possible to
985
+        // generate an instanceid via \OC_Util::getInstanceId() because the
986
+        // config file may not be writable. As such, we only register a class
987
+        // loader cache if instanceid is available without trying to create one.
988
+        $instanceId = $systemConfig->getValue('instanceid', null);
989
+        if ($instanceId) {
990
+            try {
991
+                $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
992
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
993
+            } catch (\Exception $ex) {
994
+            }
995
+        }
996
+    }
997
+
998
+    /**
999
+     * Handle the request
1000
+     */
1001
+    public static function handleRequest(): void {
1002
+        Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
1003
+        $systemConfig = Server::get(\OC\SystemConfig::class);
1004
+
1005
+        // Check if Nextcloud is installed or in maintenance (update) mode
1006
+        if (!$systemConfig->getValue('installed', false)) {
1007
+            \OC::$server->getSession()->clear();
1008
+            $controller = Server::get(\OC\Core\Controller\SetupController::class);
1009
+            $controller->run($_POST);
1010
+            exit();
1011
+        }
1012
+
1013
+        $request = Server::get(IRequest::class);
1014
+        $requestPath = $request->getRawPathInfo();
1015
+        if ($requestPath === '/heartbeat') {
1016
+            return;
1017
+        }
1018
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1019
+            self::checkMaintenanceMode($systemConfig);
1020
+
1021
+            if (\OCP\Util::needUpgrade()) {
1022
+                if (function_exists('opcache_reset')) {
1023
+                    opcache_reset();
1024
+                }
1025
+                if (!((bool)$systemConfig->getValue('maintenance', false))) {
1026
+                    self::printUpgradePage($systemConfig);
1027
+                    exit();
1028
+                }
1029
+            }
1030
+        }
1031
+
1032
+        $appManager = Server::get(\OCP\App\IAppManager::class);
1033
+
1034
+        // Always load authentication apps
1035
+        $appManager->loadApps(['authentication']);
1036
+        $appManager->loadApps(['extended_authentication']);
1037
+
1038
+        // Load minimum set of apps
1039
+        if (!\OCP\Util::needUpgrade()
1040
+            && !((bool)$systemConfig->getValue('maintenance', false))) {
1041
+            // For logged-in users: Load everything
1042
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1043
+                $appManager->loadApps();
1044
+            } else {
1045
+                // For guests: Load only filesystem and logging
1046
+                $appManager->loadApps(['filesystem', 'logging']);
1047
+
1048
+                // Don't try to login when a client is trying to get a OAuth token.
1049
+                // OAuth needs to support basic auth too, so the login is not valid
1050
+                // inside Nextcloud and the Login exception would ruin it.
1051
+                if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1052
+                    self::handleLogin($request);
1053
+                }
1054
+            }
1055
+        }
1056
+
1057
+        if (!self::$CLI) {
1058
+            try {
1059
+                if (!\OCP\Util::needUpgrade()) {
1060
+                    $appManager->loadApps(['filesystem', 'logging']);
1061
+                    $appManager->loadApps();
1062
+                }
1063
+                Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1064
+                return;
1065
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1066
+                //header('HTTP/1.0 404 Not Found');
1067
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1068
+                http_response_code(405);
1069
+                return;
1070
+            }
1071
+        }
1072
+
1073
+        // Handle WebDAV
1074
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1075
+            // not allowed any more to prevent people
1076
+            // mounting this root directly.
1077
+            // Users need to mount remote.php/webdav instead.
1078
+            http_response_code(405);
1079
+            return;
1080
+        }
1081
+
1082
+        // Handle requests for JSON or XML
1083
+        $acceptHeader = $request->getHeader('Accept');
1084
+        if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1085
+            http_response_code(404);
1086
+            return;
1087
+        }
1088
+
1089
+        // Handle resources that can't be found
1090
+        // This prevents browsers from redirecting to the default page and then
1091
+        // attempting to parse HTML as CSS and similar.
1092
+        $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1093
+        if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1094
+            http_response_code(404);
1095
+            return;
1096
+        }
1097
+
1098
+        // Redirect to the default app or login only as an entry point
1099
+        if ($requestPath === '') {
1100
+            // Someone is logged in
1101
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1102
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1103
+            } else {
1104
+                // Not handled and not logged in
1105
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1106
+            }
1107
+            return;
1108
+        }
1109
+
1110
+        try {
1111
+            Server::get(\OC\Route\Router::class)->match('/error/404');
1112
+        } catch (\Exception $e) {
1113
+            if (!$e instanceof MethodNotAllowedException) {
1114
+                logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1115
+            }
1116
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1117
+            Server::get(ITemplateManager::class)->printErrorPage(
1118
+                '404',
1119
+                $l->t('The page could not be found on the server.'),
1120
+                404
1121
+            );
1122
+        }
1123
+    }
1124
+
1125
+    /**
1126
+     * Check login: apache auth, auth token, basic auth
1127
+     */
1128
+    public static function handleLogin(OCP\IRequest $request): bool {
1129
+        if ($request->getHeader('X-Nextcloud-Federation')) {
1130
+            return false;
1131
+        }
1132
+        $userSession = Server::get(\OC\User\Session::class);
1133
+        if (OC_User::handleApacheAuth()) {
1134
+            return true;
1135
+        }
1136
+        if (self::tryAppAPILogin($request)) {
1137
+            return true;
1138
+        }
1139
+        if ($userSession->tryTokenLogin($request)) {
1140
+            return true;
1141
+        }
1142
+        if (isset($_COOKIE['nc_username'])
1143
+            && isset($_COOKIE['nc_token'])
1144
+            && isset($_COOKIE['nc_session_id'])
1145
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1146
+            return true;
1147
+        }
1148
+        if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1149
+            return true;
1150
+        }
1151
+        return false;
1152
+    }
1153
+
1154
+    protected static function handleAuthHeaders(): void {
1155
+        //copy http auth headers for apache+php-fcgid work around
1156
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1157
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1158
+        }
1159
+
1160
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1161
+        $vars = [
1162
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1163
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1164
+        ];
1165
+        foreach ($vars as $var) {
1166
+            if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1167
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1168
+                if (count($credentials) === 2) {
1169
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1170
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1171
+                    break;
1172
+                }
1173
+            }
1174
+        }
1175
+    }
1176
+
1177
+    protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1178
+        if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1179
+            return false;
1180
+        }
1181
+        $appManager = Server::get(OCP\App\IAppManager::class);
1182
+        if (!$appManager->isEnabledForAnyone('app_api')) {
1183
+            return false;
1184
+        }
1185
+        try {
1186
+            $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1187
+            return $appAPIService->validateExAppRequestToNC($request);
1188
+        } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1189
+            return false;
1190
+        }
1191
+    }
1192 1192
 }
1193 1193
 
1194 1194
 OC::init();
Please login to merge, or discard this patch.