Completed
Pull Request — master (#3614)
by Björn
14:49
created
apps/dav/lib/CardDAV/SyncService.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -165,6 +165,7 @@  discard block
 block discarded – undo
165 165
 	 * @param string $url
166 166
 	 * @param string $sharedSecret
167 167
 	 * @param string $resourcePath
168
+	 * @param string $userName
168 169
 	 * @return array
169 170
 	 */
170 171
 	protected function download($url, $userName, $sharedSecret, $resourcePath) {
@@ -265,7 +266,7 @@  discard block
 block discarded – undo
265 266
 	}
266 267
 
267 268
 	/**
268
-	 * @return array|null
269
+	 * @return string
269 270
 	 */
270 271
 	public function getLocalSystemAddressBook() {
271 272
 		if (is_null($this->localSystemAddressBook)) {
Please login to merge, or discard this patch.
Indentation   +261 added lines, -261 removed lines patch added patch discarded remove patch
@@ -37,267 +37,267 @@
 block discarded – undo
37 37
 
38 38
 class SyncService {
39 39
 
40
-	/** @var CardDavBackend */
41
-	private $backend;
42
-
43
-	/** @var IUserManager */
44
-	private $userManager;
45
-
46
-	/** @var ILogger */
47
-	private $logger;
48
-
49
-	/** @var array */
50
-	private $localSystemAddressBook;
51
-
52
-	/** @var AccountManager */
53
-	private $accountManager;
54
-
55
-	/**
56
-	 * SyncService constructor.
57
-	 *
58
-	 * @param CardDavBackend $backend
59
-	 * @param IUserManager $userManager
60
-	 * @param ILogger $logger
61
-	 * @param AccountManager $accountManager
62
-	 */
63
-	public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
64
-		$this->backend = $backend;
65
-		$this->userManager = $userManager;
66
-		$this->logger = $logger;
67
-		$this->accountManager = $accountManager;
68
-	}
69
-
70
-	/**
71
-	 * @param string $url
72
-	 * @param string $userName
73
-	 * @param string $addressBookUrl
74
-	 * @param string $sharedSecret
75
-	 * @param string $syncToken
76
-	 * @param int $targetBookId
77
-	 * @param string $targetPrincipal
78
-	 * @param array $targetProperties
79
-	 * @return string
80
-	 * @throws \Exception
81
-	 */
82
-	public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
83
-		// 1. create addressbook
84
-		$book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
85
-		$addressBookId = $book['id'];
86
-
87
-		// 2. query changes
88
-		try {
89
-			$response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
90
-		} catch (ClientHttpException $ex) {
91
-			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
92
-				// remote server revoked access to the address book, remove it
93
-				$this->backend->deleteAddressBook($addressBookId);
94
-				$this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
95
-				throw $ex;
96
-			}
97
-		}
98
-
99
-		// 3. apply changes
100
-		// TODO: use multi-get for download
101
-		foreach ($response['response'] as $resource => $status) {
102
-			$cardUri = basename($resource);
103
-			if (isset($status[200])) {
104
-				$vCard = $this->download($url, $userName, $sharedSecret, $resource);
105
-				$existingCard = $this->backend->getCard($addressBookId, $cardUri);
106
-				if ($existingCard === false) {
107
-					$this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
108
-				} else {
109
-					$this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
110
-				}
111
-			} else {
112
-				$this->backend->deleteCard($addressBookId, $cardUri);
113
-			}
114
-		}
115
-
116
-		return $response['token'];
117
-	}
118
-
119
-	/**
120
-	 * @param string $principal
121
-	 * @param string $id
122
-	 * @param array $properties
123
-	 * @return array|null
124
-	 * @throws \Sabre\DAV\Exception\BadRequest
125
-	 */
126
-	public function ensureSystemAddressBookExists($principal, $id, $properties) {
127
-		$book = $this->backend->getAddressBooksByUri($principal, $id);
128
-		if (!is_null($book)) {
129
-			return $book;
130
-		}
131
-		$this->backend->createAddressBook($principal, $id, $properties);
132
-
133
-		return $this->backend->getAddressBooksByUri($principal, $id);
134
-	}
135
-
136
-	/**
137
-	 * @param string $url
138
-	 * @param string $userName
139
-	 * @param string $addressBookUrl
140
-	 * @param string $sharedSecret
141
-	 * @param string $syncToken
142
-	 * @return array
143
-	 */
144
-	protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
145
-		$settings = [
146
-			'baseUri' => $url . '/',
147
-			'userName' => $userName,
148
-			'password' => $sharedSecret,
149
-		];
150
-		$client = new Client($settings);
151
-		$client->setThrowExceptions(true);
152
-
153
-		$body = $this->buildSyncCollectionRequestBody($syncToken);
154
-
155
-		$response = $client->request('REPORT', $addressBookUrl, $body, [
156
-			'Content-Type' => 'application/xml'
157
-		]);
158
-
159
-		$result = $this->parseMultiStatus($response['body']);
160
-
161
-		return $result;
162
-	}
163
-
164
-	/**
165
-	 * @param string $url
166
-	 * @param string $sharedSecret
167
-	 * @param string $resourcePath
168
-	 * @return array
169
-	 */
170
-	protected function download($url, $userName, $sharedSecret, $resourcePath) {
171
-		$settings = [
172
-			'baseUri' => $url,
173
-			'userName' => $userName,
174
-			'password' => $sharedSecret,
175
-		];
176
-		$client = new Client($settings);
177
-		$client->setThrowExceptions(true);
178
-
179
-		$response = $client->request('GET', $resourcePath);
180
-		return $response;
181
-	}
182
-
183
-	/**
184
-	 * @param string|null $syncToken
185
-	 * @return string
186
-	 */
187
-	private function buildSyncCollectionRequestBody($syncToken) {
188
-
189
-		$dom = new \DOMDocument('1.0', 'UTF-8');
190
-		$dom->formatOutput = true;
191
-		$root = $dom->createElementNS('DAV:', 'd:sync-collection');
192
-		$sync = $dom->createElement('d:sync-token', $syncToken);
193
-		$prop = $dom->createElement('d:prop');
194
-		$cont = $dom->createElement('d:getcontenttype');
195
-		$etag = $dom->createElement('d:getetag');
196
-
197
-		$prop->appendChild($cont);
198
-		$prop->appendChild($etag);
199
-		$root->appendChild($sync);
200
-		$root->appendChild($prop);
201
-		$dom->appendChild($root);
202
-		$body = $dom->saveXML();
203
-
204
-		return $body;
205
-	}
206
-
207
-	/**
208
-	 * @param string $body
209
-	 * @return array
210
-	 * @throws \Sabre\Xml\ParseException
211
-	 */
212
-	private function parseMultiStatus($body) {
213
-		$xml = new Service();
214
-
215
-		/** @var MultiStatus $multiStatus */
216
-		$multiStatus = $xml->expect('{DAV:}multistatus', $body);
217
-
218
-		$result = [];
219
-		foreach ($multiStatus->getResponses() as $response) {
220
-			$result[$response->getHref()] = $response->getResponseProperties();
221
-		}
222
-
223
-		return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
224
-	}
225
-
226
-	/**
227
-	 * @param IUser $user
228
-	 */
229
-	public function updateUser($user) {
230
-		$systemAddressBook = $this->getLocalSystemAddressBook();
231
-		$addressBookId = $systemAddressBook['id'];
232
-		$converter = new Converter($this->accountManager);
233
-		$name = $user->getBackendClassName();
234
-		$userId = $user->getUID();
235
-
236
-		$cardId = "$name:$userId.vcf";
237
-		$card = $this->backend->getCard($addressBookId, $cardId);
238
-		if ($card === false) {
239
-			$vCard = $converter->createCardFromUser($user);
240
-			if ($vCard !== null) {
241
-				$this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
242
-			}
243
-		} else {
244
-			$vCard = $converter->createCardFromUser($user);
245
-			if (is_null($vCard)) {
246
-				$this->backend->deleteCard($addressBookId, $cardId);
247
-			} else {
248
-				$this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
249
-			}
250
-		}
251
-	}
252
-
253
-	/**
254
-	 * @param IUser|string $userOrCardId
255
-	 */
256
-	public function deleteUser($userOrCardId) {
257
-		$systemAddressBook = $this->getLocalSystemAddressBook();
258
-		if ($userOrCardId instanceof IUser){
259
-			$name = $userOrCardId->getBackendClassName();
260
-			$userId = $userOrCardId->getUID();
261
-
262
-			$userOrCardId = "$name:$userId.vcf";
263
-		}
264
-		$this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
265
-	}
266
-
267
-	/**
268
-	 * @return array|null
269
-	 */
270
-	public function getLocalSystemAddressBook() {
271
-		if (is_null($this->localSystemAddressBook)) {
272
-			$systemPrincipal = "principals/system/system";
273
-			$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
274
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
275
-			]);
276
-		}
277
-
278
-		return $this->localSystemAddressBook;
279
-	}
280
-
281
-	public function syncInstance(\Closure $progressCallback = null) {
282
-		$systemAddressBook = $this->getLocalSystemAddressBook();
283
-		$this->userManager->callForAllUsers(function($user) use ($systemAddressBook, $progressCallback) {
284
-			$this->updateUser($user);
285
-			if (!is_null($progressCallback)) {
286
-				$progressCallback();
287
-			}
288
-		});
289
-
290
-		// remove no longer existing
291
-		$allCards = $this->backend->getCards($systemAddressBook['id']);
292
-		foreach($allCards as $card) {
293
-			$vCard = Reader::read($card['carddata']);
294
-			$uid = $vCard->UID->getValue();
295
-			// load backend and see if user exists
296
-			if (!$this->userManager->userExists($uid)) {
297
-				$this->deleteUser($card['uri']);
298
-			}
299
-		}
300
-	}
40
+    /** @var CardDavBackend */
41
+    private $backend;
42
+
43
+    /** @var IUserManager */
44
+    private $userManager;
45
+
46
+    /** @var ILogger */
47
+    private $logger;
48
+
49
+    /** @var array */
50
+    private $localSystemAddressBook;
51
+
52
+    /** @var AccountManager */
53
+    private $accountManager;
54
+
55
+    /**
56
+     * SyncService constructor.
57
+     *
58
+     * @param CardDavBackend $backend
59
+     * @param IUserManager $userManager
60
+     * @param ILogger $logger
61
+     * @param AccountManager $accountManager
62
+     */
63
+    public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, AccountManager $accountManager) {
64
+        $this->backend = $backend;
65
+        $this->userManager = $userManager;
66
+        $this->logger = $logger;
67
+        $this->accountManager = $accountManager;
68
+    }
69
+
70
+    /**
71
+     * @param string $url
72
+     * @param string $userName
73
+     * @param string $addressBookUrl
74
+     * @param string $sharedSecret
75
+     * @param string $syncToken
76
+     * @param int $targetBookId
77
+     * @param string $targetPrincipal
78
+     * @param array $targetProperties
79
+     * @return string
80
+     * @throws \Exception
81
+     */
82
+    public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) {
83
+        // 1. create addressbook
84
+        $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties);
85
+        $addressBookId = $book['id'];
86
+
87
+        // 2. query changes
88
+        try {
89
+            $response = $this->requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken);
90
+        } catch (ClientHttpException $ex) {
91
+            if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
92
+                // remote server revoked access to the address book, remove it
93
+                $this->backend->deleteAddressBook($addressBookId);
94
+                $this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
95
+                throw $ex;
96
+            }
97
+        }
98
+
99
+        // 3. apply changes
100
+        // TODO: use multi-get for download
101
+        foreach ($response['response'] as $resource => $status) {
102
+            $cardUri = basename($resource);
103
+            if (isset($status[200])) {
104
+                $vCard = $this->download($url, $userName, $sharedSecret, $resource);
105
+                $existingCard = $this->backend->getCard($addressBookId, $cardUri);
106
+                if ($existingCard === false) {
107
+                    $this->backend->createCard($addressBookId, $cardUri, $vCard['body']);
108
+                } else {
109
+                    $this->backend->updateCard($addressBookId, $cardUri, $vCard['body']);
110
+                }
111
+            } else {
112
+                $this->backend->deleteCard($addressBookId, $cardUri);
113
+            }
114
+        }
115
+
116
+        return $response['token'];
117
+    }
118
+
119
+    /**
120
+     * @param string $principal
121
+     * @param string $id
122
+     * @param array $properties
123
+     * @return array|null
124
+     * @throws \Sabre\DAV\Exception\BadRequest
125
+     */
126
+    public function ensureSystemAddressBookExists($principal, $id, $properties) {
127
+        $book = $this->backend->getAddressBooksByUri($principal, $id);
128
+        if (!is_null($book)) {
129
+            return $book;
130
+        }
131
+        $this->backend->createAddressBook($principal, $id, $properties);
132
+
133
+        return $this->backend->getAddressBooksByUri($principal, $id);
134
+    }
135
+
136
+    /**
137
+     * @param string $url
138
+     * @param string $userName
139
+     * @param string $addressBookUrl
140
+     * @param string $sharedSecret
141
+     * @param string $syncToken
142
+     * @return array
143
+     */
144
+    protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
145
+        $settings = [
146
+            'baseUri' => $url . '/',
147
+            'userName' => $userName,
148
+            'password' => $sharedSecret,
149
+        ];
150
+        $client = new Client($settings);
151
+        $client->setThrowExceptions(true);
152
+
153
+        $body = $this->buildSyncCollectionRequestBody($syncToken);
154
+
155
+        $response = $client->request('REPORT', $addressBookUrl, $body, [
156
+            'Content-Type' => 'application/xml'
157
+        ]);
158
+
159
+        $result = $this->parseMultiStatus($response['body']);
160
+
161
+        return $result;
162
+    }
163
+
164
+    /**
165
+     * @param string $url
166
+     * @param string $sharedSecret
167
+     * @param string $resourcePath
168
+     * @return array
169
+     */
170
+    protected function download($url, $userName, $sharedSecret, $resourcePath) {
171
+        $settings = [
172
+            'baseUri' => $url,
173
+            'userName' => $userName,
174
+            'password' => $sharedSecret,
175
+        ];
176
+        $client = new Client($settings);
177
+        $client->setThrowExceptions(true);
178
+
179
+        $response = $client->request('GET', $resourcePath);
180
+        return $response;
181
+    }
182
+
183
+    /**
184
+     * @param string|null $syncToken
185
+     * @return string
186
+     */
187
+    private function buildSyncCollectionRequestBody($syncToken) {
188
+
189
+        $dom = new \DOMDocument('1.0', 'UTF-8');
190
+        $dom->formatOutput = true;
191
+        $root = $dom->createElementNS('DAV:', 'd:sync-collection');
192
+        $sync = $dom->createElement('d:sync-token', $syncToken);
193
+        $prop = $dom->createElement('d:prop');
194
+        $cont = $dom->createElement('d:getcontenttype');
195
+        $etag = $dom->createElement('d:getetag');
196
+
197
+        $prop->appendChild($cont);
198
+        $prop->appendChild($etag);
199
+        $root->appendChild($sync);
200
+        $root->appendChild($prop);
201
+        $dom->appendChild($root);
202
+        $body = $dom->saveXML();
203
+
204
+        return $body;
205
+    }
206
+
207
+    /**
208
+     * @param string $body
209
+     * @return array
210
+     * @throws \Sabre\Xml\ParseException
211
+     */
212
+    private function parseMultiStatus($body) {
213
+        $xml = new Service();
214
+
215
+        /** @var MultiStatus $multiStatus */
216
+        $multiStatus = $xml->expect('{DAV:}multistatus', $body);
217
+
218
+        $result = [];
219
+        foreach ($multiStatus->getResponses() as $response) {
220
+            $result[$response->getHref()] = $response->getResponseProperties();
221
+        }
222
+
223
+        return ['response' => $result, 'token' => $multiStatus->getSyncToken()];
224
+    }
225
+
226
+    /**
227
+     * @param IUser $user
228
+     */
229
+    public function updateUser($user) {
230
+        $systemAddressBook = $this->getLocalSystemAddressBook();
231
+        $addressBookId = $systemAddressBook['id'];
232
+        $converter = new Converter($this->accountManager);
233
+        $name = $user->getBackendClassName();
234
+        $userId = $user->getUID();
235
+
236
+        $cardId = "$name:$userId.vcf";
237
+        $card = $this->backend->getCard($addressBookId, $cardId);
238
+        if ($card === false) {
239
+            $vCard = $converter->createCardFromUser($user);
240
+            if ($vCard !== null) {
241
+                $this->backend->createCard($addressBookId, $cardId, $vCard->serialize());
242
+            }
243
+        } else {
244
+            $vCard = $converter->createCardFromUser($user);
245
+            if (is_null($vCard)) {
246
+                $this->backend->deleteCard($addressBookId, $cardId);
247
+            } else {
248
+                $this->backend->updateCard($addressBookId, $cardId, $vCard->serialize());
249
+            }
250
+        }
251
+    }
252
+
253
+    /**
254
+     * @param IUser|string $userOrCardId
255
+     */
256
+    public function deleteUser($userOrCardId) {
257
+        $systemAddressBook = $this->getLocalSystemAddressBook();
258
+        if ($userOrCardId instanceof IUser){
259
+            $name = $userOrCardId->getBackendClassName();
260
+            $userId = $userOrCardId->getUID();
261
+
262
+            $userOrCardId = "$name:$userId.vcf";
263
+        }
264
+        $this->backend->deleteCard($systemAddressBook['id'], $userOrCardId);
265
+    }
266
+
267
+    /**
268
+     * @return array|null
269
+     */
270
+    public function getLocalSystemAddressBook() {
271
+        if (is_null($this->localSystemAddressBook)) {
272
+            $systemPrincipal = "principals/system/system";
273
+            $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
274
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
275
+            ]);
276
+        }
277
+
278
+        return $this->localSystemAddressBook;
279
+    }
280
+
281
+    public function syncInstance(\Closure $progressCallback = null) {
282
+        $systemAddressBook = $this->getLocalSystemAddressBook();
283
+        $this->userManager->callForAllUsers(function($user) use ($systemAddressBook, $progressCallback) {
284
+            $this->updateUser($user);
285
+            if (!is_null($progressCallback)) {
286
+                $progressCallback();
287
+            }
288
+        });
289
+
290
+        // remove no longer existing
291
+        $allCards = $this->backend->getCards($systemAddressBook['id']);
292
+        foreach($allCards as $card) {
293
+            $vCard = Reader::read($card['carddata']);
294
+            $uid = $vCard->UID->getValue();
295
+            // load backend and see if user exists
296
+            if (!$this->userManager->userExists($uid)) {
297
+                $this->deleteUser($card['uri']);
298
+            }
299
+        }
300
+    }
301 301
 
302 302
 
303 303
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
92 92
 				// remote server revoked access to the address book, remove it
93 93
 				$this->backend->deleteAddressBook($addressBookId);
94
-				$this->logger->info('Authorization failed, remove address book: ' . $url, ['app' => 'dav']);
94
+				$this->logger->info('Authorization failed, remove address book: '.$url, ['app' => 'dav']);
95 95
 				throw $ex;
96 96
 			}
97 97
 		}
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	 */
144 144
 	protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) {
145 145
 		$settings = [
146
-			'baseUri' => $url . '/',
146
+			'baseUri' => $url.'/',
147 147
 			'userName' => $userName,
148 148
 			'password' => $sharedSecret,
149 149
 		];
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
 	 */
256 256
 	public function deleteUser($userOrCardId) {
257 257
 		$systemAddressBook = $this->getLocalSystemAddressBook();
258
-		if ($userOrCardId instanceof IUser){
258
+		if ($userOrCardId instanceof IUser) {
259 259
 			$name = $userOrCardId->getBackendClassName();
260 260
 			$userId = $userOrCardId->getUID();
261 261
 
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 		if (is_null($this->localSystemAddressBook)) {
272 272
 			$systemPrincipal = "principals/system/system";
273 273
 			$this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [
274
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => 'System addressbook which holds all users of this instance'
274
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => 'System addressbook which holds all users of this instance'
275 275
 			]);
276 276
 		}
277 277
 
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
 
290 290
 		// remove no longer existing
291 291
 		$allCards = $this->backend->getCards($systemAddressBook['id']);
292
-		foreach($allCards as $card) {
292
+		foreach ($allCards as $card) {
293 293
 			$vCard = Reader::read($card['carddata']);
294 294
 			$uid = $vCard->UID->getValue();
295 295
 			// load backend and see if user exists
Please login to merge, or discard this patch.
apps/federation/lib/BackgroundJob/GetSharedSecret.php 2 patches
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -48,171 +48,171 @@
 block discarded – undo
48 48
  */
49 49
 class GetSharedSecret extends Job{
50 50
 
51
-	/** @var IClient */
52
-	private $httpClient;
53
-
54
-	/** @var IJobList */
55
-	private $jobList;
56
-
57
-	/** @var IURLGenerator */
58
-	private $urlGenerator;
59
-
60
-	/** @var TrustedServers  */
61
-	private $trustedServers;
62
-
63
-	/** @var DbHandler */
64
-	private $dbHandler;
65
-
66
-	/** @var IDiscoveryService  */
67
-	private $ocsDiscoveryService;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/** @var bool */
73
-	protected $retainJob = false;
74
-
75
-	private $format = '?format=json';
76
-
77
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
78
-
79
-	/**
80
-	 * RequestSharedSecret constructor.
81
-	 *
82
-	 * @param IClient $httpClient
83
-	 * @param IURLGenerator $urlGenerator
84
-	 * @param IJobList $jobList
85
-	 * @param TrustedServers $trustedServers
86
-	 * @param ILogger $logger
87
-	 * @param DbHandler $dbHandler
88
-	 * @param IDiscoveryService $ocsDiscoveryService
89
-	 */
90
-	public function __construct(
91
-		IClient $httpClient = null,
92
-		IURLGenerator $urlGenerator = null,
93
-		IJobList $jobList = null,
94
-		TrustedServers $trustedServers = null,
95
-		ILogger $logger = null,
96
-		DbHandler $dbHandler = null,
97
-		IDiscoveryService $ocsDiscoveryService
98
-	) {
99
-		$this->logger = $logger ? $logger : \OC::$server->getLogger();
100
-		$this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
101
-		$this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
102
-		$this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
103
-		$this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
104
-		$this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->getOCSDiscoveryService();
105
-		if ($trustedServers) {
106
-			$this->trustedServers = $trustedServers;
107
-		} else {
108
-			$this->trustedServers = new TrustedServers(
109
-				$this->dbHandler,
110
-				\OC::$server->getHTTPClientService(),
111
-				$this->logger,
112
-				$this->jobList,
113
-				\OC::$server->getSecureRandom(),
114
-				\OC::$server->getConfig(),
115
-				\OC::$server->getEventDispatcher()
116
-			);
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * run the job, then remove it from the joblist
122
-	 *
123
-	 * @param JobList $jobList
124
-	 * @param ILogger $logger
125
-	 */
126
-	public function execute($jobList, ILogger $logger = null) {
127
-		$target = $this->argument['url'];
128
-		// only execute if target is still in the list of trusted domains
129
-		if ($this->trustedServers->isTrustedServer($target)) {
130
-			$this->parentExecute($jobList, $logger);
131
-		}
132
-
133
-		if (!$this->retainJob) {
134
-			$jobList->remove($this, $this->argument);
135
-		}
136
-	}
137
-
138
-	/**
139
-	 * call execute() method of parent
140
-	 *
141
-	 * @param JobList $jobList
142
-	 * @param ILogger $logger
143
-	 */
144
-	protected function parentExecute($jobList, $logger = null) {
145
-		parent::execute($jobList, $logger);
146
-	}
147
-
148
-	protected function run($argument) {
149
-		$target = $argument['url'];
150
-		$source = $this->urlGenerator->getAbsoluteURL('/');
151
-		$source = rtrim($source, '/');
152
-		$token = $argument['token'];
153
-
154
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
-
157
-		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
-
160
-		$result = null;
161
-		try {
162
-			$result = $this->httpClient->get(
163
-				$url,
164
-				[
165
-					'query' =>
166
-						[
167
-							'url' => $source,
168
-							'token' => $token
169
-						],
170
-					'timeout' => 3,
171
-					'connect_timeout' => 3,
172
-				]
173
-			);
174
-
175
-			$status = $result->getStatusCode();
176
-
177
-		} catch (ClientException $e) {
178
-			$status = $e->getCode();
179
-			if ($status === Http::STATUS_FORBIDDEN) {
180
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
181
-			} else {
182
-				$this->logger->logException($e, ['app' => 'federation']);
183
-			}
184
-		} catch (\Exception $e) {
185
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
186
-			$this->logger->logException($e, ['app' => 'federation']);
187
-		}
188
-
189
-		// if we received a unexpected response we try again later
190
-		if (
191
-			$status !== Http::STATUS_OK
192
-			&& $status !== Http::STATUS_FORBIDDEN
193
-		) {
194
-			$this->retainJob = true;
195
-		}  else {
196
-			// reset token if we received a valid response
197
-			$this->dbHandler->addToken($target, '');
198
-		}
199
-
200
-		if ($status === Http::STATUS_OK && $result instanceof IResponse) {
201
-			$body = $result->getBody();
202
-			$result = json_decode($body, true);
203
-			if (isset($result['ocs']['data']['sharedSecret'])) {
204
-				$this->trustedServers->addSharedSecret(
205
-						$target,
206
-						$result['ocs']['data']['sharedSecret']
207
-				);
208
-			} else {
209
-				$this->logger->error(
210
-						'remote server "' . $target . '"" does not return a valid shared secret',
211
-						['app' => 'federation']
212
-				);
213
-				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
214
-			}
215
-		}
216
-
217
-	}
51
+    /** @var IClient */
52
+    private $httpClient;
53
+
54
+    /** @var IJobList */
55
+    private $jobList;
56
+
57
+    /** @var IURLGenerator */
58
+    private $urlGenerator;
59
+
60
+    /** @var TrustedServers  */
61
+    private $trustedServers;
62
+
63
+    /** @var DbHandler */
64
+    private $dbHandler;
65
+
66
+    /** @var IDiscoveryService  */
67
+    private $ocsDiscoveryService;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /** @var bool */
73
+    protected $retainJob = false;
74
+
75
+    private $format = '?format=json';
76
+
77
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
78
+
79
+    /**
80
+     * RequestSharedSecret constructor.
81
+     *
82
+     * @param IClient $httpClient
83
+     * @param IURLGenerator $urlGenerator
84
+     * @param IJobList $jobList
85
+     * @param TrustedServers $trustedServers
86
+     * @param ILogger $logger
87
+     * @param DbHandler $dbHandler
88
+     * @param IDiscoveryService $ocsDiscoveryService
89
+     */
90
+    public function __construct(
91
+        IClient $httpClient = null,
92
+        IURLGenerator $urlGenerator = null,
93
+        IJobList $jobList = null,
94
+        TrustedServers $trustedServers = null,
95
+        ILogger $logger = null,
96
+        DbHandler $dbHandler = null,
97
+        IDiscoveryService $ocsDiscoveryService
98
+    ) {
99
+        $this->logger = $logger ? $logger : \OC::$server->getLogger();
100
+        $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
101
+        $this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
102
+        $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
103
+        $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
104
+        $this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->getOCSDiscoveryService();
105
+        if ($trustedServers) {
106
+            $this->trustedServers = $trustedServers;
107
+        } else {
108
+            $this->trustedServers = new TrustedServers(
109
+                $this->dbHandler,
110
+                \OC::$server->getHTTPClientService(),
111
+                $this->logger,
112
+                $this->jobList,
113
+                \OC::$server->getSecureRandom(),
114
+                \OC::$server->getConfig(),
115
+                \OC::$server->getEventDispatcher()
116
+            );
117
+        }
118
+    }
119
+
120
+    /**
121
+     * run the job, then remove it from the joblist
122
+     *
123
+     * @param JobList $jobList
124
+     * @param ILogger $logger
125
+     */
126
+    public function execute($jobList, ILogger $logger = null) {
127
+        $target = $this->argument['url'];
128
+        // only execute if target is still in the list of trusted domains
129
+        if ($this->trustedServers->isTrustedServer($target)) {
130
+            $this->parentExecute($jobList, $logger);
131
+        }
132
+
133
+        if (!$this->retainJob) {
134
+            $jobList->remove($this, $this->argument);
135
+        }
136
+    }
137
+
138
+    /**
139
+     * call execute() method of parent
140
+     *
141
+     * @param JobList $jobList
142
+     * @param ILogger $logger
143
+     */
144
+    protected function parentExecute($jobList, $logger = null) {
145
+        parent::execute($jobList, $logger);
146
+    }
147
+
148
+    protected function run($argument) {
149
+        $target = $argument['url'];
150
+        $source = $this->urlGenerator->getAbsoluteURL('/');
151
+        $source = rtrim($source, '/');
152
+        $token = $argument['token'];
153
+
154
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
+
157
+        // make sure that we have a well formated url
158
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
+
160
+        $result = null;
161
+        try {
162
+            $result = $this->httpClient->get(
163
+                $url,
164
+                [
165
+                    'query' =>
166
+                        [
167
+                            'url' => $source,
168
+                            'token' => $token
169
+                        ],
170
+                    'timeout' => 3,
171
+                    'connect_timeout' => 3,
172
+                ]
173
+            );
174
+
175
+            $status = $result->getStatusCode();
176
+
177
+        } catch (ClientException $e) {
178
+            $status = $e->getCode();
179
+            if ($status === Http::STATUS_FORBIDDEN) {
180
+                $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
181
+            } else {
182
+                $this->logger->logException($e, ['app' => 'federation']);
183
+            }
184
+        } catch (\Exception $e) {
185
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
186
+            $this->logger->logException($e, ['app' => 'federation']);
187
+        }
188
+
189
+        // if we received a unexpected response we try again later
190
+        if (
191
+            $status !== Http::STATUS_OK
192
+            && $status !== Http::STATUS_FORBIDDEN
193
+        ) {
194
+            $this->retainJob = true;
195
+        }  else {
196
+            // reset token if we received a valid response
197
+            $this->dbHandler->addToken($target, '');
198
+        }
199
+
200
+        if ($status === Http::STATUS_OK && $result instanceof IResponse) {
201
+            $body = $result->getBody();
202
+            $result = json_decode($body, true);
203
+            if (isset($result['ocs']['data']['sharedSecret'])) {
204
+                $this->trustedServers->addSharedSecret(
205
+                        $target,
206
+                        $result['ocs']['data']['sharedSecret']
207
+                );
208
+            } else {
209
+                $this->logger->error(
210
+                        'remote server "' . $target . '"" does not return a valid shared secret',
211
+                        ['app' => 'federation']
212
+                );
213
+                $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
214
+            }
215
+        }
216
+
217
+    }
218 218
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
  *
47 47
  * @package OCA\Federation\Backgroundjob
48 48
  */
49
-class GetSharedSecret extends Job{
49
+class GetSharedSecret extends Job {
50 50
 
51 51
 	/** @var IClient */
52 52
 	private $httpClient;
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156 156
 
157 157
 		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
158
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/').$this->format;
159 159
 
160 160
 		$result = null;
161 161
 		try {
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 		} catch (ClientException $e) {
178 178
 			$status = $e->getCode();
179 179
 			if ($status === Http::STATUS_FORBIDDEN) {
180
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
180
+				$this->logger->info($target.' refused to exchange a shared secret with you.', ['app' => 'federation']);
181 181
 			} else {
182 182
 				$this->logger->logException($e, ['app' => 'federation']);
183 183
 			}
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 			&& $status !== Http::STATUS_FORBIDDEN
193 193
 		) {
194 194
 			$this->retainJob = true;
195
-		}  else {
195
+		} else {
196 196
 			// reset token if we received a valid response
197 197
 			$this->dbHandler->addToken($target, '');
198 198
 		}
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 				);
208 208
 			} else {
209 209
 				$this->logger->error(
210
-						'remote server "' . $target . '"" does not return a valid shared secret',
210
+						'remote server "'.$target.'"" does not return a valid shared secret',
211 211
 						['app' => 'federation']
212 212
 				);
213 213
 				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
Please login to merge, or discard this patch.
apps/federation/lib/BackgroundJob/RequestSharedSecret.php 2 patches
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -48,154 +48,154 @@
 block discarded – undo
48 48
  */
49 49
 class RequestSharedSecret extends Job {
50 50
 
51
-	/** @var IClient */
52
-	private $httpClient;
53
-
54
-	/** @var IJobList */
55
-	private $jobList;
56
-
57
-	/** @var IURLGenerator */
58
-	private $urlGenerator;
59
-
60
-	/** @var DbHandler */
61
-	private $dbHandler;
62
-
63
-	/** @var TrustedServers */
64
-	private $trustedServers;
65
-
66
-	/** @var IDiscoveryService  */
67
-	private $ocsDiscoveryService;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/** @var bool */
73
-	protected $retainJob = false;
74
-
75
-	private $format = '?format=json';
76
-
77
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
78
-
79
-	/**
80
-	 * RequestSharedSecret constructor.
81
-	 *
82
-	 * @param IClient $httpClient
83
-	 * @param IURLGenerator $urlGenerator
84
-	 * @param IJobList $jobList
85
-	 * @param TrustedServers $trustedServers
86
-	 * @param DbHandler $dbHandler
87
-	 * @param IDiscoveryService $ocsDiscoveryService
88
-	 */
89
-	public function __construct(
90
-		IClient $httpClient = null,
91
-		IURLGenerator $urlGenerator = null,
92
-		IJobList $jobList = null,
93
-		TrustedServers $trustedServers = null,
94
-		DbHandler $dbHandler = null,
95
-		IDiscoveryService $ocsDiscoveryService
96
-	) {
97
-		$this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
98
-		$this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
99
-		$this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
100
-		$this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
101
-		$this->logger = \OC::$server->getLogger();
102
-		$this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->getOCSDiscoveryService();
103
-		if ($trustedServers) {
104
-			$this->trustedServers = $trustedServers;
105
-		} else {
106
-			$this->trustedServers = new TrustedServers(
107
-				$this->dbHandler,
108
-				\OC::$server->getHTTPClientService(),
109
-				$this->logger,
110
-				$this->jobList,
111
-				\OC::$server->getSecureRandom(),
112
-				\OC::$server->getConfig(),
113
-				\OC::$server->getEventDispatcher()
114
-			);
115
-		}
116
-	}
117
-
118
-
119
-	/**
120
-	 * run the job, then remove it from the joblist
121
-	 *
122
-	 * @param JobList $jobList
123
-	 * @param ILogger $logger
124
-	 */
125
-	public function execute($jobList, ILogger $logger = null) {
126
-		$target = $this->argument['url'];
127
-		// only execute if target is still in the list of trusted domains
128
-		if ($this->trustedServers->isTrustedServer($target)) {
129
-			$this->parentExecute($jobList, $logger);
130
-		}
131
-
132
-		if (!$this->retainJob) {
133
-			$jobList->remove($this, $this->argument);
134
-		}
135
-	}
136
-
137
-	/**
138
-	 * call execute() method of parent
139
-	 *
140
-	 * @param JobList $jobList
141
-	 * @param ILogger $logger
142
-	 */
143
-	protected function parentExecute($jobList, $logger) {
144
-		parent::execute($jobList, $logger);
145
-	}
146
-
147
-	protected function run($argument) {
148
-
149
-		$target = $argument['url'];
150
-		$source = $this->urlGenerator->getAbsoluteURL('/');
151
-		$source = rtrim($source, '/');
152
-		$token = $argument['token'];
153
-
154
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
-
157
-		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
-
160
-		try {
161
-			$result = $this->httpClient->post(
162
-				$url,
163
-				[
164
-					'body' => [
165
-						'url' => $source,
166
-						'token' => $token,
167
-					],
168
-					'timeout' => 3,
169
-					'connect_timeout' => 3,
170
-				]
171
-			);
172
-
173
-			$status = $result->getStatusCode();
174
-
175
-		} catch (ClientException $e) {
176
-			$status = $e->getCode();
177
-			if ($status === Http::STATUS_FORBIDDEN) {
178
-				$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
179
-			} else {
180
-				$this->logger->logException($e, ['app' => 'federation']);
181
-			}
182
-		} catch (\Exception $e) {
183
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
184
-			$this->logger->logException($e, ['app' => 'federation']);
185
-		}
186
-
187
-		// if we received a unexpected response we try again later
188
-		if (
189
-			$status !== Http::STATUS_OK
190
-			&& $status !== Http::STATUS_FORBIDDEN
191
-		) {
192
-			$this->retainJob = true;
193
-		}
194
-
195
-		if ($status === Http::STATUS_FORBIDDEN) {
196
-			// clear token if remote server refuses to ask for shared secret
197
-			$this->dbHandler->addToken($target, '');
198
-		}
199
-
200
-	}
51
+    /** @var IClient */
52
+    private $httpClient;
53
+
54
+    /** @var IJobList */
55
+    private $jobList;
56
+
57
+    /** @var IURLGenerator */
58
+    private $urlGenerator;
59
+
60
+    /** @var DbHandler */
61
+    private $dbHandler;
62
+
63
+    /** @var TrustedServers */
64
+    private $trustedServers;
65
+
66
+    /** @var IDiscoveryService  */
67
+    private $ocsDiscoveryService;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /** @var bool */
73
+    protected $retainJob = false;
74
+
75
+    private $format = '?format=json';
76
+
77
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
78
+
79
+    /**
80
+     * RequestSharedSecret constructor.
81
+     *
82
+     * @param IClient $httpClient
83
+     * @param IURLGenerator $urlGenerator
84
+     * @param IJobList $jobList
85
+     * @param TrustedServers $trustedServers
86
+     * @param DbHandler $dbHandler
87
+     * @param IDiscoveryService $ocsDiscoveryService
88
+     */
89
+    public function __construct(
90
+        IClient $httpClient = null,
91
+        IURLGenerator $urlGenerator = null,
92
+        IJobList $jobList = null,
93
+        TrustedServers $trustedServers = null,
94
+        DbHandler $dbHandler = null,
95
+        IDiscoveryService $ocsDiscoveryService
96
+    ) {
97
+        $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
98
+        $this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
99
+        $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
100
+        $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
101
+        $this->logger = \OC::$server->getLogger();
102
+        $this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->getOCSDiscoveryService();
103
+        if ($trustedServers) {
104
+            $this->trustedServers = $trustedServers;
105
+        } else {
106
+            $this->trustedServers = new TrustedServers(
107
+                $this->dbHandler,
108
+                \OC::$server->getHTTPClientService(),
109
+                $this->logger,
110
+                $this->jobList,
111
+                \OC::$server->getSecureRandom(),
112
+                \OC::$server->getConfig(),
113
+                \OC::$server->getEventDispatcher()
114
+            );
115
+        }
116
+    }
117
+
118
+
119
+    /**
120
+     * run the job, then remove it from the joblist
121
+     *
122
+     * @param JobList $jobList
123
+     * @param ILogger $logger
124
+     */
125
+    public function execute($jobList, ILogger $logger = null) {
126
+        $target = $this->argument['url'];
127
+        // only execute if target is still in the list of trusted domains
128
+        if ($this->trustedServers->isTrustedServer($target)) {
129
+            $this->parentExecute($jobList, $logger);
130
+        }
131
+
132
+        if (!$this->retainJob) {
133
+            $jobList->remove($this, $this->argument);
134
+        }
135
+    }
136
+
137
+    /**
138
+     * call execute() method of parent
139
+     *
140
+     * @param JobList $jobList
141
+     * @param ILogger $logger
142
+     */
143
+    protected function parentExecute($jobList, $logger) {
144
+        parent::execute($jobList, $logger);
145
+    }
146
+
147
+    protected function run($argument) {
148
+
149
+        $target = $argument['url'];
150
+        $source = $this->urlGenerator->getAbsoluteURL('/');
151
+        $source = rtrim($source, '/');
152
+        $token = $argument['token'];
153
+
154
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
+
157
+        // make sure that we have a well formated url
158
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
+
160
+        try {
161
+            $result = $this->httpClient->post(
162
+                $url,
163
+                [
164
+                    'body' => [
165
+                        'url' => $source,
166
+                        'token' => $token,
167
+                    ],
168
+                    'timeout' => 3,
169
+                    'connect_timeout' => 3,
170
+                ]
171
+            );
172
+
173
+            $status = $result->getStatusCode();
174
+
175
+        } catch (ClientException $e) {
176
+            $status = $e->getCode();
177
+            if ($status === Http::STATUS_FORBIDDEN) {
178
+                $this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
179
+            } else {
180
+                $this->logger->logException($e, ['app' => 'federation']);
181
+            }
182
+        } catch (\Exception $e) {
183
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
184
+            $this->logger->logException($e, ['app' => 'federation']);
185
+        }
186
+
187
+        // if we received a unexpected response we try again later
188
+        if (
189
+            $status !== Http::STATUS_OK
190
+            && $status !== Http::STATUS_FORBIDDEN
191
+        ) {
192
+            $this->retainJob = true;
193
+        }
194
+
195
+        if ($status === Http::STATUS_FORBIDDEN) {
196
+            // clear token if remote server refuses to ask for shared secret
197
+            $this->dbHandler->addToken($target, '');
198
+        }
199
+
200
+    }
201 201
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156 156
 
157 157
 		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
158
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/').$this->format;
159 159
 
160 160
 		try {
161 161
 			$result = $this->httpClient->post(
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 		} catch (ClientException $e) {
176 176
 			$status = $e->getCode();
177 177
 			if ($status === Http::STATUS_FORBIDDEN) {
178
-				$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
178
+				$this->logger->info($target.' refused to ask for a shared secret.', ['app' => 'federation']);
179 179
 			} else {
180 180
 				$this->logger->logException($e, ['app' => 'federation']);
181 181
 			}
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +1480 added lines, -1480 removed lines patch added patch discarded remove patch
@@ -109,1491 +109,1491 @@
 block discarded – undo
109 109
  * TODO: hookup all manager classes
110 110
  */
111 111
 class Server extends ServerContainer implements IServerContainer {
112
-	/** @var string */
113
-	private $webRoot;
114
-
115
-	/**
116
-	 * @param string $webRoot
117
-	 * @param \OC\Config $config
118
-	 */
119
-	public function __construct($webRoot, \OC\Config $config) {
120
-		parent::__construct();
121
-		$this->webRoot = $webRoot;
122
-
123
-		$this->registerService('ContactsManager', function ($c) {
124
-			return new ContactsManager();
125
-		});
126
-
127
-		$this->registerService('PreviewManager', function (Server $c) {
128
-			return new PreviewManager(
129
-				$c->getConfig(),
130
-				$c->getRootFolder(),
131
-				$c->getAppDataDir('preview'),
132
-				$c->getEventDispatcher(),
133
-				$c->getSession()->get('user_id')
134
-			);
135
-		});
136
-
137
-		$this->registerService('OCSDiscoveryService', function (Server $c) {
138
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
112
+    /** @var string */
113
+    private $webRoot;
114
+
115
+    /**
116
+     * @param string $webRoot
117
+     * @param \OC\Config $config
118
+     */
119
+    public function __construct($webRoot, \OC\Config $config) {
120
+        parent::__construct();
121
+        $this->webRoot = $webRoot;
122
+
123
+        $this->registerService('ContactsManager', function ($c) {
124
+            return new ContactsManager();
125
+        });
126
+
127
+        $this->registerService('PreviewManager', function (Server $c) {
128
+            return new PreviewManager(
129
+                $c->getConfig(),
130
+                $c->getRootFolder(),
131
+                $c->getAppDataDir('preview'),
132
+                $c->getEventDispatcher(),
133
+                $c->getSession()->get('user_id')
134
+            );
135
+        });
136
+
137
+        $this->registerService('OCSDiscoveryService', function (Server $c) {
138
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
139 139
 ;		});
140 140
 
141
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
142
-			return new \OC\Preview\Watcher(
143
-				$c->getAppDataDir('preview')
144
-			);
145
-		});
146
-
147
-		$this->registerService('EncryptionManager', function (Server $c) {
148
-			$view = new View();
149
-			$util = new Encryption\Util(
150
-				$view,
151
-				$c->getUserManager(),
152
-				$c->getGroupManager(),
153
-				$c->getConfig()
154
-			);
155
-			return new Encryption\Manager(
156
-				$c->getConfig(),
157
-				$c->getLogger(),
158
-				$c->getL10N('core'),
159
-				new View(),
160
-				$util,
161
-				new ArrayCache()
162
-			);
163
-		});
164
-
165
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
166
-			$util = new Encryption\Util(
167
-				new View(),
168
-				$c->getUserManager(),
169
-				$c->getGroupManager(),
170
-				$c->getConfig()
171
-			);
172
-			return new Encryption\File($util);
173
-		});
174
-
175
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
176
-			$view = new View();
177
-			$util = new Encryption\Util(
178
-				$view,
179
-				$c->getUserManager(),
180
-				$c->getGroupManager(),
181
-				$c->getConfig()
182
-			);
183
-
184
-			return new Encryption\Keys\Storage($view, $util);
185
-		});
186
-		$this->registerService('TagMapper', function (Server $c) {
187
-			return new TagMapper($c->getDatabaseConnection());
188
-		});
189
-		$this->registerService('TagManager', function (Server $c) {
190
-			$tagMapper = $c->query('TagMapper');
191
-			return new TagManager($tagMapper, $c->getUserSession());
192
-		});
193
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
194
-			$config = $c->getConfig();
195
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
196
-			/** @var \OC\SystemTag\ManagerFactory $factory */
197
-			$factory = new $factoryClass($this);
198
-			return $factory;
199
-		});
200
-		$this->registerService('SystemTagManager', function (Server $c) {
201
-			return $c->query('SystemTagManagerFactory')->getManager();
202
-		});
203
-		$this->registerService('SystemTagObjectMapper', function (Server $c) {
204
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
205
-		});
206
-		$this->registerService('RootFolder', function (Server $c) {
207
-			$manager = \OC\Files\Filesystem::getMountManager(null);
208
-			$view = new View();
209
-			$root = new Root(
210
-				$manager,
211
-				$view,
212
-				null,
213
-				$c->getUserMountCache(),
214
-				$this->getLogger(),
215
-				$this->getUserManager()
216
-			);
217
-			$connector = new HookConnector($root, $view);
218
-			$connector->viewToNode();
219
-
220
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
221
-			$previewConnector->connectWatcher();
222
-
223
-			return $root;
224
-		});
225
-		$this->registerService('LazyRootFolder', function(Server $c) {
226
-			return new LazyRoot(function() use ($c) {
227
-				return $c->query('RootFolder');
228
-			});
229
-		});
230
-		$this->registerService('UserManager', function (Server $c) {
231
-			$config = $c->getConfig();
232
-			return new \OC\User\Manager($config);
233
-		});
234
-		$this->registerService('GroupManager', function (Server $c) {
235
-			$groupManager = new \OC\Group\Manager($this->getUserManager());
236
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
237
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
238
-			});
239
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
240
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
241
-			});
242
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
243
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
244
-			});
245
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
246
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
247
-			});
248
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
249
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
250
-			});
251
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
252
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
253
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
254
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
255
-			});
256
-			return $groupManager;
257
-		});
258
-		$this->registerService(Store::class, function(Server $c) {
259
-			$session = $c->getSession();
260
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
261
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
262
-			} else {
263
-				$tokenProvider = null;
264
-			}
265
-			$logger = $c->getLogger();
266
-			return new Store($session, $logger, $tokenProvider);
267
-		});
268
-		$this->registerAlias(IStore::class, Store::class);
269
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
270
-			$dbConnection = $c->getDatabaseConnection();
271
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
272
-		});
273
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
274
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
275
-			$crypto = $c->getCrypto();
276
-			$config = $c->getConfig();
277
-			$logger = $c->getLogger();
278
-			$timeFactory = new TimeFactory();
279
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
280
-		});
281
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
282
-		$this->registerService('UserSession', function (Server $c) {
283
-			$manager = $c->getUserManager();
284
-			$session = new \OC\Session\Memory('');
285
-			$timeFactory = new TimeFactory();
286
-			// Token providers might require a working database. This code
287
-			// might however be called when ownCloud is not yet setup.
288
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
289
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
290
-			} else {
291
-				$defaultTokenProvider = null;
292
-			}
293
-
294
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
295
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
296
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
297
-			});
298
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
299
-				/** @var $user \OC\User\User */
300
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
301
-			});
302
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
303
-				/** @var $user \OC\User\User */
304
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
305
-			});
306
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
307
-				/** @var $user \OC\User\User */
308
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
309
-			});
310
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
311
-				/** @var $user \OC\User\User */
312
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
313
-			});
314
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
315
-				/** @var $user \OC\User\User */
316
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
317
-			});
318
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
319
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
320
-			});
321
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
322
-				/** @var $user \OC\User\User */
323
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
324
-			});
325
-			$userSession->listen('\OC\User', 'logout', function () {
326
-				\OC_Hook::emit('OC_User', 'logout', array());
327
-			});
328
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
329
-				/** @var $user \OC\User\User */
330
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
331
-			});
332
-			return $userSession;
333
-		});
334
-
335
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
336
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
337
-		});
338
-
339
-		$this->registerService('NavigationManager', function (Server $c) {
340
-			return new \OC\NavigationManager($c->getAppManager(),
341
-				$c->getURLGenerator(),
342
-				$c->getL10NFactory(),
343
-				$c->getUserSession(),
344
-				$c->getGroupManager());
345
-		});
346
-		$this->registerService('AllConfig', function (Server $c) {
347
-			return new \OC\AllConfig(
348
-				$c->getSystemConfig()
349
-			);
350
-		});
351
-		$this->registerService('SystemConfig', function ($c) use ($config) {
352
-			return new \OC\SystemConfig($config);
353
-		});
354
-		$this->registerService('AppConfig', function (Server $c) {
355
-			return new \OC\AppConfig($c->getDatabaseConnection());
356
-		});
357
-		$this->registerService('L10NFactory', function (Server $c) {
358
-			return new \OC\L10N\Factory(
359
-				$c->getConfig(),
360
-				$c->getRequest(),
361
-				$c->getUserSession(),
362
-				\OC::$SERVERROOT
363
-			);
364
-		});
365
-		$this->registerService('URLGenerator', function (Server $c) {
366
-			$config = $c->getConfig();
367
-			$cacheFactory = $c->getMemCacheFactory();
368
-			return new \OC\URLGenerator(
369
-				$config,
370
-				$cacheFactory
371
-			);
372
-		});
373
-		$this->registerService('AppHelper', function ($c) {
374
-			return new \OC\AppHelper();
375
-		});
376
-		$this->registerService('AppFetcher', function ($c) {
377
-			return new AppFetcher(
378
-				$this->getAppDataDir('appstore'),
379
-				$this->getHTTPClientService(),
380
-				$this->query(TimeFactory::class),
381
-				$this->getConfig()
382
-			);
383
-		});
384
-		$this->registerService('CategoryFetcher', function ($c) {
385
-			return new CategoryFetcher(
386
-				$this->getAppDataDir('appstore'),
387
-				$this->getHTTPClientService(),
388
-				$this->query(TimeFactory::class),
389
-				$this->getConfig()
390
-			);
391
-		});
392
-		$this->registerService('UserCache', function ($c) {
393
-			return new Cache\File();
394
-		});
395
-		$this->registerService('MemCacheFactory', function (Server $c) {
396
-			$config = $c->getConfig();
397
-
398
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
399
-				$v = \OC_App::getAppVersions();
400
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
401
-				$version = implode(',', $v);
402
-				$instanceId = \OC_Util::getInstanceId();
403
-				$path = \OC::$SERVERROOT;
404
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
405
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
406
-					$config->getSystemValue('memcache.local', null),
407
-					$config->getSystemValue('memcache.distributed', null),
408
-					$config->getSystemValue('memcache.locking', null)
409
-				);
410
-			}
411
-
412
-			return new \OC\Memcache\Factory('', $c->getLogger(),
413
-				'\\OC\\Memcache\\ArrayCache',
414
-				'\\OC\\Memcache\\ArrayCache',
415
-				'\\OC\\Memcache\\ArrayCache'
416
-			);
417
-		});
418
-		$this->registerService('RedisFactory', function (Server $c) {
419
-			$systemConfig = $c->getSystemConfig();
420
-			return new RedisFactory($systemConfig);
421
-		});
422
-		$this->registerService('ActivityManager', function (Server $c) {
423
-			return new \OC\Activity\Manager(
424
-				$c->getRequest(),
425
-				$c->getUserSession(),
426
-				$c->getConfig(),
427
-				$c->query(IValidator::class)
428
-			);
429
-		});
430
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
431
-			return new \OC\Activity\EventMerger(
432
-				$c->getL10N('lib')
433
-			);
434
-		});
435
-		$this->registerAlias(IValidator::class, Validator::class);
436
-		$this->registerService('AvatarManager', function (Server $c) {
437
-			return new AvatarManager(
438
-				$c->getUserManager(),
439
-				$c->getAppDataDir('avatar'),
440
-				$c->getL10N('lib'),
441
-				$c->getLogger(),
442
-				$c->getConfig()
443
-			);
444
-		});
445
-		$this->registerService('Logger', function (Server $c) {
446
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
447
-			$logger = Log::getLogClass($logType);
448
-			call_user_func(array($logger, 'init'));
449
-
450
-			return new Log($logger);
451
-		});
452
-		$this->registerService('JobList', function (Server $c) {
453
-			$config = $c->getConfig();
454
-			return new \OC\BackgroundJob\JobList(
455
-				$c->getDatabaseConnection(),
456
-				$config,
457
-				new TimeFactory()
458
-			);
459
-		});
460
-		$this->registerService('Router', function (Server $c) {
461
-			$cacheFactory = $c->getMemCacheFactory();
462
-			$logger = $c->getLogger();
463
-			if ($cacheFactory->isAvailable()) {
464
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
465
-			} else {
466
-				$router = new \OC\Route\Router($logger);
467
-			}
468
-			return $router;
469
-		});
470
-		$this->registerService('Search', function ($c) {
471
-			return new Search();
472
-		});
473
-		$this->registerService('SecureRandom', function ($c) {
474
-			return new SecureRandom();
475
-		});
476
-		$this->registerService('Crypto', function (Server $c) {
477
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
478
-		});
479
-		$this->registerService('Hasher', function (Server $c) {
480
-			return new Hasher($c->getConfig());
481
-		});
482
-		$this->registerService('CredentialsManager', function (Server $c) {
483
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
484
-		});
485
-		$this->registerService('DatabaseConnection', function (Server $c) {
486
-			$systemConfig = $c->getSystemConfig();
487
-			$factory = new \OC\DB\ConnectionFactory($c->getConfig());
488
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
489
-			if (!$factory->isValidType($type)) {
490
-				throw new \OC\DatabaseException('Invalid database type');
491
-			}
492
-			$connectionParams = $factory->createConnectionParams($systemConfig);
493
-			$connection = $factory->getConnection($type, $connectionParams);
494
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
495
-			return $connection;
496
-		});
497
-		$this->registerService('HTTPHelper', function (Server $c) {
498
-			$config = $c->getConfig();
499
-			return new HTTPHelper(
500
-				$config,
501
-				$c->getHTTPClientService()
502
-			);
503
-		});
504
-		$this->registerService('HttpClientService', function (Server $c) {
505
-			$user = \OC_User::getUser();
506
-			$uid = $user ? $user : null;
507
-			return new ClientService(
508
-				$c->getConfig(),
509
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
510
-			);
511
-		});
512
-		$this->registerService('EventLogger', function (Server $c) {
513
-			if ($c->getSystemConfig()->getValue('debug', false)) {
514
-				return new EventLogger();
515
-			} else {
516
-				return new NullEventLogger();
517
-			}
518
-		});
519
-		$this->registerService('QueryLogger', function (Server $c) {
520
-			if ($c->getSystemConfig()->getValue('debug', false)) {
521
-				return new QueryLogger();
522
-			} else {
523
-				return new NullQueryLogger();
524
-			}
525
-		});
526
-		$this->registerService('TempManager', function (Server $c) {
527
-			return new TempManager(
528
-				$c->getLogger(),
529
-				$c->getConfig()
530
-			);
531
-		});
532
-		$this->registerService('AppManager', function (Server $c) {
533
-			return new \OC\App\AppManager(
534
-				$c->getUserSession(),
535
-				$c->getAppConfig(),
536
-				$c->getGroupManager(),
537
-				$c->getMemCacheFactory(),
538
-				$c->getEventDispatcher()
539
-			);
540
-		});
541
-		$this->registerService('DateTimeZone', function (Server $c) {
542
-			return new DateTimeZone(
543
-				$c->getConfig(),
544
-				$c->getSession()
545
-			);
546
-		});
547
-		$this->registerService('DateTimeFormatter', function (Server $c) {
548
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
549
-
550
-			return new DateTimeFormatter(
551
-				$c->getDateTimeZone()->getTimeZone(),
552
-				$c->getL10N('lib', $language)
553
-			);
554
-		});
555
-		$this->registerService('UserMountCache', function (Server $c) {
556
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
557
-			$listener = new UserMountCacheListener($mountCache);
558
-			$listener->listen($c->getUserManager());
559
-			return $mountCache;
560
-		});
561
-		$this->registerService('MountConfigManager', function (Server $c) {
562
-			$loader = \OC\Files\Filesystem::getLoader();
563
-			$mountCache = $c->query('UserMountCache');
564
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
565
-
566
-			// builtin providers
567
-
568
-			$config = $c->getConfig();
569
-			$manager->registerProvider(new CacheMountProvider($config));
570
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
571
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
572
-
573
-			return $manager;
574
-		});
575
-		$this->registerService('IniWrapper', function ($c) {
576
-			return new IniGetWrapper();
577
-		});
578
-		$this->registerService('AsyncCommandBus', function (Server $c) {
579
-			$jobList = $c->getJobList();
580
-			return new AsyncBus($jobList);
581
-		});
582
-		$this->registerService('TrustedDomainHelper', function ($c) {
583
-			return new TrustedDomainHelper($this->getConfig());
584
-		});
585
-		$this->registerService('Throttler', function(Server $c) {
586
-			return new Throttler(
587
-				$c->getDatabaseConnection(),
588
-				new TimeFactory(),
589
-				$c->getLogger(),
590
-				$c->getConfig()
591
-			);
592
-		});
593
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
594
-			// IConfig and IAppManager requires a working database. This code
595
-			// might however be called when ownCloud is not yet setup.
596
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
597
-				$config = $c->getConfig();
598
-				$appManager = $c->getAppManager();
599
-			} else {
600
-				$config = null;
601
-				$appManager = null;
602
-			}
603
-
604
-			return new Checker(
605
-					new EnvironmentHelper(),
606
-					new FileAccessHelper(),
607
-					new AppLocator(),
608
-					$config,
609
-					$c->getMemCacheFactory(),
610
-					$appManager,
611
-					$c->getTempManager()
612
-			);
613
-		});
614
-		$this->registerService('Request', function ($c) {
615
-			if (isset($this['urlParams'])) {
616
-				$urlParams = $this['urlParams'];
617
-			} else {
618
-				$urlParams = [];
619
-			}
620
-
621
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
622
-				&& in_array('fakeinput', stream_get_wrappers())
623
-			) {
624
-				$stream = 'fakeinput://data';
625
-			} else {
626
-				$stream = 'php://input';
627
-			}
628
-
629
-			return new Request(
630
-				[
631
-					'get' => $_GET,
632
-					'post' => $_POST,
633
-					'files' => $_FILES,
634
-					'server' => $_SERVER,
635
-					'env' => $_ENV,
636
-					'cookies' => $_COOKIE,
637
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
638
-						? $_SERVER['REQUEST_METHOD']
639
-						: null,
640
-					'urlParams' => $urlParams,
641
-				],
642
-				$this->getSecureRandom(),
643
-				$this->getConfig(),
644
-				$this->getCsrfTokenManager(),
645
-				$stream
646
-			);
647
-		});
648
-		$this->registerService('Mailer', function (Server $c) {
649
-			return new Mailer(
650
-				$c->getConfig(),
651
-				$c->getLogger(),
652
-				$c->getThemingDefaults()
653
-			);
654
-		});
655
-		$this->registerService('LDAPProvider', function(Server $c) {
656
-			$config = $c->getConfig();
657
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
658
-			if(is_null($factoryClass)) {
659
-				throw new \Exception('ldapProviderFactory not set');
660
-			}
661
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
662
-			$factory = new $factoryClass($this);
663
-			return $factory->getLDAPProvider();
664
-		});
665
-		$this->registerService('LockingProvider', function (Server $c) {
666
-			$ini = $c->getIniWrapper();
667
-			$config = $c->getConfig();
668
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
669
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
670
-				/** @var \OC\Memcache\Factory $memcacheFactory */
671
-				$memcacheFactory = $c->getMemCacheFactory();
672
-				$memcache = $memcacheFactory->createLocking('lock');
673
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
674
-					return new MemcacheLockingProvider($memcache, $ttl);
675
-				}
676
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
677
-			}
678
-			return new NoopLockingProvider();
679
-		});
680
-		$this->registerService('MountManager', function () {
681
-			return new \OC\Files\Mount\Manager();
682
-		});
683
-		$this->registerService('MimeTypeDetector', function (Server $c) {
684
-			return new \OC\Files\Type\Detection(
685
-				$c->getURLGenerator(),
686
-				\OC::$configDir,
687
-				\OC::$SERVERROOT . '/resources/config/'
688
-			);
689
-		});
690
-		$this->registerService('MimeTypeLoader', function (Server $c) {
691
-			return new \OC\Files\Type\Loader(
692
-				$c->getDatabaseConnection()
693
-			);
694
-		});
695
-		$this->registerService('NotificationManager', function (Server $c) {
696
-			return new Manager(
697
-				$c->query(IValidator::class)
698
-			);
699
-		});
700
-		$this->registerService('CapabilitiesManager', function (Server $c) {
701
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
702
-			$manager->registerCapability(function () use ($c) {
703
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
704
-			});
705
-			return $manager;
706
-		});
707
-		$this->registerService('CommentsManager', function(Server $c) {
708
-			$config = $c->getConfig();
709
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
710
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
711
-			$factory = new $factoryClass($this);
712
-			return $factory->getManager();
713
-		});
714
-		$this->registerService('ThemingDefaults', function(Server $c) {
715
-			/*
141
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
142
+            return new \OC\Preview\Watcher(
143
+                $c->getAppDataDir('preview')
144
+            );
145
+        });
146
+
147
+        $this->registerService('EncryptionManager', function (Server $c) {
148
+            $view = new View();
149
+            $util = new Encryption\Util(
150
+                $view,
151
+                $c->getUserManager(),
152
+                $c->getGroupManager(),
153
+                $c->getConfig()
154
+            );
155
+            return new Encryption\Manager(
156
+                $c->getConfig(),
157
+                $c->getLogger(),
158
+                $c->getL10N('core'),
159
+                new View(),
160
+                $util,
161
+                new ArrayCache()
162
+            );
163
+        });
164
+
165
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
166
+            $util = new Encryption\Util(
167
+                new View(),
168
+                $c->getUserManager(),
169
+                $c->getGroupManager(),
170
+                $c->getConfig()
171
+            );
172
+            return new Encryption\File($util);
173
+        });
174
+
175
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
176
+            $view = new View();
177
+            $util = new Encryption\Util(
178
+                $view,
179
+                $c->getUserManager(),
180
+                $c->getGroupManager(),
181
+                $c->getConfig()
182
+            );
183
+
184
+            return new Encryption\Keys\Storage($view, $util);
185
+        });
186
+        $this->registerService('TagMapper', function (Server $c) {
187
+            return new TagMapper($c->getDatabaseConnection());
188
+        });
189
+        $this->registerService('TagManager', function (Server $c) {
190
+            $tagMapper = $c->query('TagMapper');
191
+            return new TagManager($tagMapper, $c->getUserSession());
192
+        });
193
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
194
+            $config = $c->getConfig();
195
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
196
+            /** @var \OC\SystemTag\ManagerFactory $factory */
197
+            $factory = new $factoryClass($this);
198
+            return $factory;
199
+        });
200
+        $this->registerService('SystemTagManager', function (Server $c) {
201
+            return $c->query('SystemTagManagerFactory')->getManager();
202
+        });
203
+        $this->registerService('SystemTagObjectMapper', function (Server $c) {
204
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
205
+        });
206
+        $this->registerService('RootFolder', function (Server $c) {
207
+            $manager = \OC\Files\Filesystem::getMountManager(null);
208
+            $view = new View();
209
+            $root = new Root(
210
+                $manager,
211
+                $view,
212
+                null,
213
+                $c->getUserMountCache(),
214
+                $this->getLogger(),
215
+                $this->getUserManager()
216
+            );
217
+            $connector = new HookConnector($root, $view);
218
+            $connector->viewToNode();
219
+
220
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
221
+            $previewConnector->connectWatcher();
222
+
223
+            return $root;
224
+        });
225
+        $this->registerService('LazyRootFolder', function(Server $c) {
226
+            return new LazyRoot(function() use ($c) {
227
+                return $c->query('RootFolder');
228
+            });
229
+        });
230
+        $this->registerService('UserManager', function (Server $c) {
231
+            $config = $c->getConfig();
232
+            return new \OC\User\Manager($config);
233
+        });
234
+        $this->registerService('GroupManager', function (Server $c) {
235
+            $groupManager = new \OC\Group\Manager($this->getUserManager());
236
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
237
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
238
+            });
239
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
240
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
241
+            });
242
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
243
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
244
+            });
245
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
246
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
247
+            });
248
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
249
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
250
+            });
251
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
252
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
253
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
254
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
255
+            });
256
+            return $groupManager;
257
+        });
258
+        $this->registerService(Store::class, function(Server $c) {
259
+            $session = $c->getSession();
260
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
261
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
262
+            } else {
263
+                $tokenProvider = null;
264
+            }
265
+            $logger = $c->getLogger();
266
+            return new Store($session, $logger, $tokenProvider);
267
+        });
268
+        $this->registerAlias(IStore::class, Store::class);
269
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
270
+            $dbConnection = $c->getDatabaseConnection();
271
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
272
+        });
273
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
274
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
275
+            $crypto = $c->getCrypto();
276
+            $config = $c->getConfig();
277
+            $logger = $c->getLogger();
278
+            $timeFactory = new TimeFactory();
279
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
280
+        });
281
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
282
+        $this->registerService('UserSession', function (Server $c) {
283
+            $manager = $c->getUserManager();
284
+            $session = new \OC\Session\Memory('');
285
+            $timeFactory = new TimeFactory();
286
+            // Token providers might require a working database. This code
287
+            // might however be called when ownCloud is not yet setup.
288
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
289
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
290
+            } else {
291
+                $defaultTokenProvider = null;
292
+            }
293
+
294
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
295
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
296
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
297
+            });
298
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
299
+                /** @var $user \OC\User\User */
300
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
301
+            });
302
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
303
+                /** @var $user \OC\User\User */
304
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
305
+            });
306
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
307
+                /** @var $user \OC\User\User */
308
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
309
+            });
310
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
311
+                /** @var $user \OC\User\User */
312
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
313
+            });
314
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
315
+                /** @var $user \OC\User\User */
316
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
317
+            });
318
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
319
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
320
+            });
321
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
322
+                /** @var $user \OC\User\User */
323
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
324
+            });
325
+            $userSession->listen('\OC\User', 'logout', function () {
326
+                \OC_Hook::emit('OC_User', 'logout', array());
327
+            });
328
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
329
+                /** @var $user \OC\User\User */
330
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
331
+            });
332
+            return $userSession;
333
+        });
334
+
335
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
336
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
337
+        });
338
+
339
+        $this->registerService('NavigationManager', function (Server $c) {
340
+            return new \OC\NavigationManager($c->getAppManager(),
341
+                $c->getURLGenerator(),
342
+                $c->getL10NFactory(),
343
+                $c->getUserSession(),
344
+                $c->getGroupManager());
345
+        });
346
+        $this->registerService('AllConfig', function (Server $c) {
347
+            return new \OC\AllConfig(
348
+                $c->getSystemConfig()
349
+            );
350
+        });
351
+        $this->registerService('SystemConfig', function ($c) use ($config) {
352
+            return new \OC\SystemConfig($config);
353
+        });
354
+        $this->registerService('AppConfig', function (Server $c) {
355
+            return new \OC\AppConfig($c->getDatabaseConnection());
356
+        });
357
+        $this->registerService('L10NFactory', function (Server $c) {
358
+            return new \OC\L10N\Factory(
359
+                $c->getConfig(),
360
+                $c->getRequest(),
361
+                $c->getUserSession(),
362
+                \OC::$SERVERROOT
363
+            );
364
+        });
365
+        $this->registerService('URLGenerator', function (Server $c) {
366
+            $config = $c->getConfig();
367
+            $cacheFactory = $c->getMemCacheFactory();
368
+            return new \OC\URLGenerator(
369
+                $config,
370
+                $cacheFactory
371
+            );
372
+        });
373
+        $this->registerService('AppHelper', function ($c) {
374
+            return new \OC\AppHelper();
375
+        });
376
+        $this->registerService('AppFetcher', function ($c) {
377
+            return new AppFetcher(
378
+                $this->getAppDataDir('appstore'),
379
+                $this->getHTTPClientService(),
380
+                $this->query(TimeFactory::class),
381
+                $this->getConfig()
382
+            );
383
+        });
384
+        $this->registerService('CategoryFetcher', function ($c) {
385
+            return new CategoryFetcher(
386
+                $this->getAppDataDir('appstore'),
387
+                $this->getHTTPClientService(),
388
+                $this->query(TimeFactory::class),
389
+                $this->getConfig()
390
+            );
391
+        });
392
+        $this->registerService('UserCache', function ($c) {
393
+            return new Cache\File();
394
+        });
395
+        $this->registerService('MemCacheFactory', function (Server $c) {
396
+            $config = $c->getConfig();
397
+
398
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
399
+                $v = \OC_App::getAppVersions();
400
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
401
+                $version = implode(',', $v);
402
+                $instanceId = \OC_Util::getInstanceId();
403
+                $path = \OC::$SERVERROOT;
404
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
405
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
406
+                    $config->getSystemValue('memcache.local', null),
407
+                    $config->getSystemValue('memcache.distributed', null),
408
+                    $config->getSystemValue('memcache.locking', null)
409
+                );
410
+            }
411
+
412
+            return new \OC\Memcache\Factory('', $c->getLogger(),
413
+                '\\OC\\Memcache\\ArrayCache',
414
+                '\\OC\\Memcache\\ArrayCache',
415
+                '\\OC\\Memcache\\ArrayCache'
416
+            );
417
+        });
418
+        $this->registerService('RedisFactory', function (Server $c) {
419
+            $systemConfig = $c->getSystemConfig();
420
+            return new RedisFactory($systemConfig);
421
+        });
422
+        $this->registerService('ActivityManager', function (Server $c) {
423
+            return new \OC\Activity\Manager(
424
+                $c->getRequest(),
425
+                $c->getUserSession(),
426
+                $c->getConfig(),
427
+                $c->query(IValidator::class)
428
+            );
429
+        });
430
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
431
+            return new \OC\Activity\EventMerger(
432
+                $c->getL10N('lib')
433
+            );
434
+        });
435
+        $this->registerAlias(IValidator::class, Validator::class);
436
+        $this->registerService('AvatarManager', function (Server $c) {
437
+            return new AvatarManager(
438
+                $c->getUserManager(),
439
+                $c->getAppDataDir('avatar'),
440
+                $c->getL10N('lib'),
441
+                $c->getLogger(),
442
+                $c->getConfig()
443
+            );
444
+        });
445
+        $this->registerService('Logger', function (Server $c) {
446
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
447
+            $logger = Log::getLogClass($logType);
448
+            call_user_func(array($logger, 'init'));
449
+
450
+            return new Log($logger);
451
+        });
452
+        $this->registerService('JobList', function (Server $c) {
453
+            $config = $c->getConfig();
454
+            return new \OC\BackgroundJob\JobList(
455
+                $c->getDatabaseConnection(),
456
+                $config,
457
+                new TimeFactory()
458
+            );
459
+        });
460
+        $this->registerService('Router', function (Server $c) {
461
+            $cacheFactory = $c->getMemCacheFactory();
462
+            $logger = $c->getLogger();
463
+            if ($cacheFactory->isAvailable()) {
464
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
465
+            } else {
466
+                $router = new \OC\Route\Router($logger);
467
+            }
468
+            return $router;
469
+        });
470
+        $this->registerService('Search', function ($c) {
471
+            return new Search();
472
+        });
473
+        $this->registerService('SecureRandom', function ($c) {
474
+            return new SecureRandom();
475
+        });
476
+        $this->registerService('Crypto', function (Server $c) {
477
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
478
+        });
479
+        $this->registerService('Hasher', function (Server $c) {
480
+            return new Hasher($c->getConfig());
481
+        });
482
+        $this->registerService('CredentialsManager', function (Server $c) {
483
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
484
+        });
485
+        $this->registerService('DatabaseConnection', function (Server $c) {
486
+            $systemConfig = $c->getSystemConfig();
487
+            $factory = new \OC\DB\ConnectionFactory($c->getConfig());
488
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
489
+            if (!$factory->isValidType($type)) {
490
+                throw new \OC\DatabaseException('Invalid database type');
491
+            }
492
+            $connectionParams = $factory->createConnectionParams($systemConfig);
493
+            $connection = $factory->getConnection($type, $connectionParams);
494
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
495
+            return $connection;
496
+        });
497
+        $this->registerService('HTTPHelper', function (Server $c) {
498
+            $config = $c->getConfig();
499
+            return new HTTPHelper(
500
+                $config,
501
+                $c->getHTTPClientService()
502
+            );
503
+        });
504
+        $this->registerService('HttpClientService', function (Server $c) {
505
+            $user = \OC_User::getUser();
506
+            $uid = $user ? $user : null;
507
+            return new ClientService(
508
+                $c->getConfig(),
509
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
510
+            );
511
+        });
512
+        $this->registerService('EventLogger', function (Server $c) {
513
+            if ($c->getSystemConfig()->getValue('debug', false)) {
514
+                return new EventLogger();
515
+            } else {
516
+                return new NullEventLogger();
517
+            }
518
+        });
519
+        $this->registerService('QueryLogger', function (Server $c) {
520
+            if ($c->getSystemConfig()->getValue('debug', false)) {
521
+                return new QueryLogger();
522
+            } else {
523
+                return new NullQueryLogger();
524
+            }
525
+        });
526
+        $this->registerService('TempManager', function (Server $c) {
527
+            return new TempManager(
528
+                $c->getLogger(),
529
+                $c->getConfig()
530
+            );
531
+        });
532
+        $this->registerService('AppManager', function (Server $c) {
533
+            return new \OC\App\AppManager(
534
+                $c->getUserSession(),
535
+                $c->getAppConfig(),
536
+                $c->getGroupManager(),
537
+                $c->getMemCacheFactory(),
538
+                $c->getEventDispatcher()
539
+            );
540
+        });
541
+        $this->registerService('DateTimeZone', function (Server $c) {
542
+            return new DateTimeZone(
543
+                $c->getConfig(),
544
+                $c->getSession()
545
+            );
546
+        });
547
+        $this->registerService('DateTimeFormatter', function (Server $c) {
548
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
549
+
550
+            return new DateTimeFormatter(
551
+                $c->getDateTimeZone()->getTimeZone(),
552
+                $c->getL10N('lib', $language)
553
+            );
554
+        });
555
+        $this->registerService('UserMountCache', function (Server $c) {
556
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
557
+            $listener = new UserMountCacheListener($mountCache);
558
+            $listener->listen($c->getUserManager());
559
+            return $mountCache;
560
+        });
561
+        $this->registerService('MountConfigManager', function (Server $c) {
562
+            $loader = \OC\Files\Filesystem::getLoader();
563
+            $mountCache = $c->query('UserMountCache');
564
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
565
+
566
+            // builtin providers
567
+
568
+            $config = $c->getConfig();
569
+            $manager->registerProvider(new CacheMountProvider($config));
570
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
571
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
572
+
573
+            return $manager;
574
+        });
575
+        $this->registerService('IniWrapper', function ($c) {
576
+            return new IniGetWrapper();
577
+        });
578
+        $this->registerService('AsyncCommandBus', function (Server $c) {
579
+            $jobList = $c->getJobList();
580
+            return new AsyncBus($jobList);
581
+        });
582
+        $this->registerService('TrustedDomainHelper', function ($c) {
583
+            return new TrustedDomainHelper($this->getConfig());
584
+        });
585
+        $this->registerService('Throttler', function(Server $c) {
586
+            return new Throttler(
587
+                $c->getDatabaseConnection(),
588
+                new TimeFactory(),
589
+                $c->getLogger(),
590
+                $c->getConfig()
591
+            );
592
+        });
593
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
594
+            // IConfig and IAppManager requires a working database. This code
595
+            // might however be called when ownCloud is not yet setup.
596
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
597
+                $config = $c->getConfig();
598
+                $appManager = $c->getAppManager();
599
+            } else {
600
+                $config = null;
601
+                $appManager = null;
602
+            }
603
+
604
+            return new Checker(
605
+                    new EnvironmentHelper(),
606
+                    new FileAccessHelper(),
607
+                    new AppLocator(),
608
+                    $config,
609
+                    $c->getMemCacheFactory(),
610
+                    $appManager,
611
+                    $c->getTempManager()
612
+            );
613
+        });
614
+        $this->registerService('Request', function ($c) {
615
+            if (isset($this['urlParams'])) {
616
+                $urlParams = $this['urlParams'];
617
+            } else {
618
+                $urlParams = [];
619
+            }
620
+
621
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
622
+                && in_array('fakeinput', stream_get_wrappers())
623
+            ) {
624
+                $stream = 'fakeinput://data';
625
+            } else {
626
+                $stream = 'php://input';
627
+            }
628
+
629
+            return new Request(
630
+                [
631
+                    'get' => $_GET,
632
+                    'post' => $_POST,
633
+                    'files' => $_FILES,
634
+                    'server' => $_SERVER,
635
+                    'env' => $_ENV,
636
+                    'cookies' => $_COOKIE,
637
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
638
+                        ? $_SERVER['REQUEST_METHOD']
639
+                        : null,
640
+                    'urlParams' => $urlParams,
641
+                ],
642
+                $this->getSecureRandom(),
643
+                $this->getConfig(),
644
+                $this->getCsrfTokenManager(),
645
+                $stream
646
+            );
647
+        });
648
+        $this->registerService('Mailer', function (Server $c) {
649
+            return new Mailer(
650
+                $c->getConfig(),
651
+                $c->getLogger(),
652
+                $c->getThemingDefaults()
653
+            );
654
+        });
655
+        $this->registerService('LDAPProvider', function(Server $c) {
656
+            $config = $c->getConfig();
657
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
658
+            if(is_null($factoryClass)) {
659
+                throw new \Exception('ldapProviderFactory not set');
660
+            }
661
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
662
+            $factory = new $factoryClass($this);
663
+            return $factory->getLDAPProvider();
664
+        });
665
+        $this->registerService('LockingProvider', function (Server $c) {
666
+            $ini = $c->getIniWrapper();
667
+            $config = $c->getConfig();
668
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
669
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
670
+                /** @var \OC\Memcache\Factory $memcacheFactory */
671
+                $memcacheFactory = $c->getMemCacheFactory();
672
+                $memcache = $memcacheFactory->createLocking('lock');
673
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
674
+                    return new MemcacheLockingProvider($memcache, $ttl);
675
+                }
676
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
677
+            }
678
+            return new NoopLockingProvider();
679
+        });
680
+        $this->registerService('MountManager', function () {
681
+            return new \OC\Files\Mount\Manager();
682
+        });
683
+        $this->registerService('MimeTypeDetector', function (Server $c) {
684
+            return new \OC\Files\Type\Detection(
685
+                $c->getURLGenerator(),
686
+                \OC::$configDir,
687
+                \OC::$SERVERROOT . '/resources/config/'
688
+            );
689
+        });
690
+        $this->registerService('MimeTypeLoader', function (Server $c) {
691
+            return new \OC\Files\Type\Loader(
692
+                $c->getDatabaseConnection()
693
+            );
694
+        });
695
+        $this->registerService('NotificationManager', function (Server $c) {
696
+            return new Manager(
697
+                $c->query(IValidator::class)
698
+            );
699
+        });
700
+        $this->registerService('CapabilitiesManager', function (Server $c) {
701
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
702
+            $manager->registerCapability(function () use ($c) {
703
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
704
+            });
705
+            return $manager;
706
+        });
707
+        $this->registerService('CommentsManager', function(Server $c) {
708
+            $config = $c->getConfig();
709
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
710
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
711
+            $factory = new $factoryClass($this);
712
+            return $factory->getManager();
713
+        });
714
+        $this->registerService('ThemingDefaults', function(Server $c) {
715
+            /*
716 716
 			 * Dark magic for autoloader.
717 717
 			 * If we do a class_exists it will try to load the class which will
718 718
 			 * make composer cache the result. Resulting in errors when enabling
719 719
 			 * the theming app.
720 720
 			 */
721
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
722
-			if (isset($prefixes['OCA\\Theming\\'])) {
723
-				$classExists = true;
724
-			} else {
725
-				$classExists = false;
726
-			}
727
-
728
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
729
-				return new ThemingDefaults(
730
-					$c->getConfig(),
731
-					$c->getL10N('theming'),
732
-					$c->getURLGenerator(),
733
-					new \OC_Defaults(),
734
-					$c->getLazyRootFolder(),
735
-					$c->getMemCacheFactory()
736
-				);
737
-			}
738
-			return new \OC_Defaults();
739
-		});
740
-		$this->registerService('EventDispatcher', function () {
741
-			return new EventDispatcher();
742
-		});
743
-		$this->registerService('CryptoWrapper', function (Server $c) {
744
-			// FIXME: Instantiiated here due to cyclic dependency
745
-			$request = new Request(
746
-				[
747
-					'get' => $_GET,
748
-					'post' => $_POST,
749
-					'files' => $_FILES,
750
-					'server' => $_SERVER,
751
-					'env' => $_ENV,
752
-					'cookies' => $_COOKIE,
753
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
754
-						? $_SERVER['REQUEST_METHOD']
755
-						: null,
756
-				],
757
-				$c->getSecureRandom(),
758
-				$c->getConfig()
759
-			);
760
-
761
-			return new CryptoWrapper(
762
-				$c->getConfig(),
763
-				$c->getCrypto(),
764
-				$c->getSecureRandom(),
765
-				$request
766
-			);
767
-		});
768
-		$this->registerService('CsrfTokenManager', function (Server $c) {
769
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
770
-
771
-			return new CsrfTokenManager(
772
-				$tokenGenerator,
773
-				$c->query(SessionStorage::class)
774
-			);
775
-		});
776
-		$this->registerService(SessionStorage::class, function (Server $c) {
777
-			return new SessionStorage($c->getSession());
778
-		});
779
-		$this->registerService('ContentSecurityPolicyManager', function (Server $c) {
780
-			return new ContentSecurityPolicyManager();
781
-		});
782
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
783
-			return new ContentSecurityPolicyNonceManager(
784
-				$c->getCsrfTokenManager(),
785
-				$c->getRequest()
786
-			);
787
-		});
788
-		$this->registerService('ShareManager', function(Server $c) {
789
-			$config = $c->getConfig();
790
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
791
-			/** @var \OCP\Share\IProviderFactory $factory */
792
-			$factory = new $factoryClass($this);
793
-
794
-			$manager = new \OC\Share20\Manager(
795
-				$c->getLogger(),
796
-				$c->getConfig(),
797
-				$c->getSecureRandom(),
798
-				$c->getHasher(),
799
-				$c->getMountManager(),
800
-				$c->getGroupManager(),
801
-				$c->getL10N('core'),
802
-				$factory,
803
-				$c->getUserManager(),
804
-				$c->getLazyRootFolder(),
805
-				$c->getEventDispatcher()
806
-			);
807
-
808
-			return $manager;
809
-		});
810
-		$this->registerService('SettingsManager', function(Server $c) {
811
-			$manager = new \OC\Settings\Manager(
812
-				$c->getLogger(),
813
-				$c->getDatabaseConnection(),
814
-				$c->getL10N('lib'),
815
-				$c->getConfig(),
816
-				$c->getEncryptionManager(),
817
-				$c->getUserManager(),
818
-				$c->getLockingProvider(),
819
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
820
-				$c->getURLGenerator()
821
-			);
822
-			return $manager;
823
-		});
824
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
825
-			return new \OC\Files\AppData\Factory(
826
-				$c->getRootFolder(),
827
-				$c->getSystemConfig()
828
-			);
829
-		});
830
-
831
-		$this->registerService('LockdownManager', function (Server $c) {
832
-			return new LockdownManager();
833
-		});
834
-
835
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
836
-			return new CloudIdManager();
837
-		});
838
-
839
-		/* To trick DI since we don't extend the DIContainer here */
840
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
841
-			return new CleanPreviewsBackgroundJob(
842
-				$c->getRootFolder(),
843
-				$c->getLogger(),
844
-				$c->getJobList(),
845
-				new TimeFactory()
846
-			);
847
-		});
848
-	}
849
-
850
-	/**
851
-	 * @return \OCP\Contacts\IManager
852
-	 */
853
-	public function getContactsManager() {
854
-		return $this->query('ContactsManager');
855
-	}
856
-
857
-	/**
858
-	 * @return \OC\Encryption\Manager
859
-	 */
860
-	public function getEncryptionManager() {
861
-		return $this->query('EncryptionManager');
862
-	}
863
-
864
-	/**
865
-	 * @return \OC\Encryption\File
866
-	 */
867
-	public function getEncryptionFilesHelper() {
868
-		return $this->query('EncryptionFileHelper');
869
-	}
870
-
871
-	/**
872
-	 * @return \OCP\Encryption\Keys\IStorage
873
-	 */
874
-	public function getEncryptionKeyStorage() {
875
-		return $this->query('EncryptionKeyStorage');
876
-	}
877
-
878
-	/**
879
-	 * @return \OC\OCS\DiscoveryService
880
-	 */
881
-	public function getOCSDiscoveryService() {
882
-		return $this->query('OCSDiscoveryService');
883
-	}
884
-
885
-
886
-	/**
887
-	 * The current request object holding all information about the request
888
-	 * currently being processed is returned from this method.
889
-	 * In case the current execution was not initiated by a web request null is returned
890
-	 *
891
-	 * @return \OCP\IRequest
892
-	 */
893
-	public function getRequest() {
894
-		return $this->query('Request');
895
-	}
896
-
897
-	/**
898
-	 * Returns the preview manager which can create preview images for a given file
899
-	 *
900
-	 * @return \OCP\IPreview
901
-	 */
902
-	public function getPreviewManager() {
903
-		return $this->query('PreviewManager');
904
-	}
905
-
906
-	/**
907
-	 * Returns the tag manager which can get and set tags for different object types
908
-	 *
909
-	 * @see \OCP\ITagManager::load()
910
-	 * @return \OCP\ITagManager
911
-	 */
912
-	public function getTagManager() {
913
-		return $this->query('TagManager');
914
-	}
915
-
916
-	/**
917
-	 * Returns the system-tag manager
918
-	 *
919
-	 * @return \OCP\SystemTag\ISystemTagManager
920
-	 *
921
-	 * @since 9.0.0
922
-	 */
923
-	public function getSystemTagManager() {
924
-		return $this->query('SystemTagManager');
925
-	}
926
-
927
-	/**
928
-	 * Returns the system-tag object mapper
929
-	 *
930
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
931
-	 *
932
-	 * @since 9.0.0
933
-	 */
934
-	public function getSystemTagObjectMapper() {
935
-		return $this->query('SystemTagObjectMapper');
936
-	}
937
-
938
-	/**
939
-	 * Returns the avatar manager, used for avatar functionality
940
-	 *
941
-	 * @return \OCP\IAvatarManager
942
-	 */
943
-	public function getAvatarManager() {
944
-		return $this->query('AvatarManager');
945
-	}
946
-
947
-	/**
948
-	 * Returns the root folder of ownCloud's data directory
949
-	 *
950
-	 * @return \OCP\Files\IRootFolder
951
-	 */
952
-	public function getRootFolder() {
953
-		return $this->query('LazyRootFolder');
954
-	}
955
-
956
-	/**
957
-	 * Returns the root folder of ownCloud's data directory
958
-	 * This is the lazy variant so this gets only initialized once it
959
-	 * is actually used.
960
-	 *
961
-	 * @return \OCP\Files\IRootFolder
962
-	 */
963
-	public function getLazyRootFolder() {
964
-		return $this->query('LazyRootFolder');
965
-	}
966
-
967
-	/**
968
-	 * Returns a view to ownCloud's files folder
969
-	 *
970
-	 * @param string $userId user ID
971
-	 * @return \OCP\Files\Folder|null
972
-	 */
973
-	public function getUserFolder($userId = null) {
974
-		if ($userId === null) {
975
-			$user = $this->getUserSession()->getUser();
976
-			if (!$user) {
977
-				return null;
978
-			}
979
-			$userId = $user->getUID();
980
-		}
981
-		$root = $this->getRootFolder();
982
-		return $root->getUserFolder($userId);
983
-	}
984
-
985
-	/**
986
-	 * Returns an app-specific view in ownClouds data directory
987
-	 *
988
-	 * @return \OCP\Files\Folder
989
-	 * @deprecated since 9.2.0 use IAppData
990
-	 */
991
-	public function getAppFolder() {
992
-		$dir = '/' . \OC_App::getCurrentApp();
993
-		$root = $this->getRootFolder();
994
-		if (!$root->nodeExists($dir)) {
995
-			$folder = $root->newFolder($dir);
996
-		} else {
997
-			$folder = $root->get($dir);
998
-		}
999
-		return $folder;
1000
-	}
1001
-
1002
-	/**
1003
-	 * @return \OC\User\Manager
1004
-	 */
1005
-	public function getUserManager() {
1006
-		return $this->query('UserManager');
1007
-	}
1008
-
1009
-	/**
1010
-	 * @return \OC\Group\Manager
1011
-	 */
1012
-	public function getGroupManager() {
1013
-		return $this->query('GroupManager');
1014
-	}
1015
-
1016
-	/**
1017
-	 * @return \OC\User\Session
1018
-	 */
1019
-	public function getUserSession() {
1020
-		return $this->query('UserSession');
1021
-	}
1022
-
1023
-	/**
1024
-	 * @return \OCP\ISession
1025
-	 */
1026
-	public function getSession() {
1027
-		return $this->query('UserSession')->getSession();
1028
-	}
1029
-
1030
-	/**
1031
-	 * @param \OCP\ISession $session
1032
-	 */
1033
-	public function setSession(\OCP\ISession $session) {
1034
-		$this->query(SessionStorage::class)->setSession($session);
1035
-		$this->query('UserSession')->setSession($session);
1036
-		$this->query(Store::class)->setSession($session);
1037
-	}
1038
-
1039
-	/**
1040
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1041
-	 */
1042
-	public function getTwoFactorAuthManager() {
1043
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1044
-	}
1045
-
1046
-	/**
1047
-	 * @return \OC\NavigationManager
1048
-	 */
1049
-	public function getNavigationManager() {
1050
-		return $this->query('NavigationManager');
1051
-	}
1052
-
1053
-	/**
1054
-	 * @return \OCP\IConfig
1055
-	 */
1056
-	public function getConfig() {
1057
-		return $this->query('AllConfig');
1058
-	}
1059
-
1060
-	/**
1061
-	 * @internal For internal use only
1062
-	 * @return \OC\SystemConfig
1063
-	 */
1064
-	public function getSystemConfig() {
1065
-		return $this->query('SystemConfig');
1066
-	}
1067
-
1068
-	/**
1069
-	 * Returns the app config manager
1070
-	 *
1071
-	 * @return \OCP\IAppConfig
1072
-	 */
1073
-	public function getAppConfig() {
1074
-		return $this->query('AppConfig');
1075
-	}
1076
-
1077
-	/**
1078
-	 * @return \OCP\L10N\IFactory
1079
-	 */
1080
-	public function getL10NFactory() {
1081
-		return $this->query('L10NFactory');
1082
-	}
1083
-
1084
-	/**
1085
-	 * get an L10N instance
1086
-	 *
1087
-	 * @param string $app appid
1088
-	 * @param string $lang
1089
-	 * @return IL10N
1090
-	 */
1091
-	public function getL10N($app, $lang = null) {
1092
-		return $this->getL10NFactory()->get($app, $lang);
1093
-	}
1094
-
1095
-	/**
1096
-	 * @return \OCP\IURLGenerator
1097
-	 */
1098
-	public function getURLGenerator() {
1099
-		return $this->query('URLGenerator');
1100
-	}
1101
-
1102
-	/**
1103
-	 * @return \OCP\IHelper
1104
-	 */
1105
-	public function getHelper() {
1106
-		return $this->query('AppHelper');
1107
-	}
1108
-
1109
-	/**
1110
-	 * @return AppFetcher
1111
-	 */
1112
-	public function getAppFetcher() {
1113
-		return $this->query('AppFetcher');
1114
-	}
1115
-
1116
-	/**
1117
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1118
-	 * getMemCacheFactory() instead.
1119
-	 *
1120
-	 * @return \OCP\ICache
1121
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1122
-	 */
1123
-	public function getCache() {
1124
-		return $this->query('UserCache');
1125
-	}
1126
-
1127
-	/**
1128
-	 * Returns an \OCP\CacheFactory instance
1129
-	 *
1130
-	 * @return \OCP\ICacheFactory
1131
-	 */
1132
-	public function getMemCacheFactory() {
1133
-		return $this->query('MemCacheFactory');
1134
-	}
1135
-
1136
-	/**
1137
-	 * Returns an \OC\RedisFactory instance
1138
-	 *
1139
-	 * @return \OC\RedisFactory
1140
-	 */
1141
-	public function getGetRedisFactory() {
1142
-		return $this->query('RedisFactory');
1143
-	}
1144
-
1145
-
1146
-	/**
1147
-	 * Returns the current session
1148
-	 *
1149
-	 * @return \OCP\IDBConnection
1150
-	 */
1151
-	public function getDatabaseConnection() {
1152
-		return $this->query('DatabaseConnection');
1153
-	}
1154
-
1155
-	/**
1156
-	 * Returns the activity manager
1157
-	 *
1158
-	 * @return \OCP\Activity\IManager
1159
-	 */
1160
-	public function getActivityManager() {
1161
-		return $this->query('ActivityManager');
1162
-	}
1163
-
1164
-	/**
1165
-	 * Returns an job list for controlling background jobs
1166
-	 *
1167
-	 * @return \OCP\BackgroundJob\IJobList
1168
-	 */
1169
-	public function getJobList() {
1170
-		return $this->query('JobList');
1171
-	}
1172
-
1173
-	/**
1174
-	 * Returns a logger instance
1175
-	 *
1176
-	 * @return \OCP\ILogger
1177
-	 */
1178
-	public function getLogger() {
1179
-		return $this->query('Logger');
1180
-	}
1181
-
1182
-	/**
1183
-	 * Returns a router for generating and matching urls
1184
-	 *
1185
-	 * @return \OCP\Route\IRouter
1186
-	 */
1187
-	public function getRouter() {
1188
-		return $this->query('Router');
1189
-	}
1190
-
1191
-	/**
1192
-	 * Returns a search instance
1193
-	 *
1194
-	 * @return \OCP\ISearch
1195
-	 */
1196
-	public function getSearch() {
1197
-		return $this->query('Search');
1198
-	}
1199
-
1200
-	/**
1201
-	 * Returns a SecureRandom instance
1202
-	 *
1203
-	 * @return \OCP\Security\ISecureRandom
1204
-	 */
1205
-	public function getSecureRandom() {
1206
-		return $this->query('SecureRandom');
1207
-	}
1208
-
1209
-	/**
1210
-	 * Returns a Crypto instance
1211
-	 *
1212
-	 * @return \OCP\Security\ICrypto
1213
-	 */
1214
-	public function getCrypto() {
1215
-		return $this->query('Crypto');
1216
-	}
1217
-
1218
-	/**
1219
-	 * Returns a Hasher instance
1220
-	 *
1221
-	 * @return \OCP\Security\IHasher
1222
-	 */
1223
-	public function getHasher() {
1224
-		return $this->query('Hasher');
1225
-	}
1226
-
1227
-	/**
1228
-	 * Returns a CredentialsManager instance
1229
-	 *
1230
-	 * @return \OCP\Security\ICredentialsManager
1231
-	 */
1232
-	public function getCredentialsManager() {
1233
-		return $this->query('CredentialsManager');
1234
-	}
1235
-
1236
-	/**
1237
-	 * Returns an instance of the HTTP helper class
1238
-	 *
1239
-	 * @deprecated Use getHTTPClientService()
1240
-	 * @return \OC\HTTPHelper
1241
-	 */
1242
-	public function getHTTPHelper() {
1243
-		return $this->query('HTTPHelper');
1244
-	}
1245
-
1246
-	/**
1247
-	 * Get the certificate manager for the user
1248
-	 *
1249
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1250
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1251
-	 */
1252
-	public function getCertificateManager($userId = '') {
1253
-		if ($userId === '') {
1254
-			$userSession = $this->getUserSession();
1255
-			$user = $userSession->getUser();
1256
-			if (is_null($user)) {
1257
-				return null;
1258
-			}
1259
-			$userId = $user->getUID();
1260
-		}
1261
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1262
-	}
1263
-
1264
-	/**
1265
-	 * Returns an instance of the HTTP client service
1266
-	 *
1267
-	 * @return \OCP\Http\Client\IClientService
1268
-	 */
1269
-	public function getHTTPClientService() {
1270
-		return $this->query('HttpClientService');
1271
-	}
1272
-
1273
-	/**
1274
-	 * Create a new event source
1275
-	 *
1276
-	 * @return \OCP\IEventSource
1277
-	 */
1278
-	public function createEventSource() {
1279
-		return new \OC_EventSource();
1280
-	}
1281
-
1282
-	/**
1283
-	 * Get the active event logger
1284
-	 *
1285
-	 * The returned logger only logs data when debug mode is enabled
1286
-	 *
1287
-	 * @return \OCP\Diagnostics\IEventLogger
1288
-	 */
1289
-	public function getEventLogger() {
1290
-		return $this->query('EventLogger');
1291
-	}
1292
-
1293
-	/**
1294
-	 * Get the active query logger
1295
-	 *
1296
-	 * The returned logger only logs data when debug mode is enabled
1297
-	 *
1298
-	 * @return \OCP\Diagnostics\IQueryLogger
1299
-	 */
1300
-	public function getQueryLogger() {
1301
-		return $this->query('QueryLogger');
1302
-	}
1303
-
1304
-	/**
1305
-	 * Get the manager for temporary files and folders
1306
-	 *
1307
-	 * @return \OCP\ITempManager
1308
-	 */
1309
-	public function getTempManager() {
1310
-		return $this->query('TempManager');
1311
-	}
1312
-
1313
-	/**
1314
-	 * Get the app manager
1315
-	 *
1316
-	 * @return \OCP\App\IAppManager
1317
-	 */
1318
-	public function getAppManager() {
1319
-		return $this->query('AppManager');
1320
-	}
1321
-
1322
-	/**
1323
-	 * Creates a new mailer
1324
-	 *
1325
-	 * @return \OCP\Mail\IMailer
1326
-	 */
1327
-	public function getMailer() {
1328
-		return $this->query('Mailer');
1329
-	}
1330
-
1331
-	/**
1332
-	 * Get the webroot
1333
-	 *
1334
-	 * @return string
1335
-	 */
1336
-	public function getWebRoot() {
1337
-		return $this->webRoot;
1338
-	}
1339
-
1340
-	/**
1341
-	 * @return \OC\OCSClient
1342
-	 */
1343
-	public function getOcsClient() {
1344
-		return $this->query('OcsClient');
1345
-	}
1346
-
1347
-	/**
1348
-	 * @return \OCP\IDateTimeZone
1349
-	 */
1350
-	public function getDateTimeZone() {
1351
-		return $this->query('DateTimeZone');
1352
-	}
1353
-
1354
-	/**
1355
-	 * @return \OCP\IDateTimeFormatter
1356
-	 */
1357
-	public function getDateTimeFormatter() {
1358
-		return $this->query('DateTimeFormatter');
1359
-	}
1360
-
1361
-	/**
1362
-	 * @return \OCP\Files\Config\IMountProviderCollection
1363
-	 */
1364
-	public function getMountProviderCollection() {
1365
-		return $this->query('MountConfigManager');
1366
-	}
1367
-
1368
-	/**
1369
-	 * Get the IniWrapper
1370
-	 *
1371
-	 * @return IniGetWrapper
1372
-	 */
1373
-	public function getIniWrapper() {
1374
-		return $this->query('IniWrapper');
1375
-	}
1376
-
1377
-	/**
1378
-	 * @return \OCP\Command\IBus
1379
-	 */
1380
-	public function getCommandBus() {
1381
-		return $this->query('AsyncCommandBus');
1382
-	}
1383
-
1384
-	/**
1385
-	 * Get the trusted domain helper
1386
-	 *
1387
-	 * @return TrustedDomainHelper
1388
-	 */
1389
-	public function getTrustedDomainHelper() {
1390
-		return $this->query('TrustedDomainHelper');
1391
-	}
1392
-
1393
-	/**
1394
-	 * Get the locking provider
1395
-	 *
1396
-	 * @return \OCP\Lock\ILockingProvider
1397
-	 * @since 8.1.0
1398
-	 */
1399
-	public function getLockingProvider() {
1400
-		return $this->query('LockingProvider');
1401
-	}
1402
-
1403
-	/**
1404
-	 * @return \OCP\Files\Mount\IMountManager
1405
-	 **/
1406
-	function getMountManager() {
1407
-		return $this->query('MountManager');
1408
-	}
1409
-
1410
-	/** @return \OCP\Files\Config\IUserMountCache */
1411
-	function getUserMountCache() {
1412
-		return $this->query('UserMountCache');
1413
-	}
1414
-
1415
-	/**
1416
-	 * Get the MimeTypeDetector
1417
-	 *
1418
-	 * @return \OCP\Files\IMimeTypeDetector
1419
-	 */
1420
-	public function getMimeTypeDetector() {
1421
-		return $this->query('MimeTypeDetector');
1422
-	}
1423
-
1424
-	/**
1425
-	 * Get the MimeTypeLoader
1426
-	 *
1427
-	 * @return \OCP\Files\IMimeTypeLoader
1428
-	 */
1429
-	public function getMimeTypeLoader() {
1430
-		return $this->query('MimeTypeLoader');
1431
-	}
1432
-
1433
-	/**
1434
-	 * Get the manager of all the capabilities
1435
-	 *
1436
-	 * @return \OC\CapabilitiesManager
1437
-	 */
1438
-	public function getCapabilitiesManager() {
1439
-		return $this->query('CapabilitiesManager');
1440
-	}
1441
-
1442
-	/**
1443
-	 * Get the EventDispatcher
1444
-	 *
1445
-	 * @return EventDispatcherInterface
1446
-	 * @since 8.2.0
1447
-	 */
1448
-	public function getEventDispatcher() {
1449
-		return $this->query('EventDispatcher');
1450
-	}
1451
-
1452
-	/**
1453
-	 * Get the Notification Manager
1454
-	 *
1455
-	 * @return \OCP\Notification\IManager
1456
-	 * @since 8.2.0
1457
-	 */
1458
-	public function getNotificationManager() {
1459
-		return $this->query('NotificationManager');
1460
-	}
1461
-
1462
-	/**
1463
-	 * @return \OCP\Comments\ICommentsManager
1464
-	 */
1465
-	public function getCommentsManager() {
1466
-		return $this->query('CommentsManager');
1467
-	}
1468
-
1469
-	/**
1470
-	 * @return \OC_Defaults
1471
-	 */
1472
-	public function getThemingDefaults() {
1473
-		return $this->query('ThemingDefaults');
1474
-	}
1475
-
1476
-	/**
1477
-	 * @return \OC\IntegrityCheck\Checker
1478
-	 */
1479
-	public function getIntegrityCodeChecker() {
1480
-		return $this->query('IntegrityCodeChecker');
1481
-	}
1482
-
1483
-	/**
1484
-	 * @return \OC\Session\CryptoWrapper
1485
-	 */
1486
-	public function getSessionCryptoWrapper() {
1487
-		return $this->query('CryptoWrapper');
1488
-	}
1489
-
1490
-	/**
1491
-	 * @return CsrfTokenManager
1492
-	 */
1493
-	public function getCsrfTokenManager() {
1494
-		return $this->query('CsrfTokenManager');
1495
-	}
1496
-
1497
-	/**
1498
-	 * @return Throttler
1499
-	 */
1500
-	public function getBruteForceThrottler() {
1501
-		return $this->query('Throttler');
1502
-	}
1503
-
1504
-	/**
1505
-	 * @return IContentSecurityPolicyManager
1506
-	 */
1507
-	public function getContentSecurityPolicyManager() {
1508
-		return $this->query('ContentSecurityPolicyManager');
1509
-	}
1510
-
1511
-	/**
1512
-	 * @return ContentSecurityPolicyNonceManager
1513
-	 */
1514
-	public function getContentSecurityPolicyNonceManager() {
1515
-		return $this->query('ContentSecurityPolicyNonceManager');
1516
-	}
1517
-
1518
-	/**
1519
-	 * Not a public API as of 8.2, wait for 9.0
1520
-	 *
1521
-	 * @return \OCA\Files_External\Service\BackendService
1522
-	 */
1523
-	public function getStoragesBackendService() {
1524
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1525
-	}
1526
-
1527
-	/**
1528
-	 * Not a public API as of 8.2, wait for 9.0
1529
-	 *
1530
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1531
-	 */
1532
-	public function getGlobalStoragesService() {
1533
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1534
-	}
1535
-
1536
-	/**
1537
-	 * Not a public API as of 8.2, wait for 9.0
1538
-	 *
1539
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1540
-	 */
1541
-	public function getUserGlobalStoragesService() {
1542
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1543
-	}
1544
-
1545
-	/**
1546
-	 * Not a public API as of 8.2, wait for 9.0
1547
-	 *
1548
-	 * @return \OCA\Files_External\Service\UserStoragesService
1549
-	 */
1550
-	public function getUserStoragesService() {
1551
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1552
-	}
1553
-
1554
-	/**
1555
-	 * @return \OCP\Share\IManager
1556
-	 */
1557
-	public function getShareManager() {
1558
-		return $this->query('ShareManager');
1559
-	}
1560
-
1561
-	/**
1562
-	 * Returns the LDAP Provider
1563
-	 *
1564
-	 * @return \OCP\LDAP\ILDAPProvider
1565
-	 */
1566
-	public function getLDAPProvider() {
1567
-		return $this->query('LDAPProvider');
1568
-	}
1569
-
1570
-	/**
1571
-	 * @return \OCP\Settings\IManager
1572
-	 */
1573
-	public function getSettingsManager() {
1574
-		return $this->query('SettingsManager');
1575
-	}
1576
-
1577
-	/**
1578
-	 * @return \OCP\Files\IAppData
1579
-	 */
1580
-	public function getAppDataDir($app) {
1581
-		/** @var \OC\Files\AppData\Factory $factory */
1582
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1583
-		return $factory->get($app);
1584
-	}
1585
-
1586
-	/**
1587
-	 * @return \OCP\Lockdown\ILockdownManager
1588
-	 */
1589
-	public function getLockdownManager() {
1590
-		return $this->query('LockdownManager');
1591
-	}
1592
-
1593
-	/**
1594
-	 * @return \OCP\Federation\ICloudIdManager
1595
-	 */
1596
-	public function getCloudIdManager() {
1597
-		return $this->query(ICloudIdManager::class);
1598
-	}
721
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
722
+            if (isset($prefixes['OCA\\Theming\\'])) {
723
+                $classExists = true;
724
+            } else {
725
+                $classExists = false;
726
+            }
727
+
728
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
729
+                return new ThemingDefaults(
730
+                    $c->getConfig(),
731
+                    $c->getL10N('theming'),
732
+                    $c->getURLGenerator(),
733
+                    new \OC_Defaults(),
734
+                    $c->getLazyRootFolder(),
735
+                    $c->getMemCacheFactory()
736
+                );
737
+            }
738
+            return new \OC_Defaults();
739
+        });
740
+        $this->registerService('EventDispatcher', function () {
741
+            return new EventDispatcher();
742
+        });
743
+        $this->registerService('CryptoWrapper', function (Server $c) {
744
+            // FIXME: Instantiiated here due to cyclic dependency
745
+            $request = new Request(
746
+                [
747
+                    'get' => $_GET,
748
+                    'post' => $_POST,
749
+                    'files' => $_FILES,
750
+                    'server' => $_SERVER,
751
+                    'env' => $_ENV,
752
+                    'cookies' => $_COOKIE,
753
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
754
+                        ? $_SERVER['REQUEST_METHOD']
755
+                        : null,
756
+                ],
757
+                $c->getSecureRandom(),
758
+                $c->getConfig()
759
+            );
760
+
761
+            return new CryptoWrapper(
762
+                $c->getConfig(),
763
+                $c->getCrypto(),
764
+                $c->getSecureRandom(),
765
+                $request
766
+            );
767
+        });
768
+        $this->registerService('CsrfTokenManager', function (Server $c) {
769
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
770
+
771
+            return new CsrfTokenManager(
772
+                $tokenGenerator,
773
+                $c->query(SessionStorage::class)
774
+            );
775
+        });
776
+        $this->registerService(SessionStorage::class, function (Server $c) {
777
+            return new SessionStorage($c->getSession());
778
+        });
779
+        $this->registerService('ContentSecurityPolicyManager', function (Server $c) {
780
+            return new ContentSecurityPolicyManager();
781
+        });
782
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
783
+            return new ContentSecurityPolicyNonceManager(
784
+                $c->getCsrfTokenManager(),
785
+                $c->getRequest()
786
+            );
787
+        });
788
+        $this->registerService('ShareManager', function(Server $c) {
789
+            $config = $c->getConfig();
790
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
791
+            /** @var \OCP\Share\IProviderFactory $factory */
792
+            $factory = new $factoryClass($this);
793
+
794
+            $manager = new \OC\Share20\Manager(
795
+                $c->getLogger(),
796
+                $c->getConfig(),
797
+                $c->getSecureRandom(),
798
+                $c->getHasher(),
799
+                $c->getMountManager(),
800
+                $c->getGroupManager(),
801
+                $c->getL10N('core'),
802
+                $factory,
803
+                $c->getUserManager(),
804
+                $c->getLazyRootFolder(),
805
+                $c->getEventDispatcher()
806
+            );
807
+
808
+            return $manager;
809
+        });
810
+        $this->registerService('SettingsManager', function(Server $c) {
811
+            $manager = new \OC\Settings\Manager(
812
+                $c->getLogger(),
813
+                $c->getDatabaseConnection(),
814
+                $c->getL10N('lib'),
815
+                $c->getConfig(),
816
+                $c->getEncryptionManager(),
817
+                $c->getUserManager(),
818
+                $c->getLockingProvider(),
819
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
820
+                $c->getURLGenerator()
821
+            );
822
+            return $manager;
823
+        });
824
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
825
+            return new \OC\Files\AppData\Factory(
826
+                $c->getRootFolder(),
827
+                $c->getSystemConfig()
828
+            );
829
+        });
830
+
831
+        $this->registerService('LockdownManager', function (Server $c) {
832
+            return new LockdownManager();
833
+        });
834
+
835
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
836
+            return new CloudIdManager();
837
+        });
838
+
839
+        /* To trick DI since we don't extend the DIContainer here */
840
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
841
+            return new CleanPreviewsBackgroundJob(
842
+                $c->getRootFolder(),
843
+                $c->getLogger(),
844
+                $c->getJobList(),
845
+                new TimeFactory()
846
+            );
847
+        });
848
+    }
849
+
850
+    /**
851
+     * @return \OCP\Contacts\IManager
852
+     */
853
+    public function getContactsManager() {
854
+        return $this->query('ContactsManager');
855
+    }
856
+
857
+    /**
858
+     * @return \OC\Encryption\Manager
859
+     */
860
+    public function getEncryptionManager() {
861
+        return $this->query('EncryptionManager');
862
+    }
863
+
864
+    /**
865
+     * @return \OC\Encryption\File
866
+     */
867
+    public function getEncryptionFilesHelper() {
868
+        return $this->query('EncryptionFileHelper');
869
+    }
870
+
871
+    /**
872
+     * @return \OCP\Encryption\Keys\IStorage
873
+     */
874
+    public function getEncryptionKeyStorage() {
875
+        return $this->query('EncryptionKeyStorage');
876
+    }
877
+
878
+    /**
879
+     * @return \OC\OCS\DiscoveryService
880
+     */
881
+    public function getOCSDiscoveryService() {
882
+        return $this->query('OCSDiscoveryService');
883
+    }
884
+
885
+
886
+    /**
887
+     * The current request object holding all information about the request
888
+     * currently being processed is returned from this method.
889
+     * In case the current execution was not initiated by a web request null is returned
890
+     *
891
+     * @return \OCP\IRequest
892
+     */
893
+    public function getRequest() {
894
+        return $this->query('Request');
895
+    }
896
+
897
+    /**
898
+     * Returns the preview manager which can create preview images for a given file
899
+     *
900
+     * @return \OCP\IPreview
901
+     */
902
+    public function getPreviewManager() {
903
+        return $this->query('PreviewManager');
904
+    }
905
+
906
+    /**
907
+     * Returns the tag manager which can get and set tags for different object types
908
+     *
909
+     * @see \OCP\ITagManager::load()
910
+     * @return \OCP\ITagManager
911
+     */
912
+    public function getTagManager() {
913
+        return $this->query('TagManager');
914
+    }
915
+
916
+    /**
917
+     * Returns the system-tag manager
918
+     *
919
+     * @return \OCP\SystemTag\ISystemTagManager
920
+     *
921
+     * @since 9.0.0
922
+     */
923
+    public function getSystemTagManager() {
924
+        return $this->query('SystemTagManager');
925
+    }
926
+
927
+    /**
928
+     * Returns the system-tag object mapper
929
+     *
930
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
931
+     *
932
+     * @since 9.0.0
933
+     */
934
+    public function getSystemTagObjectMapper() {
935
+        return $this->query('SystemTagObjectMapper');
936
+    }
937
+
938
+    /**
939
+     * Returns the avatar manager, used for avatar functionality
940
+     *
941
+     * @return \OCP\IAvatarManager
942
+     */
943
+    public function getAvatarManager() {
944
+        return $this->query('AvatarManager');
945
+    }
946
+
947
+    /**
948
+     * Returns the root folder of ownCloud's data directory
949
+     *
950
+     * @return \OCP\Files\IRootFolder
951
+     */
952
+    public function getRootFolder() {
953
+        return $this->query('LazyRootFolder');
954
+    }
955
+
956
+    /**
957
+     * Returns the root folder of ownCloud's data directory
958
+     * This is the lazy variant so this gets only initialized once it
959
+     * is actually used.
960
+     *
961
+     * @return \OCP\Files\IRootFolder
962
+     */
963
+    public function getLazyRootFolder() {
964
+        return $this->query('LazyRootFolder');
965
+    }
966
+
967
+    /**
968
+     * Returns a view to ownCloud's files folder
969
+     *
970
+     * @param string $userId user ID
971
+     * @return \OCP\Files\Folder|null
972
+     */
973
+    public function getUserFolder($userId = null) {
974
+        if ($userId === null) {
975
+            $user = $this->getUserSession()->getUser();
976
+            if (!$user) {
977
+                return null;
978
+            }
979
+            $userId = $user->getUID();
980
+        }
981
+        $root = $this->getRootFolder();
982
+        return $root->getUserFolder($userId);
983
+    }
984
+
985
+    /**
986
+     * Returns an app-specific view in ownClouds data directory
987
+     *
988
+     * @return \OCP\Files\Folder
989
+     * @deprecated since 9.2.0 use IAppData
990
+     */
991
+    public function getAppFolder() {
992
+        $dir = '/' . \OC_App::getCurrentApp();
993
+        $root = $this->getRootFolder();
994
+        if (!$root->nodeExists($dir)) {
995
+            $folder = $root->newFolder($dir);
996
+        } else {
997
+            $folder = $root->get($dir);
998
+        }
999
+        return $folder;
1000
+    }
1001
+
1002
+    /**
1003
+     * @return \OC\User\Manager
1004
+     */
1005
+    public function getUserManager() {
1006
+        return $this->query('UserManager');
1007
+    }
1008
+
1009
+    /**
1010
+     * @return \OC\Group\Manager
1011
+     */
1012
+    public function getGroupManager() {
1013
+        return $this->query('GroupManager');
1014
+    }
1015
+
1016
+    /**
1017
+     * @return \OC\User\Session
1018
+     */
1019
+    public function getUserSession() {
1020
+        return $this->query('UserSession');
1021
+    }
1022
+
1023
+    /**
1024
+     * @return \OCP\ISession
1025
+     */
1026
+    public function getSession() {
1027
+        return $this->query('UserSession')->getSession();
1028
+    }
1029
+
1030
+    /**
1031
+     * @param \OCP\ISession $session
1032
+     */
1033
+    public function setSession(\OCP\ISession $session) {
1034
+        $this->query(SessionStorage::class)->setSession($session);
1035
+        $this->query('UserSession')->setSession($session);
1036
+        $this->query(Store::class)->setSession($session);
1037
+    }
1038
+
1039
+    /**
1040
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1041
+     */
1042
+    public function getTwoFactorAuthManager() {
1043
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1044
+    }
1045
+
1046
+    /**
1047
+     * @return \OC\NavigationManager
1048
+     */
1049
+    public function getNavigationManager() {
1050
+        return $this->query('NavigationManager');
1051
+    }
1052
+
1053
+    /**
1054
+     * @return \OCP\IConfig
1055
+     */
1056
+    public function getConfig() {
1057
+        return $this->query('AllConfig');
1058
+    }
1059
+
1060
+    /**
1061
+     * @internal For internal use only
1062
+     * @return \OC\SystemConfig
1063
+     */
1064
+    public function getSystemConfig() {
1065
+        return $this->query('SystemConfig');
1066
+    }
1067
+
1068
+    /**
1069
+     * Returns the app config manager
1070
+     *
1071
+     * @return \OCP\IAppConfig
1072
+     */
1073
+    public function getAppConfig() {
1074
+        return $this->query('AppConfig');
1075
+    }
1076
+
1077
+    /**
1078
+     * @return \OCP\L10N\IFactory
1079
+     */
1080
+    public function getL10NFactory() {
1081
+        return $this->query('L10NFactory');
1082
+    }
1083
+
1084
+    /**
1085
+     * get an L10N instance
1086
+     *
1087
+     * @param string $app appid
1088
+     * @param string $lang
1089
+     * @return IL10N
1090
+     */
1091
+    public function getL10N($app, $lang = null) {
1092
+        return $this->getL10NFactory()->get($app, $lang);
1093
+    }
1094
+
1095
+    /**
1096
+     * @return \OCP\IURLGenerator
1097
+     */
1098
+    public function getURLGenerator() {
1099
+        return $this->query('URLGenerator');
1100
+    }
1101
+
1102
+    /**
1103
+     * @return \OCP\IHelper
1104
+     */
1105
+    public function getHelper() {
1106
+        return $this->query('AppHelper');
1107
+    }
1108
+
1109
+    /**
1110
+     * @return AppFetcher
1111
+     */
1112
+    public function getAppFetcher() {
1113
+        return $this->query('AppFetcher');
1114
+    }
1115
+
1116
+    /**
1117
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1118
+     * getMemCacheFactory() instead.
1119
+     *
1120
+     * @return \OCP\ICache
1121
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1122
+     */
1123
+    public function getCache() {
1124
+        return $this->query('UserCache');
1125
+    }
1126
+
1127
+    /**
1128
+     * Returns an \OCP\CacheFactory instance
1129
+     *
1130
+     * @return \OCP\ICacheFactory
1131
+     */
1132
+    public function getMemCacheFactory() {
1133
+        return $this->query('MemCacheFactory');
1134
+    }
1135
+
1136
+    /**
1137
+     * Returns an \OC\RedisFactory instance
1138
+     *
1139
+     * @return \OC\RedisFactory
1140
+     */
1141
+    public function getGetRedisFactory() {
1142
+        return $this->query('RedisFactory');
1143
+    }
1144
+
1145
+
1146
+    /**
1147
+     * Returns the current session
1148
+     *
1149
+     * @return \OCP\IDBConnection
1150
+     */
1151
+    public function getDatabaseConnection() {
1152
+        return $this->query('DatabaseConnection');
1153
+    }
1154
+
1155
+    /**
1156
+     * Returns the activity manager
1157
+     *
1158
+     * @return \OCP\Activity\IManager
1159
+     */
1160
+    public function getActivityManager() {
1161
+        return $this->query('ActivityManager');
1162
+    }
1163
+
1164
+    /**
1165
+     * Returns an job list for controlling background jobs
1166
+     *
1167
+     * @return \OCP\BackgroundJob\IJobList
1168
+     */
1169
+    public function getJobList() {
1170
+        return $this->query('JobList');
1171
+    }
1172
+
1173
+    /**
1174
+     * Returns a logger instance
1175
+     *
1176
+     * @return \OCP\ILogger
1177
+     */
1178
+    public function getLogger() {
1179
+        return $this->query('Logger');
1180
+    }
1181
+
1182
+    /**
1183
+     * Returns a router for generating and matching urls
1184
+     *
1185
+     * @return \OCP\Route\IRouter
1186
+     */
1187
+    public function getRouter() {
1188
+        return $this->query('Router');
1189
+    }
1190
+
1191
+    /**
1192
+     * Returns a search instance
1193
+     *
1194
+     * @return \OCP\ISearch
1195
+     */
1196
+    public function getSearch() {
1197
+        return $this->query('Search');
1198
+    }
1199
+
1200
+    /**
1201
+     * Returns a SecureRandom instance
1202
+     *
1203
+     * @return \OCP\Security\ISecureRandom
1204
+     */
1205
+    public function getSecureRandom() {
1206
+        return $this->query('SecureRandom');
1207
+    }
1208
+
1209
+    /**
1210
+     * Returns a Crypto instance
1211
+     *
1212
+     * @return \OCP\Security\ICrypto
1213
+     */
1214
+    public function getCrypto() {
1215
+        return $this->query('Crypto');
1216
+    }
1217
+
1218
+    /**
1219
+     * Returns a Hasher instance
1220
+     *
1221
+     * @return \OCP\Security\IHasher
1222
+     */
1223
+    public function getHasher() {
1224
+        return $this->query('Hasher');
1225
+    }
1226
+
1227
+    /**
1228
+     * Returns a CredentialsManager instance
1229
+     *
1230
+     * @return \OCP\Security\ICredentialsManager
1231
+     */
1232
+    public function getCredentialsManager() {
1233
+        return $this->query('CredentialsManager');
1234
+    }
1235
+
1236
+    /**
1237
+     * Returns an instance of the HTTP helper class
1238
+     *
1239
+     * @deprecated Use getHTTPClientService()
1240
+     * @return \OC\HTTPHelper
1241
+     */
1242
+    public function getHTTPHelper() {
1243
+        return $this->query('HTTPHelper');
1244
+    }
1245
+
1246
+    /**
1247
+     * Get the certificate manager for the user
1248
+     *
1249
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1250
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1251
+     */
1252
+    public function getCertificateManager($userId = '') {
1253
+        if ($userId === '') {
1254
+            $userSession = $this->getUserSession();
1255
+            $user = $userSession->getUser();
1256
+            if (is_null($user)) {
1257
+                return null;
1258
+            }
1259
+            $userId = $user->getUID();
1260
+        }
1261
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1262
+    }
1263
+
1264
+    /**
1265
+     * Returns an instance of the HTTP client service
1266
+     *
1267
+     * @return \OCP\Http\Client\IClientService
1268
+     */
1269
+    public function getHTTPClientService() {
1270
+        return $this->query('HttpClientService');
1271
+    }
1272
+
1273
+    /**
1274
+     * Create a new event source
1275
+     *
1276
+     * @return \OCP\IEventSource
1277
+     */
1278
+    public function createEventSource() {
1279
+        return new \OC_EventSource();
1280
+    }
1281
+
1282
+    /**
1283
+     * Get the active event logger
1284
+     *
1285
+     * The returned logger only logs data when debug mode is enabled
1286
+     *
1287
+     * @return \OCP\Diagnostics\IEventLogger
1288
+     */
1289
+    public function getEventLogger() {
1290
+        return $this->query('EventLogger');
1291
+    }
1292
+
1293
+    /**
1294
+     * Get the active query logger
1295
+     *
1296
+     * The returned logger only logs data when debug mode is enabled
1297
+     *
1298
+     * @return \OCP\Diagnostics\IQueryLogger
1299
+     */
1300
+    public function getQueryLogger() {
1301
+        return $this->query('QueryLogger');
1302
+    }
1303
+
1304
+    /**
1305
+     * Get the manager for temporary files and folders
1306
+     *
1307
+     * @return \OCP\ITempManager
1308
+     */
1309
+    public function getTempManager() {
1310
+        return $this->query('TempManager');
1311
+    }
1312
+
1313
+    /**
1314
+     * Get the app manager
1315
+     *
1316
+     * @return \OCP\App\IAppManager
1317
+     */
1318
+    public function getAppManager() {
1319
+        return $this->query('AppManager');
1320
+    }
1321
+
1322
+    /**
1323
+     * Creates a new mailer
1324
+     *
1325
+     * @return \OCP\Mail\IMailer
1326
+     */
1327
+    public function getMailer() {
1328
+        return $this->query('Mailer');
1329
+    }
1330
+
1331
+    /**
1332
+     * Get the webroot
1333
+     *
1334
+     * @return string
1335
+     */
1336
+    public function getWebRoot() {
1337
+        return $this->webRoot;
1338
+    }
1339
+
1340
+    /**
1341
+     * @return \OC\OCSClient
1342
+     */
1343
+    public function getOcsClient() {
1344
+        return $this->query('OcsClient');
1345
+    }
1346
+
1347
+    /**
1348
+     * @return \OCP\IDateTimeZone
1349
+     */
1350
+    public function getDateTimeZone() {
1351
+        return $this->query('DateTimeZone');
1352
+    }
1353
+
1354
+    /**
1355
+     * @return \OCP\IDateTimeFormatter
1356
+     */
1357
+    public function getDateTimeFormatter() {
1358
+        return $this->query('DateTimeFormatter');
1359
+    }
1360
+
1361
+    /**
1362
+     * @return \OCP\Files\Config\IMountProviderCollection
1363
+     */
1364
+    public function getMountProviderCollection() {
1365
+        return $this->query('MountConfigManager');
1366
+    }
1367
+
1368
+    /**
1369
+     * Get the IniWrapper
1370
+     *
1371
+     * @return IniGetWrapper
1372
+     */
1373
+    public function getIniWrapper() {
1374
+        return $this->query('IniWrapper');
1375
+    }
1376
+
1377
+    /**
1378
+     * @return \OCP\Command\IBus
1379
+     */
1380
+    public function getCommandBus() {
1381
+        return $this->query('AsyncCommandBus');
1382
+    }
1383
+
1384
+    /**
1385
+     * Get the trusted domain helper
1386
+     *
1387
+     * @return TrustedDomainHelper
1388
+     */
1389
+    public function getTrustedDomainHelper() {
1390
+        return $this->query('TrustedDomainHelper');
1391
+    }
1392
+
1393
+    /**
1394
+     * Get the locking provider
1395
+     *
1396
+     * @return \OCP\Lock\ILockingProvider
1397
+     * @since 8.1.0
1398
+     */
1399
+    public function getLockingProvider() {
1400
+        return $this->query('LockingProvider');
1401
+    }
1402
+
1403
+    /**
1404
+     * @return \OCP\Files\Mount\IMountManager
1405
+     **/
1406
+    function getMountManager() {
1407
+        return $this->query('MountManager');
1408
+    }
1409
+
1410
+    /** @return \OCP\Files\Config\IUserMountCache */
1411
+    function getUserMountCache() {
1412
+        return $this->query('UserMountCache');
1413
+    }
1414
+
1415
+    /**
1416
+     * Get the MimeTypeDetector
1417
+     *
1418
+     * @return \OCP\Files\IMimeTypeDetector
1419
+     */
1420
+    public function getMimeTypeDetector() {
1421
+        return $this->query('MimeTypeDetector');
1422
+    }
1423
+
1424
+    /**
1425
+     * Get the MimeTypeLoader
1426
+     *
1427
+     * @return \OCP\Files\IMimeTypeLoader
1428
+     */
1429
+    public function getMimeTypeLoader() {
1430
+        return $this->query('MimeTypeLoader');
1431
+    }
1432
+
1433
+    /**
1434
+     * Get the manager of all the capabilities
1435
+     *
1436
+     * @return \OC\CapabilitiesManager
1437
+     */
1438
+    public function getCapabilitiesManager() {
1439
+        return $this->query('CapabilitiesManager');
1440
+    }
1441
+
1442
+    /**
1443
+     * Get the EventDispatcher
1444
+     *
1445
+     * @return EventDispatcherInterface
1446
+     * @since 8.2.0
1447
+     */
1448
+    public function getEventDispatcher() {
1449
+        return $this->query('EventDispatcher');
1450
+    }
1451
+
1452
+    /**
1453
+     * Get the Notification Manager
1454
+     *
1455
+     * @return \OCP\Notification\IManager
1456
+     * @since 8.2.0
1457
+     */
1458
+    public function getNotificationManager() {
1459
+        return $this->query('NotificationManager');
1460
+    }
1461
+
1462
+    /**
1463
+     * @return \OCP\Comments\ICommentsManager
1464
+     */
1465
+    public function getCommentsManager() {
1466
+        return $this->query('CommentsManager');
1467
+    }
1468
+
1469
+    /**
1470
+     * @return \OC_Defaults
1471
+     */
1472
+    public function getThemingDefaults() {
1473
+        return $this->query('ThemingDefaults');
1474
+    }
1475
+
1476
+    /**
1477
+     * @return \OC\IntegrityCheck\Checker
1478
+     */
1479
+    public function getIntegrityCodeChecker() {
1480
+        return $this->query('IntegrityCodeChecker');
1481
+    }
1482
+
1483
+    /**
1484
+     * @return \OC\Session\CryptoWrapper
1485
+     */
1486
+    public function getSessionCryptoWrapper() {
1487
+        return $this->query('CryptoWrapper');
1488
+    }
1489
+
1490
+    /**
1491
+     * @return CsrfTokenManager
1492
+     */
1493
+    public function getCsrfTokenManager() {
1494
+        return $this->query('CsrfTokenManager');
1495
+    }
1496
+
1497
+    /**
1498
+     * @return Throttler
1499
+     */
1500
+    public function getBruteForceThrottler() {
1501
+        return $this->query('Throttler');
1502
+    }
1503
+
1504
+    /**
1505
+     * @return IContentSecurityPolicyManager
1506
+     */
1507
+    public function getContentSecurityPolicyManager() {
1508
+        return $this->query('ContentSecurityPolicyManager');
1509
+    }
1510
+
1511
+    /**
1512
+     * @return ContentSecurityPolicyNonceManager
1513
+     */
1514
+    public function getContentSecurityPolicyNonceManager() {
1515
+        return $this->query('ContentSecurityPolicyNonceManager');
1516
+    }
1517
+
1518
+    /**
1519
+     * Not a public API as of 8.2, wait for 9.0
1520
+     *
1521
+     * @return \OCA\Files_External\Service\BackendService
1522
+     */
1523
+    public function getStoragesBackendService() {
1524
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1525
+    }
1526
+
1527
+    /**
1528
+     * Not a public API as of 8.2, wait for 9.0
1529
+     *
1530
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1531
+     */
1532
+    public function getGlobalStoragesService() {
1533
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1534
+    }
1535
+
1536
+    /**
1537
+     * Not a public API as of 8.2, wait for 9.0
1538
+     *
1539
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1540
+     */
1541
+    public function getUserGlobalStoragesService() {
1542
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1543
+    }
1544
+
1545
+    /**
1546
+     * Not a public API as of 8.2, wait for 9.0
1547
+     *
1548
+     * @return \OCA\Files_External\Service\UserStoragesService
1549
+     */
1550
+    public function getUserStoragesService() {
1551
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1552
+    }
1553
+
1554
+    /**
1555
+     * @return \OCP\Share\IManager
1556
+     */
1557
+    public function getShareManager() {
1558
+        return $this->query('ShareManager');
1559
+    }
1560
+
1561
+    /**
1562
+     * Returns the LDAP Provider
1563
+     *
1564
+     * @return \OCP\LDAP\ILDAPProvider
1565
+     */
1566
+    public function getLDAPProvider() {
1567
+        return $this->query('LDAPProvider');
1568
+    }
1569
+
1570
+    /**
1571
+     * @return \OCP\Settings\IManager
1572
+     */
1573
+    public function getSettingsManager() {
1574
+        return $this->query('SettingsManager');
1575
+    }
1576
+
1577
+    /**
1578
+     * @return \OCP\Files\IAppData
1579
+     */
1580
+    public function getAppDataDir($app) {
1581
+        /** @var \OC\Files\AppData\Factory $factory */
1582
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1583
+        return $factory->get($app);
1584
+    }
1585
+
1586
+    /**
1587
+     * @return \OCP\Lockdown\ILockdownManager
1588
+     */
1589
+    public function getLockdownManager() {
1590
+        return $this->query('LockdownManager');
1591
+    }
1592
+
1593
+    /**
1594
+     * @return \OCP\Federation\ICloudIdManager
1595
+     */
1596
+    public function getCloudIdManager() {
1597
+        return $this->query(ICloudIdManager::class);
1598
+    }
1599 1599
 }
Please login to merge, or discard this patch.
Spacing   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -120,11 +120,11 @@  discard block
 block discarded – undo
120 120
 		parent::__construct();
121 121
 		$this->webRoot = $webRoot;
122 122
 
123
-		$this->registerService('ContactsManager', function ($c) {
123
+		$this->registerService('ContactsManager', function($c) {
124 124
 			return new ContactsManager();
125 125
 		});
126 126
 
127
-		$this->registerService('PreviewManager', function (Server $c) {
127
+		$this->registerService('PreviewManager', function(Server $c) {
128 128
 			return new PreviewManager(
129 129
 				$c->getConfig(),
130 130
 				$c->getRootFolder(),
@@ -134,17 +134,17 @@  discard block
 block discarded – undo
134 134
 			);
135 135
 		});
136 136
 
137
-		$this->registerService('OCSDiscoveryService', function (Server $c) {
137
+		$this->registerService('OCSDiscoveryService', function(Server $c) {
138 138
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
139 139
 ;		});
140 140
 
141
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
141
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
142 142
 			return new \OC\Preview\Watcher(
143 143
 				$c->getAppDataDir('preview')
144 144
 			);
145 145
 		});
146 146
 
147
-		$this->registerService('EncryptionManager', function (Server $c) {
147
+		$this->registerService('EncryptionManager', function(Server $c) {
148 148
 			$view = new View();
149 149
 			$util = new Encryption\Util(
150 150
 				$view,
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 			);
163 163
 		});
164 164
 
165
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
165
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
166 166
 			$util = new Encryption\Util(
167 167
 				new View(),
168 168
 				$c->getUserManager(),
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 			return new Encryption\File($util);
173 173
 		});
174 174
 
175
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
175
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
176 176
 			$view = new View();
177 177
 			$util = new Encryption\Util(
178 178
 				$view,
@@ -183,27 +183,27 @@  discard block
 block discarded – undo
183 183
 
184 184
 			return new Encryption\Keys\Storage($view, $util);
185 185
 		});
186
-		$this->registerService('TagMapper', function (Server $c) {
186
+		$this->registerService('TagMapper', function(Server $c) {
187 187
 			return new TagMapper($c->getDatabaseConnection());
188 188
 		});
189
-		$this->registerService('TagManager', function (Server $c) {
189
+		$this->registerService('TagManager', function(Server $c) {
190 190
 			$tagMapper = $c->query('TagMapper');
191 191
 			return new TagManager($tagMapper, $c->getUserSession());
192 192
 		});
193
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
193
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
194 194
 			$config = $c->getConfig();
195 195
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
196 196
 			/** @var \OC\SystemTag\ManagerFactory $factory */
197 197
 			$factory = new $factoryClass($this);
198 198
 			return $factory;
199 199
 		});
200
-		$this->registerService('SystemTagManager', function (Server $c) {
200
+		$this->registerService('SystemTagManager', function(Server $c) {
201 201
 			return $c->query('SystemTagManagerFactory')->getManager();
202 202
 		});
203
-		$this->registerService('SystemTagObjectMapper', function (Server $c) {
203
+		$this->registerService('SystemTagObjectMapper', function(Server $c) {
204 204
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
205 205
 		});
206
-		$this->registerService('RootFolder', function (Server $c) {
206
+		$this->registerService('RootFolder', function(Server $c) {
207 207
 			$manager = \OC\Files\Filesystem::getMountManager(null);
208 208
 			$view = new View();
209 209
 			$root = new Root(
@@ -227,28 +227,28 @@  discard block
 block discarded – undo
227 227
 				return $c->query('RootFolder');
228 228
 			});
229 229
 		});
230
-		$this->registerService('UserManager', function (Server $c) {
230
+		$this->registerService('UserManager', function(Server $c) {
231 231
 			$config = $c->getConfig();
232 232
 			return new \OC\User\Manager($config);
233 233
 		});
234
-		$this->registerService('GroupManager', function (Server $c) {
234
+		$this->registerService('GroupManager', function(Server $c) {
235 235
 			$groupManager = new \OC\Group\Manager($this->getUserManager());
236
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
236
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
237 237
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
238 238
 			});
239
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
239
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
240 240
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
241 241
 			});
242
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
242
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
243 243
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
244 244
 			});
245
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
245
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
246 246
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
247 247
 			});
248
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
248
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
249 249
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
250 250
 			});
251
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
251
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
252 252
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
253 253
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
254 254
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -266,11 +266,11 @@  discard block
 block discarded – undo
266 266
 			return new Store($session, $logger, $tokenProvider);
267 267
 		});
268 268
 		$this->registerAlias(IStore::class, Store::class);
269
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
269
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
270 270
 			$dbConnection = $c->getDatabaseConnection();
271 271
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
272 272
 		});
273
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
273
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
274 274
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
275 275
 			$crypto = $c->getCrypto();
276 276
 			$config = $c->getConfig();
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
280 280
 		});
281 281
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
282
-		$this->registerService('UserSession', function (Server $c) {
282
+		$this->registerService('UserSession', function(Server $c) {
283 283
 			$manager = $c->getUserManager();
284 284
 			$session = new \OC\Session\Memory('');
285 285
 			$timeFactory = new TimeFactory();
@@ -292,69 +292,69 @@  discard block
 block discarded – undo
292 292
 			}
293 293
 
294 294
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
295
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
295
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
296 296
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
297 297
 			});
298
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
298
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
299 299
 				/** @var $user \OC\User\User */
300 300
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
301 301
 			});
302
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
302
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
303 303
 				/** @var $user \OC\User\User */
304 304
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
305 305
 			});
306
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
306
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
307 307
 				/** @var $user \OC\User\User */
308 308
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
309 309
 			});
310
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
310
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
311 311
 				/** @var $user \OC\User\User */
312 312
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
313 313
 			});
314
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
314
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
315 315
 				/** @var $user \OC\User\User */
316 316
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
317 317
 			});
318
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
318
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
319 319
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
320 320
 			});
321
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
321
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
322 322
 				/** @var $user \OC\User\User */
323 323
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
324 324
 			});
325
-			$userSession->listen('\OC\User', 'logout', function () {
325
+			$userSession->listen('\OC\User', 'logout', function() {
326 326
 				\OC_Hook::emit('OC_User', 'logout', array());
327 327
 			});
328
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
328
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value) {
329 329
 				/** @var $user \OC\User\User */
330 330
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
331 331
 			});
332 332
 			return $userSession;
333 333
 		});
334 334
 
335
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
335
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
336 336
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
337 337
 		});
338 338
 
339
-		$this->registerService('NavigationManager', function (Server $c) {
339
+		$this->registerService('NavigationManager', function(Server $c) {
340 340
 			return new \OC\NavigationManager($c->getAppManager(),
341 341
 				$c->getURLGenerator(),
342 342
 				$c->getL10NFactory(),
343 343
 				$c->getUserSession(),
344 344
 				$c->getGroupManager());
345 345
 		});
346
-		$this->registerService('AllConfig', function (Server $c) {
346
+		$this->registerService('AllConfig', function(Server $c) {
347 347
 			return new \OC\AllConfig(
348 348
 				$c->getSystemConfig()
349 349
 			);
350 350
 		});
351
-		$this->registerService('SystemConfig', function ($c) use ($config) {
351
+		$this->registerService('SystemConfig', function($c) use ($config) {
352 352
 			return new \OC\SystemConfig($config);
353 353
 		});
354
-		$this->registerService('AppConfig', function (Server $c) {
354
+		$this->registerService('AppConfig', function(Server $c) {
355 355
 			return new \OC\AppConfig($c->getDatabaseConnection());
356 356
 		});
357
-		$this->registerService('L10NFactory', function (Server $c) {
357
+		$this->registerService('L10NFactory', function(Server $c) {
358 358
 			return new \OC\L10N\Factory(
359 359
 				$c->getConfig(),
360 360
 				$c->getRequest(),
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 				\OC::$SERVERROOT
363 363
 			);
364 364
 		});
365
-		$this->registerService('URLGenerator', function (Server $c) {
365
+		$this->registerService('URLGenerator', function(Server $c) {
366 366
 			$config = $c->getConfig();
367 367
 			$cacheFactory = $c->getMemCacheFactory();
368 368
 			return new \OC\URLGenerator(
@@ -370,10 +370,10 @@  discard block
 block discarded – undo
370 370
 				$cacheFactory
371 371
 			);
372 372
 		});
373
-		$this->registerService('AppHelper', function ($c) {
373
+		$this->registerService('AppHelper', function($c) {
374 374
 			return new \OC\AppHelper();
375 375
 		});
376
-		$this->registerService('AppFetcher', function ($c) {
376
+		$this->registerService('AppFetcher', function($c) {
377 377
 			return new AppFetcher(
378 378
 				$this->getAppDataDir('appstore'),
379 379
 				$this->getHTTPClientService(),
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
 				$this->getConfig()
382 382
 			);
383 383
 		});
384
-		$this->registerService('CategoryFetcher', function ($c) {
384
+		$this->registerService('CategoryFetcher', function($c) {
385 385
 			return new CategoryFetcher(
386 386
 				$this->getAppDataDir('appstore'),
387 387
 				$this->getHTTPClientService(),
@@ -389,19 +389,19 @@  discard block
 block discarded – undo
389 389
 				$this->getConfig()
390 390
 			);
391 391
 		});
392
-		$this->registerService('UserCache', function ($c) {
392
+		$this->registerService('UserCache', function($c) {
393 393
 			return new Cache\File();
394 394
 		});
395
-		$this->registerService('MemCacheFactory', function (Server $c) {
395
+		$this->registerService('MemCacheFactory', function(Server $c) {
396 396
 			$config = $c->getConfig();
397 397
 
398 398
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
399 399
 				$v = \OC_App::getAppVersions();
400
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
400
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
401 401
 				$version = implode(',', $v);
402 402
 				$instanceId = \OC_Util::getInstanceId();
403 403
 				$path = \OC::$SERVERROOT;
404
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
404
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
405 405
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
406 406
 					$config->getSystemValue('memcache.local', null),
407 407
 					$config->getSystemValue('memcache.distributed', null),
@@ -415,11 +415,11 @@  discard block
 block discarded – undo
415 415
 				'\\OC\\Memcache\\ArrayCache'
416 416
 			);
417 417
 		});
418
-		$this->registerService('RedisFactory', function (Server $c) {
418
+		$this->registerService('RedisFactory', function(Server $c) {
419 419
 			$systemConfig = $c->getSystemConfig();
420 420
 			return new RedisFactory($systemConfig);
421 421
 		});
422
-		$this->registerService('ActivityManager', function (Server $c) {
422
+		$this->registerService('ActivityManager', function(Server $c) {
423 423
 			return new \OC\Activity\Manager(
424 424
 				$c->getRequest(),
425 425
 				$c->getUserSession(),
@@ -427,13 +427,13 @@  discard block
 block discarded – undo
427 427
 				$c->query(IValidator::class)
428 428
 			);
429 429
 		});
430
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
430
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
431 431
 			return new \OC\Activity\EventMerger(
432 432
 				$c->getL10N('lib')
433 433
 			);
434 434
 		});
435 435
 		$this->registerAlias(IValidator::class, Validator::class);
436
-		$this->registerService('AvatarManager', function (Server $c) {
436
+		$this->registerService('AvatarManager', function(Server $c) {
437 437
 			return new AvatarManager(
438 438
 				$c->getUserManager(),
439 439
 				$c->getAppDataDir('avatar'),
@@ -442,14 +442,14 @@  discard block
 block discarded – undo
442 442
 				$c->getConfig()
443 443
 			);
444 444
 		});
445
-		$this->registerService('Logger', function (Server $c) {
445
+		$this->registerService('Logger', function(Server $c) {
446 446
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
447 447
 			$logger = Log::getLogClass($logType);
448 448
 			call_user_func(array($logger, 'init'));
449 449
 
450 450
 			return new Log($logger);
451 451
 		});
452
-		$this->registerService('JobList', function (Server $c) {
452
+		$this->registerService('JobList', function(Server $c) {
453 453
 			$config = $c->getConfig();
454 454
 			return new \OC\BackgroundJob\JobList(
455 455
 				$c->getDatabaseConnection(),
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
 				new TimeFactory()
458 458
 			);
459 459
 		});
460
-		$this->registerService('Router', function (Server $c) {
460
+		$this->registerService('Router', function(Server $c) {
461 461
 			$cacheFactory = $c->getMemCacheFactory();
462 462
 			$logger = $c->getLogger();
463 463
 			if ($cacheFactory->isAvailable()) {
@@ -467,22 +467,22 @@  discard block
 block discarded – undo
467 467
 			}
468 468
 			return $router;
469 469
 		});
470
-		$this->registerService('Search', function ($c) {
470
+		$this->registerService('Search', function($c) {
471 471
 			return new Search();
472 472
 		});
473
-		$this->registerService('SecureRandom', function ($c) {
473
+		$this->registerService('SecureRandom', function($c) {
474 474
 			return new SecureRandom();
475 475
 		});
476
-		$this->registerService('Crypto', function (Server $c) {
476
+		$this->registerService('Crypto', function(Server $c) {
477 477
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
478 478
 		});
479
-		$this->registerService('Hasher', function (Server $c) {
479
+		$this->registerService('Hasher', function(Server $c) {
480 480
 			return new Hasher($c->getConfig());
481 481
 		});
482
-		$this->registerService('CredentialsManager', function (Server $c) {
482
+		$this->registerService('CredentialsManager', function(Server $c) {
483 483
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
484 484
 		});
485
-		$this->registerService('DatabaseConnection', function (Server $c) {
485
+		$this->registerService('DatabaseConnection', function(Server $c) {
486 486
 			$systemConfig = $c->getSystemConfig();
487 487
 			$factory = new \OC\DB\ConnectionFactory($c->getConfig());
488 488
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -494,14 +494,14 @@  discard block
 block discarded – undo
494 494
 			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
495 495
 			return $connection;
496 496
 		});
497
-		$this->registerService('HTTPHelper', function (Server $c) {
497
+		$this->registerService('HTTPHelper', function(Server $c) {
498 498
 			$config = $c->getConfig();
499 499
 			return new HTTPHelper(
500 500
 				$config,
501 501
 				$c->getHTTPClientService()
502 502
 			);
503 503
 		});
504
-		$this->registerService('HttpClientService', function (Server $c) {
504
+		$this->registerService('HttpClientService', function(Server $c) {
505 505
 			$user = \OC_User::getUser();
506 506
 			$uid = $user ? $user : null;
507 507
 			return new ClientService(
@@ -509,27 +509,27 @@  discard block
 block discarded – undo
509 509
 				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
510 510
 			);
511 511
 		});
512
-		$this->registerService('EventLogger', function (Server $c) {
512
+		$this->registerService('EventLogger', function(Server $c) {
513 513
 			if ($c->getSystemConfig()->getValue('debug', false)) {
514 514
 				return new EventLogger();
515 515
 			} else {
516 516
 				return new NullEventLogger();
517 517
 			}
518 518
 		});
519
-		$this->registerService('QueryLogger', function (Server $c) {
519
+		$this->registerService('QueryLogger', function(Server $c) {
520 520
 			if ($c->getSystemConfig()->getValue('debug', false)) {
521 521
 				return new QueryLogger();
522 522
 			} else {
523 523
 				return new NullQueryLogger();
524 524
 			}
525 525
 		});
526
-		$this->registerService('TempManager', function (Server $c) {
526
+		$this->registerService('TempManager', function(Server $c) {
527 527
 			return new TempManager(
528 528
 				$c->getLogger(),
529 529
 				$c->getConfig()
530 530
 			);
531 531
 		});
532
-		$this->registerService('AppManager', function (Server $c) {
532
+		$this->registerService('AppManager', function(Server $c) {
533 533
 			return new \OC\App\AppManager(
534 534
 				$c->getUserSession(),
535 535
 				$c->getAppConfig(),
@@ -538,13 +538,13 @@  discard block
 block discarded – undo
538 538
 				$c->getEventDispatcher()
539 539
 			);
540 540
 		});
541
-		$this->registerService('DateTimeZone', function (Server $c) {
541
+		$this->registerService('DateTimeZone', function(Server $c) {
542 542
 			return new DateTimeZone(
543 543
 				$c->getConfig(),
544 544
 				$c->getSession()
545 545
 			);
546 546
 		});
547
-		$this->registerService('DateTimeFormatter', function (Server $c) {
547
+		$this->registerService('DateTimeFormatter', function(Server $c) {
548 548
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
549 549
 
550 550
 			return new DateTimeFormatter(
@@ -552,16 +552,16 @@  discard block
 block discarded – undo
552 552
 				$c->getL10N('lib', $language)
553 553
 			);
554 554
 		});
555
-		$this->registerService('UserMountCache', function (Server $c) {
555
+		$this->registerService('UserMountCache', function(Server $c) {
556 556
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
557 557
 			$listener = new UserMountCacheListener($mountCache);
558 558
 			$listener->listen($c->getUserManager());
559 559
 			return $mountCache;
560 560
 		});
561
-		$this->registerService('MountConfigManager', function (Server $c) {
561
+		$this->registerService('MountConfigManager', function(Server $c) {
562 562
 			$loader = \OC\Files\Filesystem::getLoader();
563 563
 			$mountCache = $c->query('UserMountCache');
564
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
564
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
565 565
 
566 566
 			// builtin providers
567 567
 
@@ -572,14 +572,14 @@  discard block
 block discarded – undo
572 572
 
573 573
 			return $manager;
574 574
 		});
575
-		$this->registerService('IniWrapper', function ($c) {
575
+		$this->registerService('IniWrapper', function($c) {
576 576
 			return new IniGetWrapper();
577 577
 		});
578
-		$this->registerService('AsyncCommandBus', function (Server $c) {
578
+		$this->registerService('AsyncCommandBus', function(Server $c) {
579 579
 			$jobList = $c->getJobList();
580 580
 			return new AsyncBus($jobList);
581 581
 		});
582
-		$this->registerService('TrustedDomainHelper', function ($c) {
582
+		$this->registerService('TrustedDomainHelper', function($c) {
583 583
 			return new TrustedDomainHelper($this->getConfig());
584 584
 		});
585 585
 		$this->registerService('Throttler', function(Server $c) {
@@ -590,10 +590,10 @@  discard block
 block discarded – undo
590 590
 				$c->getConfig()
591 591
 			);
592 592
 		});
593
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
593
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
594 594
 			// IConfig and IAppManager requires a working database. This code
595 595
 			// might however be called when ownCloud is not yet setup.
596
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
596
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
597 597
 				$config = $c->getConfig();
598 598
 				$appManager = $c->getAppManager();
599 599
 			} else {
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
 					$c->getTempManager()
612 612
 			);
613 613
 		});
614
-		$this->registerService('Request', function ($c) {
614
+		$this->registerService('Request', function($c) {
615 615
 			if (isset($this['urlParams'])) {
616 616
 				$urlParams = $this['urlParams'];
617 617
 			} else {
@@ -645,7 +645,7 @@  discard block
 block discarded – undo
645 645
 				$stream
646 646
 			);
647 647
 		});
648
-		$this->registerService('Mailer', function (Server $c) {
648
+		$this->registerService('Mailer', function(Server $c) {
649 649
 			return new Mailer(
650 650
 				$c->getConfig(),
651 651
 				$c->getLogger(),
@@ -655,14 +655,14 @@  discard block
 block discarded – undo
655 655
 		$this->registerService('LDAPProvider', function(Server $c) {
656 656
 			$config = $c->getConfig();
657 657
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
658
-			if(is_null($factoryClass)) {
658
+			if (is_null($factoryClass)) {
659 659
 				throw new \Exception('ldapProviderFactory not set');
660 660
 			}
661 661
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
662 662
 			$factory = new $factoryClass($this);
663 663
 			return $factory->getLDAPProvider();
664 664
 		});
665
-		$this->registerService('LockingProvider', function (Server $c) {
665
+		$this->registerService('LockingProvider', function(Server $c) {
666 666
 			$ini = $c->getIniWrapper();
667 667
 			$config = $c->getConfig();
668 668
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -677,29 +677,29 @@  discard block
 block discarded – undo
677 677
 			}
678 678
 			return new NoopLockingProvider();
679 679
 		});
680
-		$this->registerService('MountManager', function () {
680
+		$this->registerService('MountManager', function() {
681 681
 			return new \OC\Files\Mount\Manager();
682 682
 		});
683
-		$this->registerService('MimeTypeDetector', function (Server $c) {
683
+		$this->registerService('MimeTypeDetector', function(Server $c) {
684 684
 			return new \OC\Files\Type\Detection(
685 685
 				$c->getURLGenerator(),
686 686
 				\OC::$configDir,
687
-				\OC::$SERVERROOT . '/resources/config/'
687
+				\OC::$SERVERROOT.'/resources/config/'
688 688
 			);
689 689
 		});
690
-		$this->registerService('MimeTypeLoader', function (Server $c) {
690
+		$this->registerService('MimeTypeLoader', function(Server $c) {
691 691
 			return new \OC\Files\Type\Loader(
692 692
 				$c->getDatabaseConnection()
693 693
 			);
694 694
 		});
695
-		$this->registerService('NotificationManager', function (Server $c) {
695
+		$this->registerService('NotificationManager', function(Server $c) {
696 696
 			return new Manager(
697 697
 				$c->query(IValidator::class)
698 698
 			);
699 699
 		});
700
-		$this->registerService('CapabilitiesManager', function (Server $c) {
700
+		$this->registerService('CapabilitiesManager', function(Server $c) {
701 701
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
702
-			$manager->registerCapability(function () use ($c) {
702
+			$manager->registerCapability(function() use ($c) {
703 703
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
704 704
 			});
705 705
 			return $manager;
@@ -737,10 +737,10 @@  discard block
 block discarded – undo
737 737
 			}
738 738
 			return new \OC_Defaults();
739 739
 		});
740
-		$this->registerService('EventDispatcher', function () {
740
+		$this->registerService('EventDispatcher', function() {
741 741
 			return new EventDispatcher();
742 742
 		});
743
-		$this->registerService('CryptoWrapper', function (Server $c) {
743
+		$this->registerService('CryptoWrapper', function(Server $c) {
744 744
 			// FIXME: Instantiiated here due to cyclic dependency
745 745
 			$request = new Request(
746 746
 				[
@@ -765,7 +765,7 @@  discard block
 block discarded – undo
765 765
 				$request
766 766
 			);
767 767
 		});
768
-		$this->registerService('CsrfTokenManager', function (Server $c) {
768
+		$this->registerService('CsrfTokenManager', function(Server $c) {
769 769
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
770 770
 
771 771
 			return new CsrfTokenManager(
@@ -773,10 +773,10 @@  discard block
 block discarded – undo
773 773
 				$c->query(SessionStorage::class)
774 774
 			);
775 775
 		});
776
-		$this->registerService(SessionStorage::class, function (Server $c) {
776
+		$this->registerService(SessionStorage::class, function(Server $c) {
777 777
 			return new SessionStorage($c->getSession());
778 778
 		});
779
-		$this->registerService('ContentSecurityPolicyManager', function (Server $c) {
779
+		$this->registerService('ContentSecurityPolicyManager', function(Server $c) {
780 780
 			return new ContentSecurityPolicyManager();
781 781
 		});
782 782
 		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
@@ -821,23 +821,23 @@  discard block
 block discarded – undo
821 821
 			);
822 822
 			return $manager;
823 823
 		});
824
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
824
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
825 825
 			return new \OC\Files\AppData\Factory(
826 826
 				$c->getRootFolder(),
827 827
 				$c->getSystemConfig()
828 828
 			);
829 829
 		});
830 830
 
831
-		$this->registerService('LockdownManager', function (Server $c) {
831
+		$this->registerService('LockdownManager', function(Server $c) {
832 832
 			return new LockdownManager();
833 833
 		});
834 834
 
835
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
835
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
836 836
 			return new CloudIdManager();
837 837
 		});
838 838
 
839 839
 		/* To trick DI since we don't extend the DIContainer here */
840
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
840
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
841 841
 			return new CleanPreviewsBackgroundJob(
842 842
 				$c->getRootFolder(),
843 843
 				$c->getLogger(),
@@ -989,7 +989,7 @@  discard block
 block discarded – undo
989 989
 	 * @deprecated since 9.2.0 use IAppData
990 990
 	 */
991 991
 	public function getAppFolder() {
992
-		$dir = '/' . \OC_App::getCurrentApp();
992
+		$dir = '/'.\OC_App::getCurrentApp();
993 993
 		$root = $this->getRootFolder();
994 994
 		if (!$root->nodeExists($dir)) {
995 995
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.
apps/user_ldap/lib/Access.php 2 patches
Indentation   +1768 added lines, -1768 removed lines patch added patch discarded remove patch
@@ -52,1527 +52,1527 @@  discard block
 block discarded – undo
52 52
  * @package OCA\User_LDAP
53 53
  */
54 54
 class Access extends LDAPUtility implements IUserTools {
55
-	/**
56
-	 * @var \OCA\User_LDAP\Connection
57
-	 */
58
-	public $connection;
59
-	/** @var Manager */
60
-	public $userManager;
61
-	//never ever check this var directly, always use getPagedSearchResultState
62
-	protected $pagedSearchedSuccessful;
63
-
64
-	/**
65
-	 * @var string[] $cookies an array of returned Paged Result cookies
66
-	 */
67
-	protected $cookies = array();
68
-
69
-	/**
70
-	 * @var string $lastCookie the last cookie returned from a Paged Results
71
-	 * operation, defaults to an empty string
72
-	 */
73
-	protected $lastCookie = '';
74
-
75
-	/**
76
-	 * @var AbstractMapping $userMapper
77
-	 */
78
-	protected $userMapper;
79
-
80
-	/**
81
-	* @var AbstractMapping $userMapper
82
-	*/
83
-	protected $groupMapper;
55
+    /**
56
+     * @var \OCA\User_LDAP\Connection
57
+     */
58
+    public $connection;
59
+    /** @var Manager */
60
+    public $userManager;
61
+    //never ever check this var directly, always use getPagedSearchResultState
62
+    protected $pagedSearchedSuccessful;
63
+
64
+    /**
65
+     * @var string[] $cookies an array of returned Paged Result cookies
66
+     */
67
+    protected $cookies = array();
68
+
69
+    /**
70
+     * @var string $lastCookie the last cookie returned from a Paged Results
71
+     * operation, defaults to an empty string
72
+     */
73
+    protected $lastCookie = '';
74
+
75
+    /**
76
+     * @var AbstractMapping $userMapper
77
+     */
78
+    protected $userMapper;
79
+
80
+    /**
81
+     * @var AbstractMapping $userMapper
82
+     */
83
+    protected $groupMapper;
84 84
 	
85
-	/**
86
-	 * @var \OCA\User_LDAP\Helper
87
-	 */
88
-	private $helper;
89
-
90
-	public function __construct(Connection $connection, ILDAPWrapper $ldap,
91
-		Manager $userManager, Helper $helper) {
92
-		parent::__construct($ldap);
93
-		$this->connection = $connection;
94
-		$this->userManager = $userManager;
95
-		$this->userManager->setLdapAccess($this);
96
-		$this->helper = $helper;
97
-	}
98
-
99
-	/**
100
-	 * sets the User Mapper
101
-	 * @param AbstractMapping $mapper
102
-	 */
103
-	public function setUserMapper(AbstractMapping $mapper) {
104
-		$this->userMapper = $mapper;
105
-	}
106
-
107
-	/**
108
-	 * returns the User Mapper
109
-	 * @throws \Exception
110
-	 * @return AbstractMapping
111
-	 */
112
-	public function getUserMapper() {
113
-		if(is_null($this->userMapper)) {
114
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
115
-		}
116
-		return $this->userMapper;
117
-	}
118
-
119
-	/**
120
-	 * sets the Group Mapper
121
-	 * @param AbstractMapping $mapper
122
-	 */
123
-	public function setGroupMapper(AbstractMapping $mapper) {
124
-		$this->groupMapper = $mapper;
125
-	}
126
-
127
-	/**
128
-	 * returns the Group Mapper
129
-	 * @throws \Exception
130
-	 * @return AbstractMapping
131
-	 */
132
-	public function getGroupMapper() {
133
-		if(is_null($this->groupMapper)) {
134
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
135
-		}
136
-		return $this->groupMapper;
137
-	}
138
-
139
-	/**
140
-	 * @return bool
141
-	 */
142
-	private function checkConnection() {
143
-		return ($this->connection instanceof Connection);
144
-	}
145
-
146
-	/**
147
-	 * returns the Connection instance
148
-	 * @return \OCA\User_LDAP\Connection
149
-	 */
150
-	public function getConnection() {
151
-		return $this->connection;
152
-	}
153
-
154
-	/**
155
-	 * reads a given attribute for an LDAP record identified by a DN
156
-	 * @param string $dn the record in question
157
-	 * @param string $attr the attribute that shall be retrieved
158
-	 *        if empty, just check the record's existence
159
-	 * @param string $filter
160
-	 * @return array|false an array of values on success or an empty
161
-	 *          array if $attr is empty, false otherwise
162
-	 */
163
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
164
-		if(!$this->checkConnection()) {
165
-			\OCP\Util::writeLog('user_ldap',
166
-				'No LDAP Connector assigned, access impossible for readAttribute.',
167
-				\OCP\Util::WARN);
168
-			return false;
169
-		}
170
-		$cr = $this->connection->getConnectionResource();
171
-		if(!$this->ldap->isResource($cr)) {
172
-			//LDAP not available
173
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
174
-			return false;
175
-		}
176
-		//Cancel possibly running Paged Results operation, otherwise we run in
177
-		//LDAP protocol errors
178
-		$this->abandonPagedSearch();
179
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
180
-		// but does not hurt either.
181
-		$pagingSize = intval($this->connection->ldapPagingSize);
182
-		// 0 won't result in replies, small numbers may leave out groups
183
-		// (cf. #12306), 500 is default for paging and should work everywhere.
184
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
185
-		$attr = mb_strtolower($attr, 'UTF-8');
186
-		// the actual read attribute later may contain parameters on a ranged
187
-		// request, e.g. member;range=99-199. Depends on server reply.
188
-		$attrToRead = $attr;
189
-
190
-		$values = [];
191
-		$isRangeRequest = false;
192
-		do {
193
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
194
-			if(is_bool($result)) {
195
-				// when an exists request was run and it was successful, an empty
196
-				// array must be returned
197
-				return $result ? [] : false;
198
-			}
199
-
200
-			if (!$isRangeRequest) {
201
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
202
-				if (!empty($values)) {
203
-					return $values;
204
-				}
205
-			}
206
-
207
-			$isRangeRequest = false;
208
-			$result = $this->extractRangeData($result, $attr);
209
-			if (!empty($result)) {
210
-				$normalizedResult = $this->extractAttributeValuesFromResult(
211
-					[ $attr => $result['values'] ],
212
-					$attr
213
-				);
214
-				$values = array_merge($values, $normalizedResult);
215
-
216
-				if($result['rangeHigh'] === '*') {
217
-					// when server replies with * as high range value, there are
218
-					// no more results left
219
-					return $values;
220
-				} else {
221
-					$low  = $result['rangeHigh'] + 1;
222
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
223
-					$isRangeRequest = true;
224
-				}
225
-			}
226
-		} while($isRangeRequest);
227
-
228
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
229
-		return false;
230
-	}
231
-
232
-	/**
233
-	 * Runs an read operation against LDAP
234
-	 *
235
-	 * @param resource $cr the LDAP connection
236
-	 * @param string $dn
237
-	 * @param string $attribute
238
-	 * @param string $filter
239
-	 * @param int $maxResults
240
-	 * @return array|bool false if there was any error, true if an exists check
241
-	 *                    was performed and the requested DN found, array with the
242
-	 *                    returned data on a successful usual operation
243
-	 */
244
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
245
-		$this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
246
-		$dn = $this->helper->DNasBaseParameter($dn);
247
-		$rr = @$this->ldap->read($cr, $dn, $filter, array($attribute));
248
-		if (!$this->ldap->isResource($rr)) {
249
-			if ($attribute !== '') {
250
-				//do not throw this message on userExists check, irritates
251
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
252
-			}
253
-			//in case an error occurs , e.g. object does not exist
254
-			return false;
255
-		}
256
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->ldap->countEntries($cr, $rr) === 1)) {
257
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
258
-			return true;
259
-		}
260
-		$er = $this->ldap->firstEntry($cr, $rr);
261
-		if (!$this->ldap->isResource($er)) {
262
-			//did not match the filter, return false
263
-			return false;
264
-		}
265
-		//LDAP attributes are not case sensitive
266
-		$result = \OCP\Util::mb_array_change_key_case(
267
-			$this->ldap->getAttributes($cr, $er), MB_CASE_LOWER, 'UTF-8');
268
-
269
-		return $result;
270
-	}
271
-
272
-	/**
273
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
274
-	 * data if present.
275
-	 *
276
-	 * @param array $result from ILDAPWrapper::getAttributes()
277
-	 * @param string $attribute the attribute name that was read
278
-	 * @return string[]
279
-	 */
280
-	public function extractAttributeValuesFromResult($result, $attribute) {
281
-		$values = [];
282
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
283
-			$lowercaseAttribute = strtolower($attribute);
284
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
285
-				if($this->resemblesDN($attribute)) {
286
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
287
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
288
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
289
-				} else {
290
-					$values[] = $result[$attribute][$i];
291
-				}
292
-			}
293
-		}
294
-		return $values;
295
-	}
296
-
297
-	/**
298
-	 * Attempts to find ranged data in a getAttribute results and extracts the
299
-	 * returned values as well as information on the range and full attribute
300
-	 * name for further processing.
301
-	 *
302
-	 * @param array $result from ILDAPWrapper::getAttributes()
303
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
304
-	 * @return array If a range was detected with keys 'values', 'attributeName',
305
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
306
-	 */
307
-	public function extractRangeData($result, $attribute) {
308
-		$keys = array_keys($result);
309
-		foreach($keys as $key) {
310
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
311
-				$queryData = explode(';', $key);
312
-				if(strpos($queryData[1], 'range=') === 0) {
313
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
314
-					$data = [
315
-						'values' => $result[$key],
316
-						'attributeName' => $queryData[0],
317
-						'attributeFull' => $key,
318
-						'rangeHigh' => $high,
319
-					];
320
-					return $data;
321
-				}
322
-			}
323
-		}
324
-		return [];
325
-	}
85
+    /**
86
+     * @var \OCA\User_LDAP\Helper
87
+     */
88
+    private $helper;
89
+
90
+    public function __construct(Connection $connection, ILDAPWrapper $ldap,
91
+        Manager $userManager, Helper $helper) {
92
+        parent::__construct($ldap);
93
+        $this->connection = $connection;
94
+        $this->userManager = $userManager;
95
+        $this->userManager->setLdapAccess($this);
96
+        $this->helper = $helper;
97
+    }
98
+
99
+    /**
100
+     * sets the User Mapper
101
+     * @param AbstractMapping $mapper
102
+     */
103
+    public function setUserMapper(AbstractMapping $mapper) {
104
+        $this->userMapper = $mapper;
105
+    }
106
+
107
+    /**
108
+     * returns the User Mapper
109
+     * @throws \Exception
110
+     * @return AbstractMapping
111
+     */
112
+    public function getUserMapper() {
113
+        if(is_null($this->userMapper)) {
114
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
115
+        }
116
+        return $this->userMapper;
117
+    }
118
+
119
+    /**
120
+     * sets the Group Mapper
121
+     * @param AbstractMapping $mapper
122
+     */
123
+    public function setGroupMapper(AbstractMapping $mapper) {
124
+        $this->groupMapper = $mapper;
125
+    }
126
+
127
+    /**
128
+     * returns the Group Mapper
129
+     * @throws \Exception
130
+     * @return AbstractMapping
131
+     */
132
+    public function getGroupMapper() {
133
+        if(is_null($this->groupMapper)) {
134
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
135
+        }
136
+        return $this->groupMapper;
137
+    }
138
+
139
+    /**
140
+     * @return bool
141
+     */
142
+    private function checkConnection() {
143
+        return ($this->connection instanceof Connection);
144
+    }
145
+
146
+    /**
147
+     * returns the Connection instance
148
+     * @return \OCA\User_LDAP\Connection
149
+     */
150
+    public function getConnection() {
151
+        return $this->connection;
152
+    }
153
+
154
+    /**
155
+     * reads a given attribute for an LDAP record identified by a DN
156
+     * @param string $dn the record in question
157
+     * @param string $attr the attribute that shall be retrieved
158
+     *        if empty, just check the record's existence
159
+     * @param string $filter
160
+     * @return array|false an array of values on success or an empty
161
+     *          array if $attr is empty, false otherwise
162
+     */
163
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
164
+        if(!$this->checkConnection()) {
165
+            \OCP\Util::writeLog('user_ldap',
166
+                'No LDAP Connector assigned, access impossible for readAttribute.',
167
+                \OCP\Util::WARN);
168
+            return false;
169
+        }
170
+        $cr = $this->connection->getConnectionResource();
171
+        if(!$this->ldap->isResource($cr)) {
172
+            //LDAP not available
173
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
174
+            return false;
175
+        }
176
+        //Cancel possibly running Paged Results operation, otherwise we run in
177
+        //LDAP protocol errors
178
+        $this->abandonPagedSearch();
179
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
180
+        // but does not hurt either.
181
+        $pagingSize = intval($this->connection->ldapPagingSize);
182
+        // 0 won't result in replies, small numbers may leave out groups
183
+        // (cf. #12306), 500 is default for paging and should work everywhere.
184
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
185
+        $attr = mb_strtolower($attr, 'UTF-8');
186
+        // the actual read attribute later may contain parameters on a ranged
187
+        // request, e.g. member;range=99-199. Depends on server reply.
188
+        $attrToRead = $attr;
189
+
190
+        $values = [];
191
+        $isRangeRequest = false;
192
+        do {
193
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
194
+            if(is_bool($result)) {
195
+                // when an exists request was run and it was successful, an empty
196
+                // array must be returned
197
+                return $result ? [] : false;
198
+            }
199
+
200
+            if (!$isRangeRequest) {
201
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
202
+                if (!empty($values)) {
203
+                    return $values;
204
+                }
205
+            }
206
+
207
+            $isRangeRequest = false;
208
+            $result = $this->extractRangeData($result, $attr);
209
+            if (!empty($result)) {
210
+                $normalizedResult = $this->extractAttributeValuesFromResult(
211
+                    [ $attr => $result['values'] ],
212
+                    $attr
213
+                );
214
+                $values = array_merge($values, $normalizedResult);
215
+
216
+                if($result['rangeHigh'] === '*') {
217
+                    // when server replies with * as high range value, there are
218
+                    // no more results left
219
+                    return $values;
220
+                } else {
221
+                    $low  = $result['rangeHigh'] + 1;
222
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
223
+                    $isRangeRequest = true;
224
+                }
225
+            }
226
+        } while($isRangeRequest);
227
+
228
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
229
+        return false;
230
+    }
231
+
232
+    /**
233
+     * Runs an read operation against LDAP
234
+     *
235
+     * @param resource $cr the LDAP connection
236
+     * @param string $dn
237
+     * @param string $attribute
238
+     * @param string $filter
239
+     * @param int $maxResults
240
+     * @return array|bool false if there was any error, true if an exists check
241
+     *                    was performed and the requested DN found, array with the
242
+     *                    returned data on a successful usual operation
243
+     */
244
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
245
+        $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
246
+        $dn = $this->helper->DNasBaseParameter($dn);
247
+        $rr = @$this->ldap->read($cr, $dn, $filter, array($attribute));
248
+        if (!$this->ldap->isResource($rr)) {
249
+            if ($attribute !== '') {
250
+                //do not throw this message on userExists check, irritates
251
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
252
+            }
253
+            //in case an error occurs , e.g. object does not exist
254
+            return false;
255
+        }
256
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->ldap->countEntries($cr, $rr) === 1)) {
257
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
258
+            return true;
259
+        }
260
+        $er = $this->ldap->firstEntry($cr, $rr);
261
+        if (!$this->ldap->isResource($er)) {
262
+            //did not match the filter, return false
263
+            return false;
264
+        }
265
+        //LDAP attributes are not case sensitive
266
+        $result = \OCP\Util::mb_array_change_key_case(
267
+            $this->ldap->getAttributes($cr, $er), MB_CASE_LOWER, 'UTF-8');
268
+
269
+        return $result;
270
+    }
271
+
272
+    /**
273
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
274
+     * data if present.
275
+     *
276
+     * @param array $result from ILDAPWrapper::getAttributes()
277
+     * @param string $attribute the attribute name that was read
278
+     * @return string[]
279
+     */
280
+    public function extractAttributeValuesFromResult($result, $attribute) {
281
+        $values = [];
282
+        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
283
+            $lowercaseAttribute = strtolower($attribute);
284
+            for($i=0;$i<$result[$attribute]['count'];$i++) {
285
+                if($this->resemblesDN($attribute)) {
286
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
287
+                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
288
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
289
+                } else {
290
+                    $values[] = $result[$attribute][$i];
291
+                }
292
+            }
293
+        }
294
+        return $values;
295
+    }
296
+
297
+    /**
298
+     * Attempts to find ranged data in a getAttribute results and extracts the
299
+     * returned values as well as information on the range and full attribute
300
+     * name for further processing.
301
+     *
302
+     * @param array $result from ILDAPWrapper::getAttributes()
303
+     * @param string $attribute the attribute name that was read. Without ";range=…"
304
+     * @return array If a range was detected with keys 'values', 'attributeName',
305
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
306
+     */
307
+    public function extractRangeData($result, $attribute) {
308
+        $keys = array_keys($result);
309
+        foreach($keys as $key) {
310
+            if($key !== $attribute && strpos($key, $attribute) === 0) {
311
+                $queryData = explode(';', $key);
312
+                if(strpos($queryData[1], 'range=') === 0) {
313
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
314
+                    $data = [
315
+                        'values' => $result[$key],
316
+                        'attributeName' => $queryData[0],
317
+                        'attributeFull' => $key,
318
+                        'rangeHigh' => $high,
319
+                    ];
320
+                    return $data;
321
+                }
322
+            }
323
+        }
324
+        return [];
325
+    }
326 326
 	
327
-	/**
328
-	 * Set password for an LDAP user identified by a DN
329
-	 *
330
-	 * @param string $userDN the user in question
331
-	 * @param string $password the new password
332
-	 * @return bool
333
-	 * @throws HintException
334
-	 * @throws \Exception
335
-	 */
336
-	public function setPassword($userDN, $password) {
337
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
338
-			throw new \Exception('LDAP password changes are disabled.');
339
-		}
340
-		$cr = $this->connection->getConnectionResource();
341
-		if(!$this->ldap->isResource($cr)) {
342
-			//LDAP not available
343
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
344
-			return false;
345
-		}
327
+    /**
328
+     * Set password for an LDAP user identified by a DN
329
+     *
330
+     * @param string $userDN the user in question
331
+     * @param string $password the new password
332
+     * @return bool
333
+     * @throws HintException
334
+     * @throws \Exception
335
+     */
336
+    public function setPassword($userDN, $password) {
337
+        if(intval($this->connection->turnOnPasswordChange) !== 1) {
338
+            throw new \Exception('LDAP password changes are disabled.');
339
+        }
340
+        $cr = $this->connection->getConnectionResource();
341
+        if(!$this->ldap->isResource($cr)) {
342
+            //LDAP not available
343
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
344
+            return false;
345
+        }
346 346
 		
347
-		try {
348
-			return $this->ldap->modReplace($cr, $userDN, $password);
349
-		} catch(ConstraintViolationException $e) {
350
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
351
-		}
352
-	}
353
-
354
-	/**
355
-	 * checks whether the given attributes value is probably a DN
356
-	 * @param string $attr the attribute in question
357
-	 * @return boolean if so true, otherwise false
358
-	 */
359
-	private function resemblesDN($attr) {
360
-		$resemblingAttributes = array(
361
-			'dn',
362
-			'uniquemember',
363
-			'member',
364
-			// memberOf is an "operational" attribute, without a definition in any RFC
365
-			'memberof'
366
-		);
367
-		return in_array($attr, $resemblingAttributes);
368
-	}
369
-
370
-	/**
371
-	 * checks whether the given string is probably a DN
372
-	 * @param string $string
373
-	 * @return boolean
374
-	 */
375
-	public function stringResemblesDN($string) {
376
-		$r = $this->ldap->explodeDN($string, 0);
377
-		// if exploding a DN succeeds and does not end up in
378
-		// an empty array except for $r[count] being 0.
379
-		return (is_array($r) && count($r) > 1);
380
-	}
381
-
382
-	/**
383
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
384
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
385
-	 * becomes dc=foobar,dc=server,dc=org
386
-	 * @param string $dn
387
-	 * @return string
388
-	 */
389
-	public function getDomainDNFromDN($dn) {
390
-		$allParts = $this->ldap->explodeDN($dn, 0);
391
-		if($allParts === false) {
392
-			//not a valid DN
393
-			return '';
394
-		}
395
-		$domainParts = array();
396
-		$dcFound = false;
397
-		foreach($allParts as $part) {
398
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
399
-				$dcFound = true;
400
-			}
401
-			if($dcFound) {
402
-				$domainParts[] = $part;
403
-			}
404
-		}
405
-		$domainDN = implode(',', $domainParts);
406
-		return $domainDN;
407
-	}
408
-
409
-	/**
410
-	 * returns the LDAP DN for the given internal ownCloud name of the group
411
-	 * @param string $name the ownCloud name in question
412
-	 * @return string|false LDAP DN on success, otherwise false
413
-	 */
414
-	public function groupname2dn($name) {
415
-		return $this->groupMapper->getDNByName($name);
416
-	}
417
-
418
-	/**
419
-	 * returns the LDAP DN for the given internal ownCloud name of the user
420
-	 * @param string $name the ownCloud name in question
421
-	 * @return string|false with the LDAP DN on success, otherwise false
422
-	 */
423
-	public function username2dn($name) {
424
-		$fdn = $this->userMapper->getDNByName($name);
425
-
426
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
427
-		//server setups
428
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
429
-			return $fdn;
430
-		}
431
-
432
-		return false;
433
-	}
434
-
435
-	/**
436
-	 * returns the internal ownCloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
437
-	 * @param string $fdn the dn of the group object
438
-	 * @param string $ldapName optional, the display name of the object
439
-	 * @return string|false with the name to use in ownCloud, false on DN outside of search DN
440
-	 */
441
-	public function dn2groupname($fdn, $ldapName = null) {
442
-		//To avoid bypassing the base DN settings under certain circumstances
443
-		//with the group support, check whether the provided DN matches one of
444
-		//the given Bases
445
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
446
-			return false;
447
-		}
448
-
449
-		return $this->dn2ocname($fdn, $ldapName, false);
450
-	}
451
-
452
-	/**
453
-	 * accepts an array of group DNs and tests whether they match the user
454
-	 * filter by doing read operations against the group entries. Returns an
455
-	 * array of DNs that match the filter.
456
-	 *
457
-	 * @param string[] $groupDNs
458
-	 * @return string[]
459
-	 */
460
-	public function groupsMatchFilter($groupDNs) {
461
-		$validGroupDNs = [];
462
-		foreach($groupDNs as $dn) {
463
-			$cacheKey = 'groupsMatchFilter-'.$dn;
464
-			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
465
-			if(!is_null($groupMatchFilter)) {
466
-				if($groupMatchFilter) {
467
-					$validGroupDNs[] = $dn;
468
-				}
469
-				continue;
470
-			}
471
-
472
-			// Check the base DN first. If this is not met already, we don't
473
-			// need to ask the server at all.
474
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
475
-				$this->connection->writeToCache($cacheKey, false);
476
-				continue;
477
-			}
478
-
479
-			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
480
-			if(is_array($result)) {
481
-				$this->connection->writeToCache($cacheKey, true);
482
-				$validGroupDNs[] = $dn;
483
-			} else {
484
-				$this->connection->writeToCache($cacheKey, false);
485
-			}
486
-
487
-		}
488
-		return $validGroupDNs;
489
-	}
490
-
491
-	/**
492
-	 * returns the internal ownCloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
493
-	 * @param string $dn the dn of the user object
494
-	 * @param string $ldapName optional, the display name of the object
495
-	 * @return string|false with with the name to use in ownCloud
496
-	 */
497
-	public function dn2username($fdn, $ldapName = null) {
498
-		//To avoid bypassing the base DN settings under certain circumstances
499
-		//with the group support, check whether the provided DN matches one of
500
-		//the given Bases
501
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
502
-			return false;
503
-		}
504
-
505
-		return $this->dn2ocname($fdn, $ldapName, true);
506
-	}
507
-
508
-	/**
509
-	 * returns an internal ownCloud name for the given LDAP DN, false on DN outside of search DN
510
-	 * @param string $dn the dn of the user object
511
-	 * @param string $ldapName optional, the display name of the object
512
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
513
-	 * @return string|false with with the name to use in ownCloud
514
-	 */
515
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true) {
516
-		if($isUser) {
517
-			$mapper = $this->getUserMapper();
518
-			$nameAttribute = $this->connection->ldapUserDisplayName;
519
-		} else {
520
-			$mapper = $this->getGroupMapper();
521
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
522
-		}
523
-
524
-		//let's try to retrieve the ownCloud name from the mappings table
525
-		$ocName = $mapper->getNameByDN($fdn);
526
-		if(is_string($ocName)) {
527
-			return $ocName;
528
-		}
529
-
530
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
531
-		$uuid = $this->getUUID($fdn, $isUser);
532
-		if(is_string($uuid)) {
533
-			$ocName = $mapper->getNameByUUID($uuid);
534
-			if(is_string($ocName)) {
535
-				$mapper->setDNbyUUID($fdn, $uuid);
536
-				return $ocName;
537
-			}
538
-		} else {
539
-			//If the UUID can't be detected something is foul.
540
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
541
-			return false;
542
-		}
543
-
544
-		if(is_null($ldapName)) {
545
-			$ldapName = $this->readAttribute($fdn, $nameAttribute);
546
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
547
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
548
-				return false;
549
-			}
550
-			$ldapName = $ldapName[0];
551
-		}
552
-
553
-		if($isUser) {
554
-			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
555
-			if ($usernameAttribute !== '') {
556
-				$username = $this->readAttribute($fdn, $usernameAttribute);
557
-				$username = $username[0];
558
-			} else {
559
-				$username = $uuid;
560
-			}
561
-			$intName = $this->sanitizeUsername($username);
562
-		} else {
563
-			$intName = $ldapName;
564
-		}
565
-
566
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
567
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
568
-		//NOTE: mind, disabling cache affects only this instance! Using it
569
-		// outside of core user management will still cache the user as non-existing.
570
-		$originalTTL = $this->connection->ldapCacheTTL;
571
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
572
-		if(($isUser && !\OCP\User::userExists($intName))
573
-			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
574
-			if($mapper->map($fdn, $intName, $uuid)) {
575
-				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
576
-				return $intName;
577
-			}
578
-		}
579
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
580
-
581
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
582
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
583
-			return $altName;
584
-		}
585
-
586
-		//if everything else did not help..
587
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
588
-		return false;
589
-	}
590
-
591
-	/**
592
-	 * gives back the user names as they are used ownClod internally
593
-	 * @param array $ldapUsers as returned by fetchList()
594
-	 * @return array an array with the user names to use in ownCloud
595
-	 *
596
-	 * gives back the user names as they are used ownClod internally
597
-	 */
598
-	public function ownCloudUserNames($ldapUsers) {
599
-		return $this->ldap2ownCloudNames($ldapUsers, true);
600
-	}
601
-
602
-	/**
603
-	 * gives back the group names as they are used ownClod internally
604
-	 * @param array $ldapGroups as returned by fetchList()
605
-	 * @return array an array with the group names to use in ownCloud
606
-	 *
607
-	 * gives back the group names as they are used ownClod internally
608
-	 */
609
-	public function ownCloudGroupNames($ldapGroups) {
610
-		return $this->ldap2ownCloudNames($ldapGroups, false);
611
-	}
612
-
613
-	/**
614
-	 * @param array $ldapObjects as returned by fetchList()
615
-	 * @param bool $isUsers
616
-	 * @return array
617
-	 */
618
-	private function ldap2ownCloudNames($ldapObjects, $isUsers) {
619
-		if($isUsers) {
620
-			$nameAttribute = $this->connection->ldapUserDisplayName;
621
-			$sndAttribute  = $this->connection->ldapUserDisplayName2;
622
-		} else {
623
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
624
-		}
625
-		$ownCloudNames = array();
626
-
627
-		foreach($ldapObjects as $ldapObject) {
628
-			$nameByLDAP = null;
629
-			if(    isset($ldapObject[$nameAttribute])
630
-				&& is_array($ldapObject[$nameAttribute])
631
-				&& isset($ldapObject[$nameAttribute][0])
632
-			) {
633
-				// might be set, but not necessarily. if so, we use it.
634
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
635
-			}
636
-
637
-			$ocName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
638
-			if($ocName) {
639
-				$ownCloudNames[] = $ocName;
640
-				if($isUsers) {
641
-					//cache the user names so it does not need to be retrieved
642
-					//again later (e.g. sharing dialogue).
643
-					if(is_null($nameByLDAP)) {
644
-						continue;
645
-					}
646
-					$sndName = isset($ldapObject[$sndAttribute][0])
647
-						? $ldapObject[$sndAttribute][0] : '';
648
-					$this->cacheUserDisplayName($ocName, $nameByLDAP, $sndName);
649
-				}
650
-			}
651
-		}
652
-		return $ownCloudNames;
653
-	}
654
-
655
-	/**
656
-	 * caches the user display name
657
-	 * @param string $ocName the internal ownCloud username
658
-	 * @param string|false $home the home directory path
659
-	 */
660
-	public function cacheUserHome($ocName, $home) {
661
-		$cacheKey = 'getHome'.$ocName;
662
-		$this->connection->writeToCache($cacheKey, $home);
663
-	}
664
-
665
-	/**
666
-	 * caches a user as existing
667
-	 * @param string $ocName the internal ownCloud username
668
-	 */
669
-	public function cacheUserExists($ocName) {
670
-		$this->connection->writeToCache('userExists'.$ocName, true);
671
-	}
672
-
673
-	/**
674
-	 * caches the user display name
675
-	 * @param string $ocName the internal ownCloud username
676
-	 * @param string $displayName the display name
677
-	 * @param string $displayName2 the second display name
678
-	 */
679
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
680
-		$user = $this->userManager->get($ocName);
681
-		if($user === null) {
682
-			return;
683
-		}
684
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
685
-		$cacheKeyTrunk = 'getDisplayName';
686
-		$this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
687
-	}
688
-
689
-	/**
690
-	 * creates a unique name for internal ownCloud use for users. Don't call it directly.
691
-	 * @param string $name the display name of the object
692
-	 * @return string|false with with the name to use in ownCloud or false if unsuccessful
693
-	 *
694
-	 * Instead of using this method directly, call
695
-	 * createAltInternalOwnCloudName($name, true)
696
-	 */
697
-	private function _createAltInternalOwnCloudNameForUsers($name) {
698
-		$attempts = 0;
699
-		//while loop is just a precaution. If a name is not generated within
700
-		//20 attempts, something else is very wrong. Avoids infinite loop.
701
-		while($attempts < 20){
702
-			$altName = $name . '_' . rand(1000,9999);
703
-			if(!\OCP\User::userExists($altName)) {
704
-				return $altName;
705
-			}
706
-			$attempts++;
707
-		}
708
-		return false;
709
-	}
710
-
711
-	/**
712
-	 * creates a unique name for internal ownCloud use for groups. Don't call it directly.
713
-	 * @param string $name the display name of the object
714
-	 * @return string|false with with the name to use in ownCloud or false if unsuccessful.
715
-	 *
716
-	 * Instead of using this method directly, call
717
-	 * createAltInternalOwnCloudName($name, false)
718
-	 *
719
-	 * Group names are also used as display names, so we do a sequential
720
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
721
-	 * "Developers"
722
-	 */
723
-	private function _createAltInternalOwnCloudNameForGroups($name) {
724
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
725
-		if(!($usedNames) || count($usedNames) === 0) {
726
-			$lastNo = 1; //will become name_2
727
-		} else {
728
-			natsort($usedNames);
729
-			$lastName = array_pop($usedNames);
730
-			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
731
-		}
732
-		$altName = $name.'_'.strval($lastNo+1);
733
-		unset($usedNames);
734
-
735
-		$attempts = 1;
736
-		while($attempts < 21){
737
-			// Check to be really sure it is unique
738
-			// while loop is just a precaution. If a name is not generated within
739
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
740
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
741
-				return $altName;
742
-			}
743
-			$altName = $name . '_' . ($lastNo + $attempts);
744
-			$attempts++;
745
-		}
746
-		return false;
747
-	}
748
-
749
-	/**
750
-	 * creates a unique name for internal ownCloud use.
751
-	 * @param string $name the display name of the object
752
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
753
-	 * @return string|false with with the name to use in ownCloud or false if unsuccessful
754
-	 */
755
-	private function createAltInternalOwnCloudName($name, $isUser) {
756
-		$originalTTL = $this->connection->ldapCacheTTL;
757
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
758
-		if($isUser) {
759
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
760
-		} else {
761
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
762
-		}
763
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
764
-
765
-		return $altName;
766
-	}
767
-
768
-	/**
769
-	 * fetches a list of users according to a provided loginName and utilizing
770
-	 * the login filter.
771
-	 *
772
-	 * @param string $loginName
773
-	 * @param array $attributes optional, list of attributes to read
774
-	 * @return array
775
-	 */
776
-	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
777
-		$loginName = $this->escapeFilterPart($loginName);
778
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
779
-		$users = $this->fetchListOfUsers($filter, $attributes);
780
-		return $users;
781
-	}
782
-
783
-	/**
784
-	 * counts the number of users according to a provided loginName and
785
-	 * utilizing the login filter.
786
-	 *
787
-	 * @param string $loginName
788
-	 * @return array
789
-	 */
790
-	public function countUsersByLoginName($loginName) {
791
-		$loginName = $this->escapeFilterPart($loginName);
792
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
793
-		$users = $this->countUsers($filter);
794
-		return $users;
795
-	}
796
-
797
-	/**
798
-	 * @param string $filter
799
-	 * @param string|string[] $attr
800
-	 * @param int $limit
801
-	 * @param int $offset
802
-	 * @return array
803
-	 */
804
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null) {
805
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
806
-		$this->batchApplyUserAttributes($ldapRecords);
807
-		return $this->fetchList($ldapRecords, (count($attr) > 1));
808
-	}
809
-
810
-	/**
811
-	 * provided with an array of LDAP user records the method will fetch the
812
-	 * user object and requests it to process the freshly fetched attributes and
813
-	 * and their values
814
-	 * @param array $ldapRecords
815
-	 */
816
-	public function batchApplyUserAttributes(array $ldapRecords){
817
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
818
-		foreach($ldapRecords as $userRecord) {
819
-			if(!isset($userRecord[$displayNameAttribute])) {
820
-				// displayName is obligatory
821
-				continue;
822
-			}
823
-			$ocName  = $this->dn2ocname($userRecord['dn'][0]);
824
-			if($ocName === false) {
825
-				continue;
826
-			}
827
-			$this->cacheUserExists($ocName);
828
-			$user = $this->userManager->get($ocName);
829
-			if($user instanceof OfflineUser) {
830
-				$user->unmark();
831
-				$user = $this->userManager->get($ocName);
832
-			}
833
-			if ($user !== null) {
834
-				$user->processAttributes($userRecord);
835
-			} else {
836
-				\OC::$server->getLogger()->debug(
837
-					"The ldap user manager returned null for $ocName",
838
-					['app'=>'user_ldap']
839
-				);
840
-			}
841
-		}
842
-	}
843
-
844
-	/**
845
-	 * @param string $filter
846
-	 * @param string|string[] $attr
847
-	 * @param int $limit
848
-	 * @param int $offset
849
-	 * @return array
850
-	 */
851
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
852
-		return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
853
-	}
854
-
855
-	/**
856
-	 * @param array $list
857
-	 * @param bool $manyAttributes
858
-	 * @return array
859
-	 */
860
-	private function fetchList($list, $manyAttributes) {
861
-		if(is_array($list)) {
862
-			if($manyAttributes) {
863
-				return $list;
864
-			} else {
865
-				$list = array_reduce($list, function($carry, $item) {
866
-					$attribute = array_keys($item)[0];
867
-					$carry[] = $item[$attribute][0];
868
-					return $carry;
869
-				}, array());
870
-				return array_unique($list, SORT_LOCALE_STRING);
871
-			}
872
-		}
873
-
874
-		//error cause actually, maybe throw an exception in future.
875
-		return array();
876
-	}
877
-
878
-	/**
879
-	 * executes an LDAP search, optimized for Users
880
-	 * @param string $filter the LDAP filter for the search
881
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
882
-	 * @param integer $limit
883
-	 * @param integer $offset
884
-	 * @return array with the search result
885
-	 *
886
-	 * Executes an LDAP search
887
-	 */
888
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
889
-		return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
890
-	}
891
-
892
-	/**
893
-	 * @param string $filter
894
-	 * @param string|string[] $attr
895
-	 * @param int $limit
896
-	 * @param int $offset
897
-	 * @return false|int
898
-	 */
899
-	public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
900
-		return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
901
-	}
902
-
903
-	/**
904
-	 * executes an LDAP search, optimized for Groups
905
-	 * @param string $filter the LDAP filter for the search
906
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
907
-	 * @param integer $limit
908
-	 * @param integer $offset
909
-	 * @return array with the search result
910
-	 *
911
-	 * Executes an LDAP search
912
-	 */
913
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
914
-		return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
915
-	}
916
-
917
-	/**
918
-	 * returns the number of available groups
919
-	 * @param string $filter the LDAP search filter
920
-	 * @param string[] $attr optional
921
-	 * @param int|null $limit
922
-	 * @param int|null $offset
923
-	 * @return int|bool
924
-	 */
925
-	public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
926
-		return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
927
-	}
928
-
929
-	/**
930
-	 * returns the number of available objects on the base DN
931
-	 *
932
-	 * @param int|null $limit
933
-	 * @param int|null $offset
934
-	 * @return int|bool
935
-	 */
936
-	public function countObjects($limit = null, $offset = null) {
937
-		return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
938
-	}
939
-
940
-	/**
941
-	 * retrieved. Results will according to the order in the array.
942
-	 * @param int $limit optional, maximum results to be counted
943
-	 * @param int $offset optional, a starting point
944
-	 * @return array|false array with the search result as first value and pagedSearchOK as
945
-	 * second | false if not successful
946
-	 */
947
-	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
948
-		if(!is_null($attr) && !is_array($attr)) {
949
-			$attr = array(mb_strtolower($attr, 'UTF-8'));
950
-		}
951
-
952
-		// See if we have a resource, in case not cancel with message
953
-		$cr = $this->connection->getConnectionResource();
954
-		if(!$this->ldap->isResource($cr)) {
955
-			// Seems like we didn't find any resource.
956
-			// Return an empty array just like before.
957
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
958
-			return false;
959
-		}
960
-
961
-		//check whether paged search should be attempted
962
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
963
-
964
-		$linkResources = array_pad(array(), count($base), $cr);
965
-		$sr = $this->ldap->search($linkResources, $base, $filter, $attr);
966
-		$error = $this->ldap->errno($cr);
967
-		if(!is_array($sr) || $error !== 0) {
968
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
969
-			return false;
970
-		}
971
-
972
-		return array($sr, $pagedSearchOK);
973
-	}
974
-
975
-	/**
976
-	 * processes an LDAP paged search operation
977
-	 * @param array $sr the array containing the LDAP search resources
978
-	 * @param string $filter the LDAP filter for the search
979
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
980
-	 * @param int $iFoundItems number of results in the search operation
981
-	 * @param int $limit maximum results to be counted
982
-	 * @param int $offset a starting point
983
-	 * @param bool $pagedSearchOK whether a paged search has been executed
984
-	 * @param bool $skipHandling required for paged search when cookies to
985
-	 * prior results need to be gained
986
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
987
-	 */
988
-	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
989
-		$cookie = null;
990
-		if($pagedSearchOK) {
991
-			$cr = $this->connection->getConnectionResource();
992
-			foreach($sr as $key => $res) {
993
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
994
-					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
995
-				}
996
-			}
997
-
998
-			//browsing through prior pages to get the cookie for the new one
999
-			if($skipHandling) {
1000
-				return false;
1001
-			}
1002
-			// if count is bigger, then the server does not support
1003
-			// paged search. Instead, he did a normal search. We set a
1004
-			// flag here, so the callee knows how to deal with it.
1005
-			if($iFoundItems <= $limit) {
1006
-				$this->pagedSearchedSuccessful = true;
1007
-			}
1008
-		} else {
1009
-			if(!is_null($limit)) {
1010
-				\OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1011
-			}
1012
-		}
1013
-		/* ++ Fixing RHDS searches with pages with zero results ++
347
+        try {
348
+            return $this->ldap->modReplace($cr, $userDN, $password);
349
+        } catch(ConstraintViolationException $e) {
350
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
351
+        }
352
+    }
353
+
354
+    /**
355
+     * checks whether the given attributes value is probably a DN
356
+     * @param string $attr the attribute in question
357
+     * @return boolean if so true, otherwise false
358
+     */
359
+    private function resemblesDN($attr) {
360
+        $resemblingAttributes = array(
361
+            'dn',
362
+            'uniquemember',
363
+            'member',
364
+            // memberOf is an "operational" attribute, without a definition in any RFC
365
+            'memberof'
366
+        );
367
+        return in_array($attr, $resemblingAttributes);
368
+    }
369
+
370
+    /**
371
+     * checks whether the given string is probably a DN
372
+     * @param string $string
373
+     * @return boolean
374
+     */
375
+    public function stringResemblesDN($string) {
376
+        $r = $this->ldap->explodeDN($string, 0);
377
+        // if exploding a DN succeeds and does not end up in
378
+        // an empty array except for $r[count] being 0.
379
+        return (is_array($r) && count($r) > 1);
380
+    }
381
+
382
+    /**
383
+     * returns a DN-string that is cleaned from not domain parts, e.g.
384
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
385
+     * becomes dc=foobar,dc=server,dc=org
386
+     * @param string $dn
387
+     * @return string
388
+     */
389
+    public function getDomainDNFromDN($dn) {
390
+        $allParts = $this->ldap->explodeDN($dn, 0);
391
+        if($allParts === false) {
392
+            //not a valid DN
393
+            return '';
394
+        }
395
+        $domainParts = array();
396
+        $dcFound = false;
397
+        foreach($allParts as $part) {
398
+            if(!$dcFound && strpos($part, 'dc=') === 0) {
399
+                $dcFound = true;
400
+            }
401
+            if($dcFound) {
402
+                $domainParts[] = $part;
403
+            }
404
+        }
405
+        $domainDN = implode(',', $domainParts);
406
+        return $domainDN;
407
+    }
408
+
409
+    /**
410
+     * returns the LDAP DN for the given internal ownCloud name of the group
411
+     * @param string $name the ownCloud name in question
412
+     * @return string|false LDAP DN on success, otherwise false
413
+     */
414
+    public function groupname2dn($name) {
415
+        return $this->groupMapper->getDNByName($name);
416
+    }
417
+
418
+    /**
419
+     * returns the LDAP DN for the given internal ownCloud name of the user
420
+     * @param string $name the ownCloud name in question
421
+     * @return string|false with the LDAP DN on success, otherwise false
422
+     */
423
+    public function username2dn($name) {
424
+        $fdn = $this->userMapper->getDNByName($name);
425
+
426
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
427
+        //server setups
428
+        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
429
+            return $fdn;
430
+        }
431
+
432
+        return false;
433
+    }
434
+
435
+    /**
436
+     * returns the internal ownCloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
437
+     * @param string $fdn the dn of the group object
438
+     * @param string $ldapName optional, the display name of the object
439
+     * @return string|false with the name to use in ownCloud, false on DN outside of search DN
440
+     */
441
+    public function dn2groupname($fdn, $ldapName = null) {
442
+        //To avoid bypassing the base DN settings under certain circumstances
443
+        //with the group support, check whether the provided DN matches one of
444
+        //the given Bases
445
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
446
+            return false;
447
+        }
448
+
449
+        return $this->dn2ocname($fdn, $ldapName, false);
450
+    }
451
+
452
+    /**
453
+     * accepts an array of group DNs and tests whether they match the user
454
+     * filter by doing read operations against the group entries. Returns an
455
+     * array of DNs that match the filter.
456
+     *
457
+     * @param string[] $groupDNs
458
+     * @return string[]
459
+     */
460
+    public function groupsMatchFilter($groupDNs) {
461
+        $validGroupDNs = [];
462
+        foreach($groupDNs as $dn) {
463
+            $cacheKey = 'groupsMatchFilter-'.$dn;
464
+            $groupMatchFilter = $this->connection->getFromCache($cacheKey);
465
+            if(!is_null($groupMatchFilter)) {
466
+                if($groupMatchFilter) {
467
+                    $validGroupDNs[] = $dn;
468
+                }
469
+                continue;
470
+            }
471
+
472
+            // Check the base DN first. If this is not met already, we don't
473
+            // need to ask the server at all.
474
+            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
475
+                $this->connection->writeToCache($cacheKey, false);
476
+                continue;
477
+            }
478
+
479
+            $result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
480
+            if(is_array($result)) {
481
+                $this->connection->writeToCache($cacheKey, true);
482
+                $validGroupDNs[] = $dn;
483
+            } else {
484
+                $this->connection->writeToCache($cacheKey, false);
485
+            }
486
+
487
+        }
488
+        return $validGroupDNs;
489
+    }
490
+
491
+    /**
492
+     * returns the internal ownCloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
493
+     * @param string $dn the dn of the user object
494
+     * @param string $ldapName optional, the display name of the object
495
+     * @return string|false with with the name to use in ownCloud
496
+     */
497
+    public function dn2username($fdn, $ldapName = null) {
498
+        //To avoid bypassing the base DN settings under certain circumstances
499
+        //with the group support, check whether the provided DN matches one of
500
+        //the given Bases
501
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
502
+            return false;
503
+        }
504
+
505
+        return $this->dn2ocname($fdn, $ldapName, true);
506
+    }
507
+
508
+    /**
509
+     * returns an internal ownCloud name for the given LDAP DN, false on DN outside of search DN
510
+     * @param string $dn the dn of the user object
511
+     * @param string $ldapName optional, the display name of the object
512
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
513
+     * @return string|false with with the name to use in ownCloud
514
+     */
515
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true) {
516
+        if($isUser) {
517
+            $mapper = $this->getUserMapper();
518
+            $nameAttribute = $this->connection->ldapUserDisplayName;
519
+        } else {
520
+            $mapper = $this->getGroupMapper();
521
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
522
+        }
523
+
524
+        //let's try to retrieve the ownCloud name from the mappings table
525
+        $ocName = $mapper->getNameByDN($fdn);
526
+        if(is_string($ocName)) {
527
+            return $ocName;
528
+        }
529
+
530
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
531
+        $uuid = $this->getUUID($fdn, $isUser);
532
+        if(is_string($uuid)) {
533
+            $ocName = $mapper->getNameByUUID($uuid);
534
+            if(is_string($ocName)) {
535
+                $mapper->setDNbyUUID($fdn, $uuid);
536
+                return $ocName;
537
+            }
538
+        } else {
539
+            //If the UUID can't be detected something is foul.
540
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
541
+            return false;
542
+        }
543
+
544
+        if(is_null($ldapName)) {
545
+            $ldapName = $this->readAttribute($fdn, $nameAttribute);
546
+            if(!isset($ldapName[0]) && empty($ldapName[0])) {
547
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
548
+                return false;
549
+            }
550
+            $ldapName = $ldapName[0];
551
+        }
552
+
553
+        if($isUser) {
554
+            $usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
555
+            if ($usernameAttribute !== '') {
556
+                $username = $this->readAttribute($fdn, $usernameAttribute);
557
+                $username = $username[0];
558
+            } else {
559
+                $username = $uuid;
560
+            }
561
+            $intName = $this->sanitizeUsername($username);
562
+        } else {
563
+            $intName = $ldapName;
564
+        }
565
+
566
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
567
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
568
+        //NOTE: mind, disabling cache affects only this instance! Using it
569
+        // outside of core user management will still cache the user as non-existing.
570
+        $originalTTL = $this->connection->ldapCacheTTL;
571
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
572
+        if(($isUser && !\OCP\User::userExists($intName))
573
+            || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
574
+            if($mapper->map($fdn, $intName, $uuid)) {
575
+                $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
576
+                return $intName;
577
+            }
578
+        }
579
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
580
+
581
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
582
+        if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
583
+            return $altName;
584
+        }
585
+
586
+        //if everything else did not help..
587
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
588
+        return false;
589
+    }
590
+
591
+    /**
592
+     * gives back the user names as they are used ownClod internally
593
+     * @param array $ldapUsers as returned by fetchList()
594
+     * @return array an array with the user names to use in ownCloud
595
+     *
596
+     * gives back the user names as they are used ownClod internally
597
+     */
598
+    public function ownCloudUserNames($ldapUsers) {
599
+        return $this->ldap2ownCloudNames($ldapUsers, true);
600
+    }
601
+
602
+    /**
603
+     * gives back the group names as they are used ownClod internally
604
+     * @param array $ldapGroups as returned by fetchList()
605
+     * @return array an array with the group names to use in ownCloud
606
+     *
607
+     * gives back the group names as they are used ownClod internally
608
+     */
609
+    public function ownCloudGroupNames($ldapGroups) {
610
+        return $this->ldap2ownCloudNames($ldapGroups, false);
611
+    }
612
+
613
+    /**
614
+     * @param array $ldapObjects as returned by fetchList()
615
+     * @param bool $isUsers
616
+     * @return array
617
+     */
618
+    private function ldap2ownCloudNames($ldapObjects, $isUsers) {
619
+        if($isUsers) {
620
+            $nameAttribute = $this->connection->ldapUserDisplayName;
621
+            $sndAttribute  = $this->connection->ldapUserDisplayName2;
622
+        } else {
623
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
624
+        }
625
+        $ownCloudNames = array();
626
+
627
+        foreach($ldapObjects as $ldapObject) {
628
+            $nameByLDAP = null;
629
+            if(    isset($ldapObject[$nameAttribute])
630
+                && is_array($ldapObject[$nameAttribute])
631
+                && isset($ldapObject[$nameAttribute][0])
632
+            ) {
633
+                // might be set, but not necessarily. if so, we use it.
634
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
635
+            }
636
+
637
+            $ocName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
638
+            if($ocName) {
639
+                $ownCloudNames[] = $ocName;
640
+                if($isUsers) {
641
+                    //cache the user names so it does not need to be retrieved
642
+                    //again later (e.g. sharing dialogue).
643
+                    if(is_null($nameByLDAP)) {
644
+                        continue;
645
+                    }
646
+                    $sndName = isset($ldapObject[$sndAttribute][0])
647
+                        ? $ldapObject[$sndAttribute][0] : '';
648
+                    $this->cacheUserDisplayName($ocName, $nameByLDAP, $sndName);
649
+                }
650
+            }
651
+        }
652
+        return $ownCloudNames;
653
+    }
654
+
655
+    /**
656
+     * caches the user display name
657
+     * @param string $ocName the internal ownCloud username
658
+     * @param string|false $home the home directory path
659
+     */
660
+    public function cacheUserHome($ocName, $home) {
661
+        $cacheKey = 'getHome'.$ocName;
662
+        $this->connection->writeToCache($cacheKey, $home);
663
+    }
664
+
665
+    /**
666
+     * caches a user as existing
667
+     * @param string $ocName the internal ownCloud username
668
+     */
669
+    public function cacheUserExists($ocName) {
670
+        $this->connection->writeToCache('userExists'.$ocName, true);
671
+    }
672
+
673
+    /**
674
+     * caches the user display name
675
+     * @param string $ocName the internal ownCloud username
676
+     * @param string $displayName the display name
677
+     * @param string $displayName2 the second display name
678
+     */
679
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
680
+        $user = $this->userManager->get($ocName);
681
+        if($user === null) {
682
+            return;
683
+        }
684
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
685
+        $cacheKeyTrunk = 'getDisplayName';
686
+        $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
687
+    }
688
+
689
+    /**
690
+     * creates a unique name for internal ownCloud use for users. Don't call it directly.
691
+     * @param string $name the display name of the object
692
+     * @return string|false with with the name to use in ownCloud or false if unsuccessful
693
+     *
694
+     * Instead of using this method directly, call
695
+     * createAltInternalOwnCloudName($name, true)
696
+     */
697
+    private function _createAltInternalOwnCloudNameForUsers($name) {
698
+        $attempts = 0;
699
+        //while loop is just a precaution. If a name is not generated within
700
+        //20 attempts, something else is very wrong. Avoids infinite loop.
701
+        while($attempts < 20){
702
+            $altName = $name . '_' . rand(1000,9999);
703
+            if(!\OCP\User::userExists($altName)) {
704
+                return $altName;
705
+            }
706
+            $attempts++;
707
+        }
708
+        return false;
709
+    }
710
+
711
+    /**
712
+     * creates a unique name for internal ownCloud use for groups. Don't call it directly.
713
+     * @param string $name the display name of the object
714
+     * @return string|false with with the name to use in ownCloud or false if unsuccessful.
715
+     *
716
+     * Instead of using this method directly, call
717
+     * createAltInternalOwnCloudName($name, false)
718
+     *
719
+     * Group names are also used as display names, so we do a sequential
720
+     * numbering, e.g. Developers_42 when there are 41 other groups called
721
+     * "Developers"
722
+     */
723
+    private function _createAltInternalOwnCloudNameForGroups($name) {
724
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
725
+        if(!($usedNames) || count($usedNames) === 0) {
726
+            $lastNo = 1; //will become name_2
727
+        } else {
728
+            natsort($usedNames);
729
+            $lastName = array_pop($usedNames);
730
+            $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
731
+        }
732
+        $altName = $name.'_'.strval($lastNo+1);
733
+        unset($usedNames);
734
+
735
+        $attempts = 1;
736
+        while($attempts < 21){
737
+            // Check to be really sure it is unique
738
+            // while loop is just a precaution. If a name is not generated within
739
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
740
+            if(!\OC::$server->getGroupManager()->groupExists($altName)) {
741
+                return $altName;
742
+            }
743
+            $altName = $name . '_' . ($lastNo + $attempts);
744
+            $attempts++;
745
+        }
746
+        return false;
747
+    }
748
+
749
+    /**
750
+     * creates a unique name for internal ownCloud use.
751
+     * @param string $name the display name of the object
752
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
753
+     * @return string|false with with the name to use in ownCloud or false if unsuccessful
754
+     */
755
+    private function createAltInternalOwnCloudName($name, $isUser) {
756
+        $originalTTL = $this->connection->ldapCacheTTL;
757
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
758
+        if($isUser) {
759
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
760
+        } else {
761
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
762
+        }
763
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
764
+
765
+        return $altName;
766
+    }
767
+
768
+    /**
769
+     * fetches a list of users according to a provided loginName and utilizing
770
+     * the login filter.
771
+     *
772
+     * @param string $loginName
773
+     * @param array $attributes optional, list of attributes to read
774
+     * @return array
775
+     */
776
+    public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
777
+        $loginName = $this->escapeFilterPart($loginName);
778
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
779
+        $users = $this->fetchListOfUsers($filter, $attributes);
780
+        return $users;
781
+    }
782
+
783
+    /**
784
+     * counts the number of users according to a provided loginName and
785
+     * utilizing the login filter.
786
+     *
787
+     * @param string $loginName
788
+     * @return array
789
+     */
790
+    public function countUsersByLoginName($loginName) {
791
+        $loginName = $this->escapeFilterPart($loginName);
792
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
793
+        $users = $this->countUsers($filter);
794
+        return $users;
795
+    }
796
+
797
+    /**
798
+     * @param string $filter
799
+     * @param string|string[] $attr
800
+     * @param int $limit
801
+     * @param int $offset
802
+     * @return array
803
+     */
804
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null) {
805
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
806
+        $this->batchApplyUserAttributes($ldapRecords);
807
+        return $this->fetchList($ldapRecords, (count($attr) > 1));
808
+    }
809
+
810
+    /**
811
+     * provided with an array of LDAP user records the method will fetch the
812
+     * user object and requests it to process the freshly fetched attributes and
813
+     * and their values
814
+     * @param array $ldapRecords
815
+     */
816
+    public function batchApplyUserAttributes(array $ldapRecords){
817
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
818
+        foreach($ldapRecords as $userRecord) {
819
+            if(!isset($userRecord[$displayNameAttribute])) {
820
+                // displayName is obligatory
821
+                continue;
822
+            }
823
+            $ocName  = $this->dn2ocname($userRecord['dn'][0]);
824
+            if($ocName === false) {
825
+                continue;
826
+            }
827
+            $this->cacheUserExists($ocName);
828
+            $user = $this->userManager->get($ocName);
829
+            if($user instanceof OfflineUser) {
830
+                $user->unmark();
831
+                $user = $this->userManager->get($ocName);
832
+            }
833
+            if ($user !== null) {
834
+                $user->processAttributes($userRecord);
835
+            } else {
836
+                \OC::$server->getLogger()->debug(
837
+                    "The ldap user manager returned null for $ocName",
838
+                    ['app'=>'user_ldap']
839
+                );
840
+            }
841
+        }
842
+    }
843
+
844
+    /**
845
+     * @param string $filter
846
+     * @param string|string[] $attr
847
+     * @param int $limit
848
+     * @param int $offset
849
+     * @return array
850
+     */
851
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
852
+        return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
853
+    }
854
+
855
+    /**
856
+     * @param array $list
857
+     * @param bool $manyAttributes
858
+     * @return array
859
+     */
860
+    private function fetchList($list, $manyAttributes) {
861
+        if(is_array($list)) {
862
+            if($manyAttributes) {
863
+                return $list;
864
+            } else {
865
+                $list = array_reduce($list, function($carry, $item) {
866
+                    $attribute = array_keys($item)[0];
867
+                    $carry[] = $item[$attribute][0];
868
+                    return $carry;
869
+                }, array());
870
+                return array_unique($list, SORT_LOCALE_STRING);
871
+            }
872
+        }
873
+
874
+        //error cause actually, maybe throw an exception in future.
875
+        return array();
876
+    }
877
+
878
+    /**
879
+     * executes an LDAP search, optimized for Users
880
+     * @param string $filter the LDAP filter for the search
881
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
882
+     * @param integer $limit
883
+     * @param integer $offset
884
+     * @return array with the search result
885
+     *
886
+     * Executes an LDAP search
887
+     */
888
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
889
+        return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
890
+    }
891
+
892
+    /**
893
+     * @param string $filter
894
+     * @param string|string[] $attr
895
+     * @param int $limit
896
+     * @param int $offset
897
+     * @return false|int
898
+     */
899
+    public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
900
+        return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
901
+    }
902
+
903
+    /**
904
+     * executes an LDAP search, optimized for Groups
905
+     * @param string $filter the LDAP filter for the search
906
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
907
+     * @param integer $limit
908
+     * @param integer $offset
909
+     * @return array with the search result
910
+     *
911
+     * Executes an LDAP search
912
+     */
913
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
914
+        return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
915
+    }
916
+
917
+    /**
918
+     * returns the number of available groups
919
+     * @param string $filter the LDAP search filter
920
+     * @param string[] $attr optional
921
+     * @param int|null $limit
922
+     * @param int|null $offset
923
+     * @return int|bool
924
+     */
925
+    public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
926
+        return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
927
+    }
928
+
929
+    /**
930
+     * returns the number of available objects on the base DN
931
+     *
932
+     * @param int|null $limit
933
+     * @param int|null $offset
934
+     * @return int|bool
935
+     */
936
+    public function countObjects($limit = null, $offset = null) {
937
+        return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
938
+    }
939
+
940
+    /**
941
+     * retrieved. Results will according to the order in the array.
942
+     * @param int $limit optional, maximum results to be counted
943
+     * @param int $offset optional, a starting point
944
+     * @return array|false array with the search result as first value and pagedSearchOK as
945
+     * second | false if not successful
946
+     */
947
+    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
948
+        if(!is_null($attr) && !is_array($attr)) {
949
+            $attr = array(mb_strtolower($attr, 'UTF-8'));
950
+        }
951
+
952
+        // See if we have a resource, in case not cancel with message
953
+        $cr = $this->connection->getConnectionResource();
954
+        if(!$this->ldap->isResource($cr)) {
955
+            // Seems like we didn't find any resource.
956
+            // Return an empty array just like before.
957
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
958
+            return false;
959
+        }
960
+
961
+        //check whether paged search should be attempted
962
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
963
+
964
+        $linkResources = array_pad(array(), count($base), $cr);
965
+        $sr = $this->ldap->search($linkResources, $base, $filter, $attr);
966
+        $error = $this->ldap->errno($cr);
967
+        if(!is_array($sr) || $error !== 0) {
968
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
969
+            return false;
970
+        }
971
+
972
+        return array($sr, $pagedSearchOK);
973
+    }
974
+
975
+    /**
976
+     * processes an LDAP paged search operation
977
+     * @param array $sr the array containing the LDAP search resources
978
+     * @param string $filter the LDAP filter for the search
979
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
980
+     * @param int $iFoundItems number of results in the search operation
981
+     * @param int $limit maximum results to be counted
982
+     * @param int $offset a starting point
983
+     * @param bool $pagedSearchOK whether a paged search has been executed
984
+     * @param bool $skipHandling required for paged search when cookies to
985
+     * prior results need to be gained
986
+     * @return bool cookie validity, true if we have more pages, false otherwise.
987
+     */
988
+    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
989
+        $cookie = null;
990
+        if($pagedSearchOK) {
991
+            $cr = $this->connection->getConnectionResource();
992
+            foreach($sr as $key => $res) {
993
+                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
994
+                    $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
995
+                }
996
+            }
997
+
998
+            //browsing through prior pages to get the cookie for the new one
999
+            if($skipHandling) {
1000
+                return false;
1001
+            }
1002
+            // if count is bigger, then the server does not support
1003
+            // paged search. Instead, he did a normal search. We set a
1004
+            // flag here, so the callee knows how to deal with it.
1005
+            if($iFoundItems <= $limit) {
1006
+                $this->pagedSearchedSuccessful = true;
1007
+            }
1008
+        } else {
1009
+            if(!is_null($limit)) {
1010
+                \OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1011
+            }
1012
+        }
1013
+        /* ++ Fixing RHDS searches with pages with zero results ++
1014 1014
 		 * Return cookie status. If we don't have more pages, with RHDS
1015 1015
 		 * cookie is null, with openldap cookie is an empty string and
1016 1016
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1017 1017
 		 */
1018
-		return !empty($cookie) || $cookie === '0';
1019
-	}
1020
-
1021
-	/**
1022
-	 * executes an LDAP search, but counts the results only
1023
-	 * @param string $filter the LDAP filter for the search
1024
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1025
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1026
-	 * retrieved. Results will according to the order in the array.
1027
-	 * @param int $limit optional, maximum results to be counted
1028
-	 * @param int $offset optional, a starting point
1029
-	 * @param bool $skipHandling indicates whether the pages search operation is
1030
-	 * completed
1031
-	 * @return int|false Integer or false if the search could not be initialized
1032
-	 *
1033
-	 */
1034
-	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1035
-		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1036
-
1037
-		$limitPerPage = intval($this->connection->ldapPagingSize);
1038
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1039
-			$limitPerPage = $limit;
1040
-		}
1041
-
1042
-		$counter = 0;
1043
-		$count = null;
1044
-		$this->connection->getConnectionResource();
1045
-
1046
-		do {
1047
-			$search = $this->executeSearch($filter, $base, $attr,
1048
-										   $limitPerPage, $offset);
1049
-			if($search === false) {
1050
-				return $counter > 0 ? $counter : false;
1051
-			}
1052
-			list($sr, $pagedSearchOK) = $search;
1053
-
1054
-			/* ++ Fixing RHDS searches with pages with zero results ++
1018
+        return !empty($cookie) || $cookie === '0';
1019
+    }
1020
+
1021
+    /**
1022
+     * executes an LDAP search, but counts the results only
1023
+     * @param string $filter the LDAP filter for the search
1024
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1025
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1026
+     * retrieved. Results will according to the order in the array.
1027
+     * @param int $limit optional, maximum results to be counted
1028
+     * @param int $offset optional, a starting point
1029
+     * @param bool $skipHandling indicates whether the pages search operation is
1030
+     * completed
1031
+     * @return int|false Integer or false if the search could not be initialized
1032
+     *
1033
+     */
1034
+    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1035
+        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1036
+
1037
+        $limitPerPage = intval($this->connection->ldapPagingSize);
1038
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1039
+            $limitPerPage = $limit;
1040
+        }
1041
+
1042
+        $counter = 0;
1043
+        $count = null;
1044
+        $this->connection->getConnectionResource();
1045
+
1046
+        do {
1047
+            $search = $this->executeSearch($filter, $base, $attr,
1048
+                                            $limitPerPage, $offset);
1049
+            if($search === false) {
1050
+                return $counter > 0 ? $counter : false;
1051
+            }
1052
+            list($sr, $pagedSearchOK) = $search;
1053
+
1054
+            /* ++ Fixing RHDS searches with pages with zero results ++
1055 1055
 			 * countEntriesInSearchResults() method signature changed
1056 1056
 			 * by removing $limit and &$hasHitLimit parameters
1057 1057
 			 */
1058
-			$count = $this->countEntriesInSearchResults($sr);
1059
-			$counter += $count;
1058
+            $count = $this->countEntriesInSearchResults($sr);
1059
+            $counter += $count;
1060 1060
 
1061
-			$hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1062
-										$offset, $pagedSearchOK, $skipHandling);
1063
-			$offset += $limitPerPage;
1064
-			/* ++ Fixing RHDS searches with pages with zero results ++
1061
+            $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1062
+                                        $offset, $pagedSearchOK, $skipHandling);
1063
+            $offset += $limitPerPage;
1064
+            /* ++ Fixing RHDS searches with pages with zero results ++
1065 1065
 			 * Continue now depends on $hasMorePages value
1066 1066
 			 */
1067
-			$continue = $pagedSearchOK && $hasMorePages;
1068
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1069
-
1070
-		return $counter;
1071
-	}
1072
-
1073
-	/**
1074
-	 * @param array $searchResults
1075
-	 * @return int
1076
-	 */
1077
-	private function countEntriesInSearchResults($searchResults) {
1078
-		$cr = $this->connection->getConnectionResource();
1079
-		$counter = 0;
1080
-
1081
-		foreach($searchResults as $res) {
1082
-			$count = intval($this->ldap->countEntries($cr, $res));
1083
-			$counter += $count;
1084
-		}
1085
-
1086
-		return $counter;
1087
-	}
1088
-
1089
-	/**
1090
-	 * Executes an LDAP search
1091
-	 * @param string $filter the LDAP filter for the search
1092
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1093
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1094
-	 * @param int $limit
1095
-	 * @param int $offset
1096
-	 * @param bool $skipHandling
1097
-	 * @return array with the search result
1098
-	 */
1099
-	private function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1100
-		if($limit <= 0) {
1101
-			//otherwise search will fail
1102
-			$limit = null;
1103
-		}
1104
-
1105
-		/* ++ Fixing RHDS searches with pages with zero results ++
1067
+            $continue = $pagedSearchOK && $hasMorePages;
1068
+        } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1069
+
1070
+        return $counter;
1071
+    }
1072
+
1073
+    /**
1074
+     * @param array $searchResults
1075
+     * @return int
1076
+     */
1077
+    private function countEntriesInSearchResults($searchResults) {
1078
+        $cr = $this->connection->getConnectionResource();
1079
+        $counter = 0;
1080
+
1081
+        foreach($searchResults as $res) {
1082
+            $count = intval($this->ldap->countEntries($cr, $res));
1083
+            $counter += $count;
1084
+        }
1085
+
1086
+        return $counter;
1087
+    }
1088
+
1089
+    /**
1090
+     * Executes an LDAP search
1091
+     * @param string $filter the LDAP filter for the search
1092
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1093
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1094
+     * @param int $limit
1095
+     * @param int $offset
1096
+     * @param bool $skipHandling
1097
+     * @return array with the search result
1098
+     */
1099
+    private function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1100
+        if($limit <= 0) {
1101
+            //otherwise search will fail
1102
+            $limit = null;
1103
+        }
1104
+
1105
+        /* ++ Fixing RHDS searches with pages with zero results ++
1106 1106
 		 * As we can have pages with zero results and/or pages with less
1107 1107
 		 * than $limit results but with a still valid server 'cookie',
1108 1108
 		 * loops through until we get $continue equals true and
1109 1109
 		 * $findings['count'] < $limit
1110 1110
 		 */
1111
-		$findings = array();
1112
-		$savedoffset = $offset;
1113
-		do {
1114
-			$search = $this->executeSearch($filter, $base, $attr, $limit, $offset);
1115
-			if($search === false) {
1116
-				return array();
1117
-			}
1118
-			list($sr, $pagedSearchOK) = $search;
1119
-			$cr = $this->connection->getConnectionResource();
1120
-
1121
-			if($skipHandling) {
1122
-				//i.e. result do not need to be fetched, we just need the cookie
1123
-				//thus pass 1 or any other value as $iFoundItems because it is not
1124
-				//used
1125
-				$this->processPagedSearchStatus($sr, $filter, $base, 1, $limit,
1126
-								$offset, $pagedSearchOK,
1127
-								$skipHandling);
1128
-				return array();
1129
-			}
1130
-
1131
-			foreach($sr as $res) {
1132
-				$findings = array_merge($findings, $this->ldap->getEntries($cr	, $res ));
1133
-			}
1134
-
1135
-			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $findings['count'],
1136
-								$limit, $offset, $pagedSearchOK,
1137
-										$skipHandling);
1138
-			$offset += $limit;
1139
-		} while ($continue && $pagedSearchOK && $findings['count'] < $limit);
1140
-		// reseting offset
1141
-		$offset = $savedoffset;
1142
-
1143
-		// if we're here, probably no connection resource is returned.
1144
-		// to make ownCloud behave nicely, we simply give back an empty array.
1145
-		if(is_null($findings)) {
1146
-			return array();
1147
-		}
1148
-
1149
-		if(!is_null($attr)) {
1150
-			$selection = array();
1151
-			$i = 0;
1152
-			foreach($findings as $item) {
1153
-				if(!is_array($item)) {
1154
-					continue;
1155
-				}
1156
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1157
-				foreach($attr as $key) {
1158
-					$key = mb_strtolower($key, 'UTF-8');
1159
-					if(isset($item[$key])) {
1160
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1161
-							unset($item[$key]['count']);
1162
-						}
1163
-						if($key !== 'dn') {
1164
-							$selection[$i][$key] = $this->resemblesDN($key) ?
1165
-								$this->helper->sanitizeDN($item[$key])
1166
-								: $item[$key];
1167
-						} else {
1168
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1169
-						}
1170
-					}
1171
-
1172
-				}
1173
-				$i++;
1174
-			}
1175
-			$findings = $selection;
1176
-		}
1177
-		//we slice the findings, when
1178
-		//a) paged search unsuccessful, though attempted
1179
-		//b) no paged search, but limit set
1180
-		if((!$this->getPagedSearchResultState()
1181
-			&& $pagedSearchOK)
1182
-			|| (
1183
-				!$pagedSearchOK
1184
-				&& !is_null($limit)
1185
-			)
1186
-		) {
1187
-			$findings = array_slice($findings, intval($offset), $limit);
1188
-		}
1189
-		return $findings;
1190
-	}
1191
-
1192
-	/**
1193
-	 * @param string $name
1194
-	 * @return bool|mixed|string
1195
-	 */
1196
-	public function sanitizeUsername($name) {
1197
-		if($this->connection->ldapIgnoreNamingRules) {
1198
-			return $name;
1199
-		}
1200
-
1201
-		// Transliteration
1202
-		// latin characters to ASCII
1203
-		$name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1204
-
1205
-		// Replacements
1206
-		$name = str_replace(' ', '_', $name);
1207
-
1208
-		// Every remaining disallowed characters will be removed
1209
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1210
-
1211
-		return $name;
1212
-	}
1213
-
1214
-	/**
1215
-	* escapes (user provided) parts for LDAP filter
1216
-	* @param string $input, the provided value
1217
-	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1218
-	* @return string the escaped string
1219
-	*/
1220
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1221
-		$asterisk = '';
1222
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1223
-			$asterisk = '*';
1224
-			$input = mb_substr($input, 1, null, 'UTF-8');
1225
-		}
1226
-		$search  = array('*', '\\', '(', ')');
1227
-		$replace = array('\\*', '\\\\', '\\(', '\\)');
1228
-		return $asterisk . str_replace($search, $replace, $input);
1229
-	}
1230
-
1231
-	/**
1232
-	 * combines the input filters with AND
1233
-	 * @param string[] $filters the filters to connect
1234
-	 * @return string the combined filter
1235
-	 */
1236
-	public function combineFilterWithAnd($filters) {
1237
-		return $this->combineFilter($filters, '&');
1238
-	}
1239
-
1240
-	/**
1241
-	 * combines the input filters with OR
1242
-	 * @param string[] $filters the filters to connect
1243
-	 * @return string the combined filter
1244
-	 * Combines Filter arguments with OR
1245
-	 */
1246
-	public function combineFilterWithOr($filters) {
1247
-		return $this->combineFilter($filters, '|');
1248
-	}
1249
-
1250
-	/**
1251
-	 * combines the input filters with given operator
1252
-	 * @param string[] $filters the filters to connect
1253
-	 * @param string $operator either & or |
1254
-	 * @return string the combined filter
1255
-	 */
1256
-	private function combineFilter($filters, $operator) {
1257
-		$combinedFilter = '('.$operator;
1258
-		foreach($filters as $filter) {
1259
-			if ($filter !== '' && $filter[0] !== '(') {
1260
-				$filter = '('.$filter.')';
1261
-			}
1262
-			$combinedFilter.=$filter;
1263
-		}
1264
-		$combinedFilter.=')';
1265
-		return $combinedFilter;
1266
-	}
1267
-
1268
-	/**
1269
-	 * creates a filter part for to perform search for users
1270
-	 * @param string $search the search term
1271
-	 * @return string the final filter part to use in LDAP searches
1272
-	 */
1273
-	public function getFilterPartForUserSearch($search) {
1274
-		return $this->getFilterPartForSearch($search,
1275
-			$this->connection->ldapAttributesForUserSearch,
1276
-			$this->connection->ldapUserDisplayName);
1277
-	}
1278
-
1279
-	/**
1280
-	 * creates a filter part for to perform search for groups
1281
-	 * @param string $search the search term
1282
-	 * @return string the final filter part to use in LDAP searches
1283
-	 */
1284
-	public function getFilterPartForGroupSearch($search) {
1285
-		return $this->getFilterPartForSearch($search,
1286
-			$this->connection->ldapAttributesForGroupSearch,
1287
-			$this->connection->ldapGroupDisplayName);
1288
-	}
1289
-
1290
-	/**
1291
-	 * creates a filter part for searches by splitting up the given search
1292
-	 * string into single words
1293
-	 * @param string $search the search term
1294
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1295
-	 * otherwise it does not make sense :)
1296
-	 * @return string the final filter part to use in LDAP searches
1297
-	 * @throws \Exception
1298
-	 */
1299
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1300
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1301
-			throw new \Exception('searchAttributes must be an array with at least two string');
1302
-		}
1303
-		$searchWords = explode(' ', trim($search));
1304
-		$wordFilters = array();
1305
-		foreach($searchWords as $word) {
1306
-			$word = $this->prepareSearchTerm($word);
1307
-			//every word needs to appear at least once
1308
-			$wordMatchOneAttrFilters = array();
1309
-			foreach($searchAttributes as $attr) {
1310
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1311
-			}
1312
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1313
-		}
1314
-		return $this->combineFilterWithAnd($wordFilters);
1315
-	}
1316
-
1317
-	/**
1318
-	 * creates a filter part for searches
1319
-	 * @param string $search the search term
1320
-	 * @param string[]|null $searchAttributes
1321
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1322
-	 * did not define search attributes. Typically the display name attribute.
1323
-	 * @return string the final filter part to use in LDAP searches
1324
-	 */
1325
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1326
-		$filter = array();
1327
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1328
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1329
-			try {
1330
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1331
-			} catch(\Exception $e) {
1332
-				\OCP\Util::writeLog(
1333
-					'user_ldap',
1334
-					'Creating advanced filter for search failed, falling back to simple method.',
1335
-					\OCP\Util::INFO
1336
-				);
1337
-			}
1338
-		}
1339
-
1340
-		$search = $this->prepareSearchTerm($search);
1341
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1342
-			if ($fallbackAttribute === '') {
1343
-				return '';
1344
-			}
1345
-			$filter[] = $fallbackAttribute . '=' . $search;
1346
-		} else {
1347
-			foreach($searchAttributes as $attribute) {
1348
-				$filter[] = $attribute . '=' . $search;
1349
-			}
1350
-		}
1351
-		if(count($filter) === 1) {
1352
-			return '('.$filter[0].')';
1353
-		}
1354
-		return $this->combineFilterWithOr($filter);
1355
-	}
1356
-
1357
-	/**
1358
-	 * returns the search term depending on whether we are allowed
1359
-	 * list users found by ldap with the current input appended by
1360
-	 * a *
1361
-	 * @return string
1362
-	 */
1363
-	private function prepareSearchTerm($term) {
1364
-		$config = \OC::$server->getConfig();
1365
-
1366
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1367
-
1368
-		$result = $term;
1369
-		if ($term === '') {
1370
-			$result = '*';
1371
-		} else if ($allowEnum !== 'no') {
1372
-			$result = $term . '*';
1373
-		}
1374
-		return $result;
1375
-	}
1376
-
1377
-	/**
1378
-	 * returns the filter used for counting users
1379
-	 * @return string
1380
-	 */
1381
-	public function getFilterForUserCount() {
1382
-		$filter = $this->combineFilterWithAnd(array(
1383
-			$this->connection->ldapUserFilter,
1384
-			$this->connection->ldapUserDisplayName . '=*'
1385
-		));
1386
-
1387
-		return $filter;
1388
-	}
1389
-
1390
-	/**
1391
-	 * @param string $name
1392
-	 * @param string $password
1393
-	 * @return bool
1394
-	 */
1395
-	public function areCredentialsValid($name, $password) {
1396
-		$name = $this->helper->DNasBaseParameter($name);
1397
-		$testConnection = clone $this->connection;
1398
-		$credentials = array(
1399
-			'ldapAgentName' => $name,
1400
-			'ldapAgentPassword' => $password
1401
-		);
1402
-		if(!$testConnection->setConfiguration($credentials)) {
1403
-			return false;
1404
-		}
1405
-		return $testConnection->bind();
1406
-	}
1407
-
1408
-	/**
1409
-	 * reverse lookup of a DN given a known UUID
1410
-	 *
1411
-	 * @param string $uuid
1412
-	 * @return string
1413
-	 * @throws \Exception
1414
-	 */
1415
-	public function getUserDnByUuid($uuid) {
1416
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1417
-		$filter       = $this->connection->ldapUserFilter;
1418
-		$base         = $this->connection->ldapBaseUsers;
1419
-
1420
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1421
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1422
-			// existing DN to be able to reliably detect it.
1423
-			$result = $this->search($filter, $base, ['dn'], 1);
1424
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1425
-				throw new \Exception('Cannot determine UUID attribute');
1426
-			}
1427
-			$dn = $result[0]['dn'][0];
1428
-			if(!$this->detectUuidAttribute($dn, true)) {
1429
-				throw new \Exception('Cannot determine UUID attribute');
1430
-			}
1431
-		} else {
1432
-			// The UUID attribute is either known or an override is given.
1433
-			// By calling this method we ensure that $this->connection->$uuidAttr
1434
-			// is definitely set
1435
-			if(!$this->detectUuidAttribute('', true)) {
1436
-				throw new \Exception('Cannot determine UUID attribute');
1437
-			}
1438
-		}
1439
-
1440
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1441
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1442
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1443
-		}
1444
-
1445
-		$filter = $uuidAttr . '=' . $uuid;
1446
-		$result = $this->searchUsers($filter, ['dn'], 2);
1447
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1448
-			// we put the count into account to make sure that this is
1449
-			// really unique
1450
-			return $result[0]['dn'][0];
1451
-		}
1452
-
1453
-		throw new \Exception('Cannot determine UUID attribute');
1454
-	}
1455
-
1456
-	/**
1457
-	 * auto-detects the directory's UUID attribute
1458
-	 * @param string $dn a known DN used to check against
1459
-	 * @param bool $isUser
1460
-	 * @param bool $force the detection should be run, even if it is not set to auto
1461
-	 * @return bool true on success, false otherwise
1462
-	 */
1463
-	private function detectUuidAttribute($dn, $isUser = true, $force = false) {
1464
-		if($isUser) {
1465
-			$uuidAttr     = 'ldapUuidUserAttribute';
1466
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1467
-		} else {
1468
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1469
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1470
-		}
1471
-
1472
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1473
-			return true;
1474
-		}
1475
-
1476
-		if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1477
-			$this->connection->$uuidAttr = $uuidOverride;
1478
-			return true;
1479
-		}
1480
-
1481
-		// for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID
1482
-		$testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid');
1483
-
1484
-		foreach($testAttributes as $attribute) {
1485
-			$value = $this->readAttribute($dn, $attribute);
1486
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1487
-				\OCP\Util::writeLog('user_ldap',
1488
-									'Setting '.$attribute.' as '.$uuidAttr,
1489
-									\OCP\Util::DEBUG);
1490
-				$this->connection->$uuidAttr = $attribute;
1491
-				return true;
1492
-			}
1493
-		}
1494
-		\OCP\Util::writeLog('user_ldap',
1495
-							'Could not autodetect the UUID attribute',
1496
-							\OCP\Util::ERROR);
1497
-
1498
-		return false;
1499
-	}
1500
-
1501
-	/**
1502
-	 * @param string $dn
1503
-	 * @param bool $isUser
1504
-	 * @return string|bool
1505
-	 */
1506
-	public function getUUID($dn, $isUser = true) {
1507
-		if($isUser) {
1508
-			$uuidAttr     = 'ldapUuidUserAttribute';
1509
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1510
-		} else {
1511
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1512
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1513
-		}
1514
-
1515
-		$uuid = false;
1516
-		if($this->detectUuidAttribute($dn, $isUser)) {
1517
-			$uuid = $this->readAttribute($dn, $this->connection->$uuidAttr);
1518
-			if( !is_array($uuid)
1519
-				&& $uuidOverride !== ''
1520
-				&& $this->detectUuidAttribute($dn, $isUser, true)) {
1521
-					$uuid = $this->readAttribute($dn,
1522
-												 $this->connection->$uuidAttr);
1523
-			}
1524
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1525
-				$uuid = $uuid[0];
1526
-			}
1527
-		}
1528
-
1529
-		return $uuid;
1530
-	}
1531
-
1532
-	/**
1533
-	 * converts a binary ObjectGUID into a string representation
1534
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1535
-	 * @return string
1536
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1537
-	 */
1538
-	private function convertObjectGUID2Str($oguid) {
1539
-		$hex_guid = bin2hex($oguid);
1540
-		$hex_guid_to_guid_str = '';
1541
-		for($k = 1; $k <= 4; ++$k) {
1542
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1543
-		}
1544
-		$hex_guid_to_guid_str .= '-';
1545
-		for($k = 1; $k <= 2; ++$k) {
1546
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1547
-		}
1548
-		$hex_guid_to_guid_str .= '-';
1549
-		for($k = 1; $k <= 2; ++$k) {
1550
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1551
-		}
1552
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1553
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1554
-
1555
-		return strtoupper($hex_guid_to_guid_str);
1556
-	}
1557
-
1558
-	/**
1559
-	 * the first three blocks of the string-converted GUID happen to be in
1560
-	 * reverse order. In order to use it in a filter, this needs to be
1561
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1562
-	 * to every two hax figures.
1563
-	 *
1564
-	 * If an invalid string is passed, it will be returned without change.
1565
-	 *
1566
-	 * @param string $guid
1567
-	 * @return string
1568
-	 */
1569
-	public function formatGuid2ForFilterUser($guid) {
1570
-		if(!is_string($guid)) {
1571
-			throw new \InvalidArgumentException('String expected');
1572
-		}
1573
-		$blocks = explode('-', $guid);
1574
-		if(count($blocks) !== 5) {
1575
-			/*
1111
+        $findings = array();
1112
+        $savedoffset = $offset;
1113
+        do {
1114
+            $search = $this->executeSearch($filter, $base, $attr, $limit, $offset);
1115
+            if($search === false) {
1116
+                return array();
1117
+            }
1118
+            list($sr, $pagedSearchOK) = $search;
1119
+            $cr = $this->connection->getConnectionResource();
1120
+
1121
+            if($skipHandling) {
1122
+                //i.e. result do not need to be fetched, we just need the cookie
1123
+                //thus pass 1 or any other value as $iFoundItems because it is not
1124
+                //used
1125
+                $this->processPagedSearchStatus($sr, $filter, $base, 1, $limit,
1126
+                                $offset, $pagedSearchOK,
1127
+                                $skipHandling);
1128
+                return array();
1129
+            }
1130
+
1131
+            foreach($sr as $res) {
1132
+                $findings = array_merge($findings, $this->ldap->getEntries($cr	, $res ));
1133
+            }
1134
+
1135
+            $continue = $this->processPagedSearchStatus($sr, $filter, $base, $findings['count'],
1136
+                                $limit, $offset, $pagedSearchOK,
1137
+                                        $skipHandling);
1138
+            $offset += $limit;
1139
+        } while ($continue && $pagedSearchOK && $findings['count'] < $limit);
1140
+        // reseting offset
1141
+        $offset = $savedoffset;
1142
+
1143
+        // if we're here, probably no connection resource is returned.
1144
+        // to make ownCloud behave nicely, we simply give back an empty array.
1145
+        if(is_null($findings)) {
1146
+            return array();
1147
+        }
1148
+
1149
+        if(!is_null($attr)) {
1150
+            $selection = array();
1151
+            $i = 0;
1152
+            foreach($findings as $item) {
1153
+                if(!is_array($item)) {
1154
+                    continue;
1155
+                }
1156
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1157
+                foreach($attr as $key) {
1158
+                    $key = mb_strtolower($key, 'UTF-8');
1159
+                    if(isset($item[$key])) {
1160
+                        if(is_array($item[$key]) && isset($item[$key]['count'])) {
1161
+                            unset($item[$key]['count']);
1162
+                        }
1163
+                        if($key !== 'dn') {
1164
+                            $selection[$i][$key] = $this->resemblesDN($key) ?
1165
+                                $this->helper->sanitizeDN($item[$key])
1166
+                                : $item[$key];
1167
+                        } else {
1168
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1169
+                        }
1170
+                    }
1171
+
1172
+                }
1173
+                $i++;
1174
+            }
1175
+            $findings = $selection;
1176
+        }
1177
+        //we slice the findings, when
1178
+        //a) paged search unsuccessful, though attempted
1179
+        //b) no paged search, but limit set
1180
+        if((!$this->getPagedSearchResultState()
1181
+            && $pagedSearchOK)
1182
+            || (
1183
+                !$pagedSearchOK
1184
+                && !is_null($limit)
1185
+            )
1186
+        ) {
1187
+            $findings = array_slice($findings, intval($offset), $limit);
1188
+        }
1189
+        return $findings;
1190
+    }
1191
+
1192
+    /**
1193
+     * @param string $name
1194
+     * @return bool|mixed|string
1195
+     */
1196
+    public function sanitizeUsername($name) {
1197
+        if($this->connection->ldapIgnoreNamingRules) {
1198
+            return $name;
1199
+        }
1200
+
1201
+        // Transliteration
1202
+        // latin characters to ASCII
1203
+        $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1204
+
1205
+        // Replacements
1206
+        $name = str_replace(' ', '_', $name);
1207
+
1208
+        // Every remaining disallowed characters will be removed
1209
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1210
+
1211
+        return $name;
1212
+    }
1213
+
1214
+    /**
1215
+     * escapes (user provided) parts for LDAP filter
1216
+     * @param string $input, the provided value
1217
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1218
+     * @return string the escaped string
1219
+     */
1220
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1221
+        $asterisk = '';
1222
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1223
+            $asterisk = '*';
1224
+            $input = mb_substr($input, 1, null, 'UTF-8');
1225
+        }
1226
+        $search  = array('*', '\\', '(', ')');
1227
+        $replace = array('\\*', '\\\\', '\\(', '\\)');
1228
+        return $asterisk . str_replace($search, $replace, $input);
1229
+    }
1230
+
1231
+    /**
1232
+     * combines the input filters with AND
1233
+     * @param string[] $filters the filters to connect
1234
+     * @return string the combined filter
1235
+     */
1236
+    public function combineFilterWithAnd($filters) {
1237
+        return $this->combineFilter($filters, '&');
1238
+    }
1239
+
1240
+    /**
1241
+     * combines the input filters with OR
1242
+     * @param string[] $filters the filters to connect
1243
+     * @return string the combined filter
1244
+     * Combines Filter arguments with OR
1245
+     */
1246
+    public function combineFilterWithOr($filters) {
1247
+        return $this->combineFilter($filters, '|');
1248
+    }
1249
+
1250
+    /**
1251
+     * combines the input filters with given operator
1252
+     * @param string[] $filters the filters to connect
1253
+     * @param string $operator either & or |
1254
+     * @return string the combined filter
1255
+     */
1256
+    private function combineFilter($filters, $operator) {
1257
+        $combinedFilter = '('.$operator;
1258
+        foreach($filters as $filter) {
1259
+            if ($filter !== '' && $filter[0] !== '(') {
1260
+                $filter = '('.$filter.')';
1261
+            }
1262
+            $combinedFilter.=$filter;
1263
+        }
1264
+        $combinedFilter.=')';
1265
+        return $combinedFilter;
1266
+    }
1267
+
1268
+    /**
1269
+     * creates a filter part for to perform search for users
1270
+     * @param string $search the search term
1271
+     * @return string the final filter part to use in LDAP searches
1272
+     */
1273
+    public function getFilterPartForUserSearch($search) {
1274
+        return $this->getFilterPartForSearch($search,
1275
+            $this->connection->ldapAttributesForUserSearch,
1276
+            $this->connection->ldapUserDisplayName);
1277
+    }
1278
+
1279
+    /**
1280
+     * creates a filter part for to perform search for groups
1281
+     * @param string $search the search term
1282
+     * @return string the final filter part to use in LDAP searches
1283
+     */
1284
+    public function getFilterPartForGroupSearch($search) {
1285
+        return $this->getFilterPartForSearch($search,
1286
+            $this->connection->ldapAttributesForGroupSearch,
1287
+            $this->connection->ldapGroupDisplayName);
1288
+    }
1289
+
1290
+    /**
1291
+     * creates a filter part for searches by splitting up the given search
1292
+     * string into single words
1293
+     * @param string $search the search term
1294
+     * @param string[] $searchAttributes needs to have at least two attributes,
1295
+     * otherwise it does not make sense :)
1296
+     * @return string the final filter part to use in LDAP searches
1297
+     * @throws \Exception
1298
+     */
1299
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1300
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1301
+            throw new \Exception('searchAttributes must be an array with at least two string');
1302
+        }
1303
+        $searchWords = explode(' ', trim($search));
1304
+        $wordFilters = array();
1305
+        foreach($searchWords as $word) {
1306
+            $word = $this->prepareSearchTerm($word);
1307
+            //every word needs to appear at least once
1308
+            $wordMatchOneAttrFilters = array();
1309
+            foreach($searchAttributes as $attr) {
1310
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1311
+            }
1312
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1313
+        }
1314
+        return $this->combineFilterWithAnd($wordFilters);
1315
+    }
1316
+
1317
+    /**
1318
+     * creates a filter part for searches
1319
+     * @param string $search the search term
1320
+     * @param string[]|null $searchAttributes
1321
+     * @param string $fallbackAttribute a fallback attribute in case the user
1322
+     * did not define search attributes. Typically the display name attribute.
1323
+     * @return string the final filter part to use in LDAP searches
1324
+     */
1325
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1326
+        $filter = array();
1327
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1328
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1329
+            try {
1330
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1331
+            } catch(\Exception $e) {
1332
+                \OCP\Util::writeLog(
1333
+                    'user_ldap',
1334
+                    'Creating advanced filter for search failed, falling back to simple method.',
1335
+                    \OCP\Util::INFO
1336
+                );
1337
+            }
1338
+        }
1339
+
1340
+        $search = $this->prepareSearchTerm($search);
1341
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1342
+            if ($fallbackAttribute === '') {
1343
+                return '';
1344
+            }
1345
+            $filter[] = $fallbackAttribute . '=' . $search;
1346
+        } else {
1347
+            foreach($searchAttributes as $attribute) {
1348
+                $filter[] = $attribute . '=' . $search;
1349
+            }
1350
+        }
1351
+        if(count($filter) === 1) {
1352
+            return '('.$filter[0].')';
1353
+        }
1354
+        return $this->combineFilterWithOr($filter);
1355
+    }
1356
+
1357
+    /**
1358
+     * returns the search term depending on whether we are allowed
1359
+     * list users found by ldap with the current input appended by
1360
+     * a *
1361
+     * @return string
1362
+     */
1363
+    private function prepareSearchTerm($term) {
1364
+        $config = \OC::$server->getConfig();
1365
+
1366
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1367
+
1368
+        $result = $term;
1369
+        if ($term === '') {
1370
+            $result = '*';
1371
+        } else if ($allowEnum !== 'no') {
1372
+            $result = $term . '*';
1373
+        }
1374
+        return $result;
1375
+    }
1376
+
1377
+    /**
1378
+     * returns the filter used for counting users
1379
+     * @return string
1380
+     */
1381
+    public function getFilterForUserCount() {
1382
+        $filter = $this->combineFilterWithAnd(array(
1383
+            $this->connection->ldapUserFilter,
1384
+            $this->connection->ldapUserDisplayName . '=*'
1385
+        ));
1386
+
1387
+        return $filter;
1388
+    }
1389
+
1390
+    /**
1391
+     * @param string $name
1392
+     * @param string $password
1393
+     * @return bool
1394
+     */
1395
+    public function areCredentialsValid($name, $password) {
1396
+        $name = $this->helper->DNasBaseParameter($name);
1397
+        $testConnection = clone $this->connection;
1398
+        $credentials = array(
1399
+            'ldapAgentName' => $name,
1400
+            'ldapAgentPassword' => $password
1401
+        );
1402
+        if(!$testConnection->setConfiguration($credentials)) {
1403
+            return false;
1404
+        }
1405
+        return $testConnection->bind();
1406
+    }
1407
+
1408
+    /**
1409
+     * reverse lookup of a DN given a known UUID
1410
+     *
1411
+     * @param string $uuid
1412
+     * @return string
1413
+     * @throws \Exception
1414
+     */
1415
+    public function getUserDnByUuid($uuid) {
1416
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1417
+        $filter       = $this->connection->ldapUserFilter;
1418
+        $base         = $this->connection->ldapBaseUsers;
1419
+
1420
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1421
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1422
+            // existing DN to be able to reliably detect it.
1423
+            $result = $this->search($filter, $base, ['dn'], 1);
1424
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1425
+                throw new \Exception('Cannot determine UUID attribute');
1426
+            }
1427
+            $dn = $result[0]['dn'][0];
1428
+            if(!$this->detectUuidAttribute($dn, true)) {
1429
+                throw new \Exception('Cannot determine UUID attribute');
1430
+            }
1431
+        } else {
1432
+            // The UUID attribute is either known or an override is given.
1433
+            // By calling this method we ensure that $this->connection->$uuidAttr
1434
+            // is definitely set
1435
+            if(!$this->detectUuidAttribute('', true)) {
1436
+                throw new \Exception('Cannot determine UUID attribute');
1437
+            }
1438
+        }
1439
+
1440
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1441
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1442
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1443
+        }
1444
+
1445
+        $filter = $uuidAttr . '=' . $uuid;
1446
+        $result = $this->searchUsers($filter, ['dn'], 2);
1447
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1448
+            // we put the count into account to make sure that this is
1449
+            // really unique
1450
+            return $result[0]['dn'][0];
1451
+        }
1452
+
1453
+        throw new \Exception('Cannot determine UUID attribute');
1454
+    }
1455
+
1456
+    /**
1457
+     * auto-detects the directory's UUID attribute
1458
+     * @param string $dn a known DN used to check against
1459
+     * @param bool $isUser
1460
+     * @param bool $force the detection should be run, even if it is not set to auto
1461
+     * @return bool true on success, false otherwise
1462
+     */
1463
+    private function detectUuidAttribute($dn, $isUser = true, $force = false) {
1464
+        if($isUser) {
1465
+            $uuidAttr     = 'ldapUuidUserAttribute';
1466
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1467
+        } else {
1468
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1469
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1470
+        }
1471
+
1472
+        if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1473
+            return true;
1474
+        }
1475
+
1476
+        if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1477
+            $this->connection->$uuidAttr = $uuidOverride;
1478
+            return true;
1479
+        }
1480
+
1481
+        // for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID
1482
+        $testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid');
1483
+
1484
+        foreach($testAttributes as $attribute) {
1485
+            $value = $this->readAttribute($dn, $attribute);
1486
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1487
+                \OCP\Util::writeLog('user_ldap',
1488
+                                    'Setting '.$attribute.' as '.$uuidAttr,
1489
+                                    \OCP\Util::DEBUG);
1490
+                $this->connection->$uuidAttr = $attribute;
1491
+                return true;
1492
+            }
1493
+        }
1494
+        \OCP\Util::writeLog('user_ldap',
1495
+                            'Could not autodetect the UUID attribute',
1496
+                            \OCP\Util::ERROR);
1497
+
1498
+        return false;
1499
+    }
1500
+
1501
+    /**
1502
+     * @param string $dn
1503
+     * @param bool $isUser
1504
+     * @return string|bool
1505
+     */
1506
+    public function getUUID($dn, $isUser = true) {
1507
+        if($isUser) {
1508
+            $uuidAttr     = 'ldapUuidUserAttribute';
1509
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1510
+        } else {
1511
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1512
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1513
+        }
1514
+
1515
+        $uuid = false;
1516
+        if($this->detectUuidAttribute($dn, $isUser)) {
1517
+            $uuid = $this->readAttribute($dn, $this->connection->$uuidAttr);
1518
+            if( !is_array($uuid)
1519
+                && $uuidOverride !== ''
1520
+                && $this->detectUuidAttribute($dn, $isUser, true)) {
1521
+                    $uuid = $this->readAttribute($dn,
1522
+                                                    $this->connection->$uuidAttr);
1523
+            }
1524
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1525
+                $uuid = $uuid[0];
1526
+            }
1527
+        }
1528
+
1529
+        return $uuid;
1530
+    }
1531
+
1532
+    /**
1533
+     * converts a binary ObjectGUID into a string representation
1534
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1535
+     * @return string
1536
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1537
+     */
1538
+    private function convertObjectGUID2Str($oguid) {
1539
+        $hex_guid = bin2hex($oguid);
1540
+        $hex_guid_to_guid_str = '';
1541
+        for($k = 1; $k <= 4; ++$k) {
1542
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1543
+        }
1544
+        $hex_guid_to_guid_str .= '-';
1545
+        for($k = 1; $k <= 2; ++$k) {
1546
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1547
+        }
1548
+        $hex_guid_to_guid_str .= '-';
1549
+        for($k = 1; $k <= 2; ++$k) {
1550
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1551
+        }
1552
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1553
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1554
+
1555
+        return strtoupper($hex_guid_to_guid_str);
1556
+    }
1557
+
1558
+    /**
1559
+     * the first three blocks of the string-converted GUID happen to be in
1560
+     * reverse order. In order to use it in a filter, this needs to be
1561
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1562
+     * to every two hax figures.
1563
+     *
1564
+     * If an invalid string is passed, it will be returned without change.
1565
+     *
1566
+     * @param string $guid
1567
+     * @return string
1568
+     */
1569
+    public function formatGuid2ForFilterUser($guid) {
1570
+        if(!is_string($guid)) {
1571
+            throw new \InvalidArgumentException('String expected');
1572
+        }
1573
+        $blocks = explode('-', $guid);
1574
+        if(count($blocks) !== 5) {
1575
+            /*
1576 1576
 			 * Why not throw an Exception instead? This method is a utility
1577 1577
 			 * called only when trying to figure out whether a "missing" known
1578 1578
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1583,275 +1583,275 @@  discard block
 block discarded – undo
1583 1583
 			 * an exception here would kill the experience for a valid, acting
1584 1584
 			 * user. Instead we write a log message.
1585 1585
 			 */
1586
-			\OC::$server->getLogger()->info(
1587
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1588
-				'({uuid}) probably does not match UUID configuration.',
1589
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1590
-			);
1591
-			return $guid;
1592
-		}
1593
-		for($i=0; $i < 3; $i++) {
1594
-			$pairs = str_split($blocks[$i], 2);
1595
-			$pairs = array_reverse($pairs);
1596
-			$blocks[$i] = implode('', $pairs);
1597
-		}
1598
-		for($i=0; $i < 5; $i++) {
1599
-			$pairs = str_split($blocks[$i], 2);
1600
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1601
-		}
1602
-		return implode('', $blocks);
1603
-	}
1604
-
1605
-	/**
1606
-	 * gets a SID of the domain of the given dn
1607
-	 * @param string $dn
1608
-	 * @return string|bool
1609
-	 */
1610
-	public function getSID($dn) {
1611
-		$domainDN = $this->getDomainDNFromDN($dn);
1612
-		$cacheKey = 'getSID-'.$domainDN;
1613
-		$sid = $this->connection->getFromCache($cacheKey);
1614
-		if(!is_null($sid)) {
1615
-			return $sid;
1616
-		}
1617
-
1618
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1619
-		if(!is_array($objectSid) || empty($objectSid)) {
1620
-			$this->connection->writeToCache($cacheKey, false);
1621
-			return false;
1622
-		}
1623
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1624
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1625
-
1626
-		return $domainObjectSid;
1627
-	}
1628
-
1629
-	/**
1630
-	 * converts a binary SID into a string representation
1631
-	 * @param string $sid
1632
-	 * @return string
1633
-	 */
1634
-	public function convertSID2Str($sid) {
1635
-		// The format of a SID binary string is as follows:
1636
-		// 1 byte for the revision level
1637
-		// 1 byte for the number n of variable sub-ids
1638
-		// 6 bytes for identifier authority value
1639
-		// n*4 bytes for n sub-ids
1640
-		//
1641
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1642
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1643
-		$revision = ord($sid[0]);
1644
-		$numberSubID = ord($sid[1]);
1645
-
1646
-		$subIdStart = 8; // 1 + 1 + 6
1647
-		$subIdLength = 4;
1648
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1649
-			// Incorrect number of bytes present.
1650
-			return '';
1651
-		}
1652
-
1653
-		// 6 bytes = 48 bits can be represented using floats without loss of
1654
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1655
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1656
-
1657
-		$subIDs = array();
1658
-		for ($i = 0; $i < $numberSubID; $i++) {
1659
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1660
-			$subIDs[] = sprintf('%u', $subID[1]);
1661
-		}
1662
-
1663
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1664
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1665
-	}
1666
-
1667
-	/**
1668
-	 * checks if the given DN is part of the given base DN(s)
1669
-	 * @param string $dn the DN
1670
-	 * @param string[] $bases array containing the allowed base DN or DNs
1671
-	 * @return bool
1672
-	 */
1673
-	public function isDNPartOfBase($dn, $bases) {
1674
-		$belongsToBase = false;
1675
-		$bases = $this->helper->sanitizeDN($bases);
1676
-
1677
-		foreach($bases as $base) {
1678
-			$belongsToBase = true;
1679
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1680
-				$belongsToBase = false;
1681
-			}
1682
-			if($belongsToBase) {
1683
-				break;
1684
-			}
1685
-		}
1686
-		return $belongsToBase;
1687
-	}
1688
-
1689
-	/**
1690
-	 * resets a running Paged Search operation
1691
-	 */
1692
-	private function abandonPagedSearch() {
1693
-		if($this->connection->hasPagedResultSupport) {
1694
-			$cr = $this->connection->getConnectionResource();
1695
-			$this->ldap->controlPagedResult($cr, 0, false, $this->lastCookie);
1696
-			$this->getPagedSearchResultState();
1697
-			$this->lastCookie = '';
1698
-			$this->cookies = array();
1699
-		}
1700
-	}
1701
-
1702
-	/**
1703
-	 * get a cookie for the next LDAP paged search
1704
-	 * @param string $base a string with the base DN for the search
1705
-	 * @param string $filter the search filter to identify the correct search
1706
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1707
-	 * @param int $offset the offset for the new search to identify the correct search really good
1708
-	 * @return string containing the key or empty if none is cached
1709
-	 */
1710
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1711
-		if($offset === 0) {
1712
-			return '';
1713
-		}
1714
-		$offset -= $limit;
1715
-		//we work with cache here
1716
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1717
-		$cookie = '';
1718
-		if(isset($this->cookies[$cacheKey])) {
1719
-			$cookie = $this->cookies[$cacheKey];
1720
-			if(is_null($cookie)) {
1721
-				$cookie = '';
1722
-			}
1723
-		}
1724
-		return $cookie;
1725
-	}
1726
-
1727
-	/**
1728
-	 * checks whether an LDAP paged search operation has more pages that can be
1729
-	 * retrieved, typically when offset and limit are provided.
1730
-	 *
1731
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1732
-	 * be reset by other operations. Best, call it immediately after a search(),
1733
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1734
-	 * well. Don't rely on it with any fetchList-method.
1735
-	 * @return bool
1736
-	 */
1737
-	public function hasMoreResults() {
1738
-		if(!$this->connection->hasPagedResultSupport) {
1739
-			return false;
1740
-		}
1741
-
1742
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1743
-			// as in RFC 2696, when all results are returned, the cookie will
1744
-			// be empty.
1745
-			return false;
1746
-		}
1747
-
1748
-		return true;
1749
-	}
1750
-
1751
-	/**
1752
-	 * set a cookie for LDAP paged search run
1753
-	 * @param string $base a string with the base DN for the search
1754
-	 * @param string $filter the search filter to identify the correct search
1755
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1756
-	 * @param int $offset the offset for the run search to identify the correct search really good
1757
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1758
-	 * @return void
1759
-	 */
1760
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1761
-		// allow '0' for 389ds
1762
-		if(!empty($cookie) || $cookie === '0') {
1763
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1764
-			$this->cookies[$cacheKey] = $cookie;
1765
-			$this->lastCookie = $cookie;
1766
-		}
1767
-	}
1768
-
1769
-	/**
1770
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1771
-	 * @return boolean|null true on success, null or false otherwise
1772
-	 */
1773
-	public function getPagedSearchResultState() {
1774
-		$result = $this->pagedSearchedSuccessful;
1775
-		$this->pagedSearchedSuccessful = null;
1776
-		return $result;
1777
-	}
1778
-
1779
-	/**
1780
-	 * Prepares a paged search, if possible
1781
-	 * @param string $filter the LDAP filter for the search
1782
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1783
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
1784
-	 * @param int $limit
1785
-	 * @param int $offset
1786
-	 * @return bool|true
1787
-	 */
1788
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1789
-		$pagedSearchOK = false;
1790
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1791
-			$offset = intval($offset); //can be null
1792
-			\OCP\Util::writeLog('user_ldap',
1793
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1794
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1795
-				\OCP\Util::DEBUG);
1796
-			//get the cookie from the search for the previous search, required by LDAP
1797
-			foreach($bases as $base) {
1798
-
1799
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1800
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1801
-					// no cookie known, although the offset is not 0. Maybe cache run out. We need
1802
-					// to start all over *sigh* (btw, Dear Reader, did you know LDAP paged
1803
-					// searching was designed by MSFT?)
1804
-					// 		Lukas: No, but thanks to reading that source I finally know!
1805
-					// '0' is valid, because 389ds
1806
-					$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1807
-					//a bit recursive, $offset of 0 is the exit
1808
-					\OCP\Util::writeLog('user_ldap', 'Looking for cookie L/O '.$limit.'/'.$reOffset, \OCP\Util::INFO);
1809
-					$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1810
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1811
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1812
-					//TODO: remember this, probably does not change in the next request...
1813
-					if(empty($cookie) && $cookie !== '0') {
1814
-						// '0' is valid, because 389ds
1815
-						$cookie = null;
1816
-					}
1817
-				}
1818
-				if(!is_null($cookie)) {
1819
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1820
-					$this->abandonPagedSearch();
1821
-					$pagedSearchOK = $this->ldap->controlPagedResult(
1822
-						$this->connection->getConnectionResource(), $limit,
1823
-						false, $cookie);
1824
-					if(!$pagedSearchOK) {
1825
-						return false;
1826
-					}
1827
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1828
-				} else {
1829
-					\OCP\Util::writeLog('user_ldap',
1830
-						'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
1831
-						\OCP\Util::INFO);
1832
-				}
1833
-
1834
-			}
1835
-		/* ++ Fixing RHDS searches with pages with zero results ++
1586
+            \OC::$server->getLogger()->info(
1587
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1588
+                '({uuid}) probably does not match UUID configuration.',
1589
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1590
+            );
1591
+            return $guid;
1592
+        }
1593
+        for($i=0; $i < 3; $i++) {
1594
+            $pairs = str_split($blocks[$i], 2);
1595
+            $pairs = array_reverse($pairs);
1596
+            $blocks[$i] = implode('', $pairs);
1597
+        }
1598
+        for($i=0; $i < 5; $i++) {
1599
+            $pairs = str_split($blocks[$i], 2);
1600
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1601
+        }
1602
+        return implode('', $blocks);
1603
+    }
1604
+
1605
+    /**
1606
+     * gets a SID of the domain of the given dn
1607
+     * @param string $dn
1608
+     * @return string|bool
1609
+     */
1610
+    public function getSID($dn) {
1611
+        $domainDN = $this->getDomainDNFromDN($dn);
1612
+        $cacheKey = 'getSID-'.$domainDN;
1613
+        $sid = $this->connection->getFromCache($cacheKey);
1614
+        if(!is_null($sid)) {
1615
+            return $sid;
1616
+        }
1617
+
1618
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1619
+        if(!is_array($objectSid) || empty($objectSid)) {
1620
+            $this->connection->writeToCache($cacheKey, false);
1621
+            return false;
1622
+        }
1623
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1624
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1625
+
1626
+        return $domainObjectSid;
1627
+    }
1628
+
1629
+    /**
1630
+     * converts a binary SID into a string representation
1631
+     * @param string $sid
1632
+     * @return string
1633
+     */
1634
+    public function convertSID2Str($sid) {
1635
+        // The format of a SID binary string is as follows:
1636
+        // 1 byte for the revision level
1637
+        // 1 byte for the number n of variable sub-ids
1638
+        // 6 bytes for identifier authority value
1639
+        // n*4 bytes for n sub-ids
1640
+        //
1641
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1642
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1643
+        $revision = ord($sid[0]);
1644
+        $numberSubID = ord($sid[1]);
1645
+
1646
+        $subIdStart = 8; // 1 + 1 + 6
1647
+        $subIdLength = 4;
1648
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1649
+            // Incorrect number of bytes present.
1650
+            return '';
1651
+        }
1652
+
1653
+        // 6 bytes = 48 bits can be represented using floats without loss of
1654
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1655
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1656
+
1657
+        $subIDs = array();
1658
+        for ($i = 0; $i < $numberSubID; $i++) {
1659
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1660
+            $subIDs[] = sprintf('%u', $subID[1]);
1661
+        }
1662
+
1663
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1664
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1665
+    }
1666
+
1667
+    /**
1668
+     * checks if the given DN is part of the given base DN(s)
1669
+     * @param string $dn the DN
1670
+     * @param string[] $bases array containing the allowed base DN or DNs
1671
+     * @return bool
1672
+     */
1673
+    public function isDNPartOfBase($dn, $bases) {
1674
+        $belongsToBase = false;
1675
+        $bases = $this->helper->sanitizeDN($bases);
1676
+
1677
+        foreach($bases as $base) {
1678
+            $belongsToBase = true;
1679
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1680
+                $belongsToBase = false;
1681
+            }
1682
+            if($belongsToBase) {
1683
+                break;
1684
+            }
1685
+        }
1686
+        return $belongsToBase;
1687
+    }
1688
+
1689
+    /**
1690
+     * resets a running Paged Search operation
1691
+     */
1692
+    private function abandonPagedSearch() {
1693
+        if($this->connection->hasPagedResultSupport) {
1694
+            $cr = $this->connection->getConnectionResource();
1695
+            $this->ldap->controlPagedResult($cr, 0, false, $this->lastCookie);
1696
+            $this->getPagedSearchResultState();
1697
+            $this->lastCookie = '';
1698
+            $this->cookies = array();
1699
+        }
1700
+    }
1701
+
1702
+    /**
1703
+     * get a cookie for the next LDAP paged search
1704
+     * @param string $base a string with the base DN for the search
1705
+     * @param string $filter the search filter to identify the correct search
1706
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1707
+     * @param int $offset the offset for the new search to identify the correct search really good
1708
+     * @return string containing the key or empty if none is cached
1709
+     */
1710
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1711
+        if($offset === 0) {
1712
+            return '';
1713
+        }
1714
+        $offset -= $limit;
1715
+        //we work with cache here
1716
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1717
+        $cookie = '';
1718
+        if(isset($this->cookies[$cacheKey])) {
1719
+            $cookie = $this->cookies[$cacheKey];
1720
+            if(is_null($cookie)) {
1721
+                $cookie = '';
1722
+            }
1723
+        }
1724
+        return $cookie;
1725
+    }
1726
+
1727
+    /**
1728
+     * checks whether an LDAP paged search operation has more pages that can be
1729
+     * retrieved, typically when offset and limit are provided.
1730
+     *
1731
+     * Be very careful to use it: the last cookie value, which is inspected, can
1732
+     * be reset by other operations. Best, call it immediately after a search(),
1733
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1734
+     * well. Don't rely on it with any fetchList-method.
1735
+     * @return bool
1736
+     */
1737
+    public function hasMoreResults() {
1738
+        if(!$this->connection->hasPagedResultSupport) {
1739
+            return false;
1740
+        }
1741
+
1742
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1743
+            // as in RFC 2696, when all results are returned, the cookie will
1744
+            // be empty.
1745
+            return false;
1746
+        }
1747
+
1748
+        return true;
1749
+    }
1750
+
1751
+    /**
1752
+     * set a cookie for LDAP paged search run
1753
+     * @param string $base a string with the base DN for the search
1754
+     * @param string $filter the search filter to identify the correct search
1755
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1756
+     * @param int $offset the offset for the run search to identify the correct search really good
1757
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1758
+     * @return void
1759
+     */
1760
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1761
+        // allow '0' for 389ds
1762
+        if(!empty($cookie) || $cookie === '0') {
1763
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1764
+            $this->cookies[$cacheKey] = $cookie;
1765
+            $this->lastCookie = $cookie;
1766
+        }
1767
+    }
1768
+
1769
+    /**
1770
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1771
+     * @return boolean|null true on success, null or false otherwise
1772
+     */
1773
+    public function getPagedSearchResultState() {
1774
+        $result = $this->pagedSearchedSuccessful;
1775
+        $this->pagedSearchedSuccessful = null;
1776
+        return $result;
1777
+    }
1778
+
1779
+    /**
1780
+     * Prepares a paged search, if possible
1781
+     * @param string $filter the LDAP filter for the search
1782
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1783
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
1784
+     * @param int $limit
1785
+     * @param int $offset
1786
+     * @return bool|true
1787
+     */
1788
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1789
+        $pagedSearchOK = false;
1790
+        if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1791
+            $offset = intval($offset); //can be null
1792
+            \OCP\Util::writeLog('user_ldap',
1793
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1794
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1795
+                \OCP\Util::DEBUG);
1796
+            //get the cookie from the search for the previous search, required by LDAP
1797
+            foreach($bases as $base) {
1798
+
1799
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1800
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1801
+                    // no cookie known, although the offset is not 0. Maybe cache run out. We need
1802
+                    // to start all over *sigh* (btw, Dear Reader, did you know LDAP paged
1803
+                    // searching was designed by MSFT?)
1804
+                    // 		Lukas: No, but thanks to reading that source I finally know!
1805
+                    // '0' is valid, because 389ds
1806
+                    $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1807
+                    //a bit recursive, $offset of 0 is the exit
1808
+                    \OCP\Util::writeLog('user_ldap', 'Looking for cookie L/O '.$limit.'/'.$reOffset, \OCP\Util::INFO);
1809
+                    $this->search($filter, array($base), $attr, $limit, $reOffset, true);
1810
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1811
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1812
+                    //TODO: remember this, probably does not change in the next request...
1813
+                    if(empty($cookie) && $cookie !== '0') {
1814
+                        // '0' is valid, because 389ds
1815
+                        $cookie = null;
1816
+                    }
1817
+                }
1818
+                if(!is_null($cookie)) {
1819
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1820
+                    $this->abandonPagedSearch();
1821
+                    $pagedSearchOK = $this->ldap->controlPagedResult(
1822
+                        $this->connection->getConnectionResource(), $limit,
1823
+                        false, $cookie);
1824
+                    if(!$pagedSearchOK) {
1825
+                        return false;
1826
+                    }
1827
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1828
+                } else {
1829
+                    \OCP\Util::writeLog('user_ldap',
1830
+                        'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
1831
+                        \OCP\Util::INFO);
1832
+                }
1833
+
1834
+            }
1835
+        /* ++ Fixing RHDS searches with pages with zero results ++
1836 1836
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
1837 1837
 		 * due to pages with zero results.
1838 1838
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1839 1839
 		 * if we don't have a previous paged search.
1840 1840
 		 */
1841
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1842
-			// a search without limit was requested. However, if we do use
1843
-			// Paged Search once, we always must do it. This requires us to
1844
-			// initialize it with the configured page size.
1845
-			$this->abandonPagedSearch();
1846
-			// in case someone set it to 0 … use 500, otherwise no results will
1847
-			// be returned.
1848
-			$pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1849
-			$pagedSearchOK = $this->ldap->controlPagedResult(
1850
-				$this->connection->getConnectionResource(), $pageSize, false, ''
1851
-			);
1852
-		}
1853
-
1854
-		return $pagedSearchOK;
1855
-	}
1841
+        } else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1842
+            // a search without limit was requested. However, if we do use
1843
+            // Paged Search once, we always must do it. This requires us to
1844
+            // initialize it with the configured page size.
1845
+            $this->abandonPagedSearch();
1846
+            // in case someone set it to 0 … use 500, otherwise no results will
1847
+            // be returned.
1848
+            $pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1849
+            $pagedSearchOK = $this->ldap->controlPagedResult(
1850
+                $this->connection->getConnectionResource(), $pageSize, false, ''
1851
+            );
1852
+        }
1853
+
1854
+        return $pagedSearchOK;
1855
+    }
1856 1856
 
1857 1857
 }
Please login to merge, or discard this patch.
Spacing   +163 added lines, -163 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 	 * @return AbstractMapping
111 111
 	 */
112 112
 	public function getUserMapper() {
113
-		if(is_null($this->userMapper)) {
113
+		if (is_null($this->userMapper)) {
114 114
 			throw new \Exception('UserMapper was not assigned to this Access instance.');
115 115
 		}
116 116
 		return $this->userMapper;
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 	 * @return AbstractMapping
131 131
 	 */
132 132
 	public function getGroupMapper() {
133
-		if(is_null($this->groupMapper)) {
133
+		if (is_null($this->groupMapper)) {
134 134
 			throw new \Exception('GroupMapper was not assigned to this Access instance.');
135 135
 		}
136 136
 		return $this->groupMapper;
@@ -161,14 +161,14 @@  discard block
 block discarded – undo
161 161
 	 *          array if $attr is empty, false otherwise
162 162
 	 */
163 163
 	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
164
-		if(!$this->checkConnection()) {
164
+		if (!$this->checkConnection()) {
165 165
 			\OCP\Util::writeLog('user_ldap',
166 166
 				'No LDAP Connector assigned, access impossible for readAttribute.',
167 167
 				\OCP\Util::WARN);
168 168
 			return false;
169 169
 		}
170 170
 		$cr = $this->connection->getConnectionResource();
171
-		if(!$this->ldap->isResource($cr)) {
171
+		if (!$this->ldap->isResource($cr)) {
172 172
 			//LDAP not available
173 173
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
174 174
 			return false;
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 		$isRangeRequest = false;
192 192
 		do {
193 193
 			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
194
-			if(is_bool($result)) {
194
+			if (is_bool($result)) {
195 195
 				// when an exists request was run and it was successful, an empty
196 196
 				// array must be returned
197 197
 				return $result ? [] : false;
@@ -208,22 +208,22 @@  discard block
 block discarded – undo
208 208
 			$result = $this->extractRangeData($result, $attr);
209 209
 			if (!empty($result)) {
210 210
 				$normalizedResult = $this->extractAttributeValuesFromResult(
211
-					[ $attr => $result['values'] ],
211
+					[$attr => $result['values']],
212 212
 					$attr
213 213
 				);
214 214
 				$values = array_merge($values, $normalizedResult);
215 215
 
216
-				if($result['rangeHigh'] === '*') {
216
+				if ($result['rangeHigh'] === '*') {
217 217
 					// when server replies with * as high range value, there are
218 218
 					// no more results left
219 219
 					return $values;
220 220
 				} else {
221
-					$low  = $result['rangeHigh'] + 1;
222
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
221
+					$low = $result['rangeHigh'] + 1;
222
+					$attrToRead = $result['attributeName'].';range='.$low.'-*';
223 223
 					$isRangeRequest = true;
224 224
 				}
225 225
 			}
226
-		} while($isRangeRequest);
226
+		} while ($isRangeRequest);
227 227
 
228 228
 		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
229 229
 		return false;
@@ -248,13 +248,13 @@  discard block
 block discarded – undo
248 248
 		if (!$this->ldap->isResource($rr)) {
249 249
 			if ($attribute !== '') {
250 250
 				//do not throw this message on userExists check, irritates
251
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
251
+				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, \OCP\Util::DEBUG);
252 252
 			}
253 253
 			//in case an error occurs , e.g. object does not exist
254 254
 			return false;
255 255
 		}
256 256
 		if ($attribute === '' && ($filter === 'objectclass=*' || $this->ldap->countEntries($cr, $rr) === 1)) {
257
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
257
+			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', \OCP\Util::DEBUG);
258 258
 			return true;
259 259
 		}
260 260
 		$er = $this->ldap->firstEntry($cr, $rr);
@@ -279,12 +279,12 @@  discard block
 block discarded – undo
279 279
 	 */
280 280
 	public function extractAttributeValuesFromResult($result, $attribute) {
281 281
 		$values = [];
282
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
282
+		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
283 283
 			$lowercaseAttribute = strtolower($attribute);
284
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
285
-				if($this->resemblesDN($attribute)) {
284
+			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
285
+				if ($this->resemblesDN($attribute)) {
286 286
 					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
287
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
287
+				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
288 288
 					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
289 289
 				} else {
290 290
 					$values[] = $result[$attribute][$i];
@@ -306,10 +306,10 @@  discard block
 block discarded – undo
306 306
 	 */
307 307
 	public function extractRangeData($result, $attribute) {
308 308
 		$keys = array_keys($result);
309
-		foreach($keys as $key) {
310
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
309
+		foreach ($keys as $key) {
310
+			if ($key !== $attribute && strpos($key, $attribute) === 0) {
311 311
 				$queryData = explode(';', $key);
312
-				if(strpos($queryData[1], 'range=') === 0) {
312
+				if (strpos($queryData[1], 'range=') === 0) {
313 313
 					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
314 314
 					$data = [
315 315
 						'values' => $result[$key],
@@ -334,11 +334,11 @@  discard block
 block discarded – undo
334 334
 	 * @throws \Exception
335 335
 	 */
336 336
 	public function setPassword($userDN, $password) {
337
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
337
+		if (intval($this->connection->turnOnPasswordChange) !== 1) {
338 338
 			throw new \Exception('LDAP password changes are disabled.');
339 339
 		}
340 340
 		$cr = $this->connection->getConnectionResource();
341
-		if(!$this->ldap->isResource($cr)) {
341
+		if (!$this->ldap->isResource($cr)) {
342 342
 			//LDAP not available
343 343
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
344 344
 			return false;
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
 		
347 347
 		try {
348 348
 			return $this->ldap->modReplace($cr, $userDN, $password);
349
-		} catch(ConstraintViolationException $e) {
349
+		} catch (ConstraintViolationException $e) {
350 350
 			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
351 351
 		}
352 352
 	}
@@ -388,17 +388,17 @@  discard block
 block discarded – undo
388 388
 	 */
389 389
 	public function getDomainDNFromDN($dn) {
390 390
 		$allParts = $this->ldap->explodeDN($dn, 0);
391
-		if($allParts === false) {
391
+		if ($allParts === false) {
392 392
 			//not a valid DN
393 393
 			return '';
394 394
 		}
395 395
 		$domainParts = array();
396 396
 		$dcFound = false;
397
-		foreach($allParts as $part) {
398
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
397
+		foreach ($allParts as $part) {
398
+			if (!$dcFound && strpos($part, 'dc=') === 0) {
399 399
 				$dcFound = true;
400 400
 			}
401
-			if($dcFound) {
401
+			if ($dcFound) {
402 402
 				$domainParts[] = $part;
403 403
 			}
404 404
 		}
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 
426 426
 		//Check whether the DN belongs to the Base, to avoid issues on multi-
427 427
 		//server setups
428
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
428
+		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
429 429
 			return $fdn;
430 430
 		}
431 431
 
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 		//To avoid bypassing the base DN settings under certain circumstances
443 443
 		//with the group support, check whether the provided DN matches one of
444 444
 		//the given Bases
445
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
445
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
446 446
 			return false;
447 447
 		}
448 448
 
@@ -459,11 +459,11 @@  discard block
 block discarded – undo
459 459
 	 */
460 460
 	public function groupsMatchFilter($groupDNs) {
461 461
 		$validGroupDNs = [];
462
-		foreach($groupDNs as $dn) {
462
+		foreach ($groupDNs as $dn) {
463 463
 			$cacheKey = 'groupsMatchFilter-'.$dn;
464 464
 			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
465
-			if(!is_null($groupMatchFilter)) {
466
-				if($groupMatchFilter) {
465
+			if (!is_null($groupMatchFilter)) {
466
+				if ($groupMatchFilter) {
467 467
 					$validGroupDNs[] = $dn;
468 468
 				}
469 469
 				continue;
@@ -471,13 +471,13 @@  discard block
 block discarded – undo
471 471
 
472 472
 			// Check the base DN first. If this is not met already, we don't
473 473
 			// need to ask the server at all.
474
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
474
+			if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
475 475
 				$this->connection->writeToCache($cacheKey, false);
476 476
 				continue;
477 477
 			}
478 478
 
479 479
 			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
480
-			if(is_array($result)) {
480
+			if (is_array($result)) {
481 481
 				$this->connection->writeToCache($cacheKey, true);
482 482
 				$validGroupDNs[] = $dn;
483 483
 			} else {
@@ -498,7 +498,7 @@  discard block
 block discarded – undo
498 498
 		//To avoid bypassing the base DN settings under certain circumstances
499 499
 		//with the group support, check whether the provided DN matches one of
500 500
 		//the given Bases
501
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
501
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
502 502
 			return false;
503 503
 		}
504 504
 
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
 	 * @return string|false with with the name to use in ownCloud
514 514
 	 */
515 515
 	public function dn2ocname($fdn, $ldapName = null, $isUser = true) {
516
-		if($isUser) {
516
+		if ($isUser) {
517 517
 			$mapper = $this->getUserMapper();
518 518
 			$nameAttribute = $this->connection->ldapUserDisplayName;
519 519
 		} else {
@@ -523,15 +523,15 @@  discard block
 block discarded – undo
523 523
 
524 524
 		//let's try to retrieve the ownCloud name from the mappings table
525 525
 		$ocName = $mapper->getNameByDN($fdn);
526
-		if(is_string($ocName)) {
526
+		if (is_string($ocName)) {
527 527
 			return $ocName;
528 528
 		}
529 529
 
530 530
 		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
531 531
 		$uuid = $this->getUUID($fdn, $isUser);
532
-		if(is_string($uuid)) {
532
+		if (is_string($uuid)) {
533 533
 			$ocName = $mapper->getNameByUUID($uuid);
534
-			if(is_string($ocName)) {
534
+			if (is_string($ocName)) {
535 535
 				$mapper->setDNbyUUID($fdn, $uuid);
536 536
 				return $ocName;
537 537
 			}
@@ -541,16 +541,16 @@  discard block
 block discarded – undo
541 541
 			return false;
542 542
 		}
543 543
 
544
-		if(is_null($ldapName)) {
544
+		if (is_null($ldapName)) {
545 545
 			$ldapName = $this->readAttribute($fdn, $nameAttribute);
546
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
546
+			if (!isset($ldapName[0]) && empty($ldapName[0])) {
547 547
 				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
548 548
 				return false;
549 549
 			}
550 550
 			$ldapName = $ldapName[0];
551 551
 		}
552 552
 
553
-		if($isUser) {
553
+		if ($isUser) {
554 554
 			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
555 555
 			if ($usernameAttribute !== '') {
556 556
 				$username = $this->readAttribute($fdn, $usernameAttribute);
@@ -569,9 +569,9 @@  discard block
 block discarded – undo
569 569
 		// outside of core user management will still cache the user as non-existing.
570 570
 		$originalTTL = $this->connection->ldapCacheTTL;
571 571
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
572
-		if(($isUser && !\OCP\User::userExists($intName))
572
+		if (($isUser && !\OCP\User::userExists($intName))
573 573
 			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
574
-			if($mapper->map($fdn, $intName, $uuid)) {
574
+			if ($mapper->map($fdn, $intName, $uuid)) {
575 575
 				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
576 576
 				return $intName;
577 577
 			}
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
 		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
580 580
 
581 581
 		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
582
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
582
+		if (is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
583 583
 			return $altName;
584 584
 		}
585 585
 
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 	 * @return array
617 617
 	 */
618 618
 	private function ldap2ownCloudNames($ldapObjects, $isUsers) {
619
-		if($isUsers) {
619
+		if ($isUsers) {
620 620
 			$nameAttribute = $this->connection->ldapUserDisplayName;
621 621
 			$sndAttribute  = $this->connection->ldapUserDisplayName2;
622 622
 		} else {
@@ -624,9 +624,9 @@  discard block
 block discarded – undo
624 624
 		}
625 625
 		$ownCloudNames = array();
626 626
 
627
-		foreach($ldapObjects as $ldapObject) {
627
+		foreach ($ldapObjects as $ldapObject) {
628 628
 			$nameByLDAP = null;
629
-			if(    isset($ldapObject[$nameAttribute])
629
+			if (isset($ldapObject[$nameAttribute])
630 630
 				&& is_array($ldapObject[$nameAttribute])
631 631
 				&& isset($ldapObject[$nameAttribute][0])
632 632
 			) {
@@ -635,12 +635,12 @@  discard block
 block discarded – undo
635 635
 			}
636 636
 
637 637
 			$ocName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
638
-			if($ocName) {
638
+			if ($ocName) {
639 639
 				$ownCloudNames[] = $ocName;
640
-				if($isUsers) {
640
+				if ($isUsers) {
641 641
 					//cache the user names so it does not need to be retrieved
642 642
 					//again later (e.g. sharing dialogue).
643
-					if(is_null($nameByLDAP)) {
643
+					if (is_null($nameByLDAP)) {
644 644
 						continue;
645 645
 					}
646 646
 					$sndName = isset($ldapObject[$sndAttribute][0])
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
 	 */
679 679
 	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
680 680
 		$user = $this->userManager->get($ocName);
681
-		if($user === null) {
681
+		if ($user === null) {
682 682
 			return;
683 683
 		}
684 684
 		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
@@ -698,9 +698,9 @@  discard block
 block discarded – undo
698 698
 		$attempts = 0;
699 699
 		//while loop is just a precaution. If a name is not generated within
700 700
 		//20 attempts, something else is very wrong. Avoids infinite loop.
701
-		while($attempts < 20){
702
-			$altName = $name . '_' . rand(1000,9999);
703
-			if(!\OCP\User::userExists($altName)) {
701
+		while ($attempts < 20) {
702
+			$altName = $name.'_'.rand(1000, 9999);
703
+			if (!\OCP\User::userExists($altName)) {
704 704
 				return $altName;
705 705
 			}
706 706
 			$attempts++;
@@ -722,25 +722,25 @@  discard block
 block discarded – undo
722 722
 	 */
723 723
 	private function _createAltInternalOwnCloudNameForGroups($name) {
724 724
 		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
725
-		if(!($usedNames) || count($usedNames) === 0) {
725
+		if (!($usedNames) || count($usedNames) === 0) {
726 726
 			$lastNo = 1; //will become name_2
727 727
 		} else {
728 728
 			natsort($usedNames);
729 729
 			$lastName = array_pop($usedNames);
730 730
 			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
731 731
 		}
732
-		$altName = $name.'_'.strval($lastNo+1);
732
+		$altName = $name.'_'.strval($lastNo + 1);
733 733
 		unset($usedNames);
734 734
 
735 735
 		$attempts = 1;
736
-		while($attempts < 21){
736
+		while ($attempts < 21) {
737 737
 			// Check to be really sure it is unique
738 738
 			// while loop is just a precaution. If a name is not generated within
739 739
 			// 20 attempts, something else is very wrong. Avoids infinite loop.
740
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
740
+			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
741 741
 				return $altName;
742 742
 			}
743
-			$altName = $name . '_' . ($lastNo + $attempts);
743
+			$altName = $name.'_'.($lastNo + $attempts);
744 744
 			$attempts++;
745 745
 		}
746 746
 		return false;
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
 	private function createAltInternalOwnCloudName($name, $isUser) {
756 756
 		$originalTTL = $this->connection->ldapCacheTTL;
757 757
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
758
-		if($isUser) {
758
+		if ($isUser) {
759 759
 			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
760 760
 		} else {
761 761
 			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
@@ -813,20 +813,20 @@  discard block
 block discarded – undo
813 813
 	 * and their values
814 814
 	 * @param array $ldapRecords
815 815
 	 */
816
-	public function batchApplyUserAttributes(array $ldapRecords){
816
+	public function batchApplyUserAttributes(array $ldapRecords) {
817 817
 		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
818
-		foreach($ldapRecords as $userRecord) {
819
-			if(!isset($userRecord[$displayNameAttribute])) {
818
+		foreach ($ldapRecords as $userRecord) {
819
+			if (!isset($userRecord[$displayNameAttribute])) {
820 820
 				// displayName is obligatory
821 821
 				continue;
822 822
 			}
823
-			$ocName  = $this->dn2ocname($userRecord['dn'][0]);
824
-			if($ocName === false) {
823
+			$ocName = $this->dn2ocname($userRecord['dn'][0]);
824
+			if ($ocName === false) {
825 825
 				continue;
826 826
 			}
827 827
 			$this->cacheUserExists($ocName);
828 828
 			$user = $this->userManager->get($ocName);
829
-			if($user instanceof OfflineUser) {
829
+			if ($user instanceof OfflineUser) {
830 830
 				$user->unmark();
831 831
 				$user = $this->userManager->get($ocName);
832 832
 			}
@@ -858,8 +858,8 @@  discard block
 block discarded – undo
858 858
 	 * @return array
859 859
 	 */
860 860
 	private function fetchList($list, $manyAttributes) {
861
-		if(is_array($list)) {
862
-			if($manyAttributes) {
861
+		if (is_array($list)) {
862
+			if ($manyAttributes) {
863 863
 				return $list;
864 864
 			} else {
865 865
 				$list = array_reduce($list, function($carry, $item) {
@@ -945,13 +945,13 @@  discard block
 block discarded – undo
945 945
 	 * second | false if not successful
946 946
 	 */
947 947
 	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
948
-		if(!is_null($attr) && !is_array($attr)) {
948
+		if (!is_null($attr) && !is_array($attr)) {
949 949
 			$attr = array(mb_strtolower($attr, 'UTF-8'));
950 950
 		}
951 951
 
952 952
 		// See if we have a resource, in case not cancel with message
953 953
 		$cr = $this->connection->getConnectionResource();
954
-		if(!$this->ldap->isResource($cr)) {
954
+		if (!$this->ldap->isResource($cr)) {
955 955
 			// Seems like we didn't find any resource.
956 956
 			// Return an empty array just like before.
957 957
 			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
@@ -964,7 +964,7 @@  discard block
 block discarded – undo
964 964
 		$linkResources = array_pad(array(), count($base), $cr);
965 965
 		$sr = $this->ldap->search($linkResources, $base, $filter, $attr);
966 966
 		$error = $this->ldap->errno($cr);
967
-		if(!is_array($sr) || $error !== 0) {
967
+		if (!is_array($sr) || $error !== 0) {
968 968
 			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
969 969
 			return false;
970 970
 		}
@@ -987,26 +987,26 @@  discard block
 block discarded – undo
987 987
 	 */
988 988
 	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
989 989
 		$cookie = null;
990
-		if($pagedSearchOK) {
990
+		if ($pagedSearchOK) {
991 991
 			$cr = $this->connection->getConnectionResource();
992
-			foreach($sr as $key => $res) {
993
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
992
+			foreach ($sr as $key => $res) {
993
+				if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
994 994
 					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
995 995
 				}
996 996
 			}
997 997
 
998 998
 			//browsing through prior pages to get the cookie for the new one
999
-			if($skipHandling) {
999
+			if ($skipHandling) {
1000 1000
 				return false;
1001 1001
 			}
1002 1002
 			// if count is bigger, then the server does not support
1003 1003
 			// paged search. Instead, he did a normal search. We set a
1004 1004
 			// flag here, so the callee knows how to deal with it.
1005
-			if($iFoundItems <= $limit) {
1005
+			if ($iFoundItems <= $limit) {
1006 1006
 				$this->pagedSearchedSuccessful = true;
1007 1007
 			}
1008 1008
 		} else {
1009
-			if(!is_null($limit)) {
1009
+			if (!is_null($limit)) {
1010 1010
 				\OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1011 1011
 			}
1012 1012
 		}
@@ -1035,7 +1035,7 @@  discard block
 block discarded – undo
1035 1035
 		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1036 1036
 
1037 1037
 		$limitPerPage = intval($this->connection->ldapPagingSize);
1038
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1038
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1039 1039
 			$limitPerPage = $limit;
1040 1040
 		}
1041 1041
 
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
 		do {
1047 1047
 			$search = $this->executeSearch($filter, $base, $attr,
1048 1048
 										   $limitPerPage, $offset);
1049
-			if($search === false) {
1049
+			if ($search === false) {
1050 1050
 				return $counter > 0 ? $counter : false;
1051 1051
 			}
1052 1052
 			list($sr, $pagedSearchOK) = $search;
@@ -1065,7 +1065,7 @@  discard block
 block discarded – undo
1065 1065
 			 * Continue now depends on $hasMorePages value
1066 1066
 			 */
1067 1067
 			$continue = $pagedSearchOK && $hasMorePages;
1068
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1068
+		} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1069 1069
 
1070 1070
 		return $counter;
1071 1071
 	}
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
 		$cr = $this->connection->getConnectionResource();
1079 1079
 		$counter = 0;
1080 1080
 
1081
-		foreach($searchResults as $res) {
1081
+		foreach ($searchResults as $res) {
1082 1082
 			$count = intval($this->ldap->countEntries($cr, $res));
1083 1083
 			$counter += $count;
1084 1084
 		}
@@ -1097,7 +1097,7 @@  discard block
 block discarded – undo
1097 1097
 	 * @return array with the search result
1098 1098
 	 */
1099 1099
 	private function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1100
-		if($limit <= 0) {
1100
+		if ($limit <= 0) {
1101 1101
 			//otherwise search will fail
1102 1102
 			$limit = null;
1103 1103
 		}
@@ -1112,13 +1112,13 @@  discard block
 block discarded – undo
1112 1112
 		$savedoffset = $offset;
1113 1113
 		do {
1114 1114
 			$search = $this->executeSearch($filter, $base, $attr, $limit, $offset);
1115
-			if($search === false) {
1115
+			if ($search === false) {
1116 1116
 				return array();
1117 1117
 			}
1118 1118
 			list($sr, $pagedSearchOK) = $search;
1119 1119
 			$cr = $this->connection->getConnectionResource();
1120 1120
 
1121
-			if($skipHandling) {
1121
+			if ($skipHandling) {
1122 1122
 				//i.e. result do not need to be fetched, we just need the cookie
1123 1123
 				//thus pass 1 or any other value as $iFoundItems because it is not
1124 1124
 				//used
@@ -1128,8 +1128,8 @@  discard block
 block discarded – undo
1128 1128
 				return array();
1129 1129
 			}
1130 1130
 
1131
-			foreach($sr as $res) {
1132
-				$findings = array_merge($findings, $this->ldap->getEntries($cr	, $res ));
1131
+			foreach ($sr as $res) {
1132
+				$findings = array_merge($findings, $this->ldap->getEntries($cr, $res));
1133 1133
 			}
1134 1134
 
1135 1135
 			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $findings['count'],
@@ -1142,25 +1142,25 @@  discard block
 block discarded – undo
1142 1142
 
1143 1143
 		// if we're here, probably no connection resource is returned.
1144 1144
 		// to make ownCloud behave nicely, we simply give back an empty array.
1145
-		if(is_null($findings)) {
1145
+		if (is_null($findings)) {
1146 1146
 			return array();
1147 1147
 		}
1148 1148
 
1149
-		if(!is_null($attr)) {
1149
+		if (!is_null($attr)) {
1150 1150
 			$selection = array();
1151 1151
 			$i = 0;
1152
-			foreach($findings as $item) {
1153
-				if(!is_array($item)) {
1152
+			foreach ($findings as $item) {
1153
+				if (!is_array($item)) {
1154 1154
 					continue;
1155 1155
 				}
1156 1156
 				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1157
-				foreach($attr as $key) {
1157
+				foreach ($attr as $key) {
1158 1158
 					$key = mb_strtolower($key, 'UTF-8');
1159
-					if(isset($item[$key])) {
1160
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1159
+					if (isset($item[$key])) {
1160
+						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1161 1161
 							unset($item[$key]['count']);
1162 1162
 						}
1163
-						if($key !== 'dn') {
1163
+						if ($key !== 'dn') {
1164 1164
 							$selection[$i][$key] = $this->resemblesDN($key) ?
1165 1165
 								$this->helper->sanitizeDN($item[$key])
1166 1166
 								: $item[$key];
@@ -1177,7 +1177,7 @@  discard block
 block discarded – undo
1177 1177
 		//we slice the findings, when
1178 1178
 		//a) paged search unsuccessful, though attempted
1179 1179
 		//b) no paged search, but limit set
1180
-		if((!$this->getPagedSearchResultState()
1180
+		if ((!$this->getPagedSearchResultState()
1181 1181
 			&& $pagedSearchOK)
1182 1182
 			|| (
1183 1183
 				!$pagedSearchOK
@@ -1194,7 +1194,7 @@  discard block
 block discarded – undo
1194 1194
 	 * @return bool|mixed|string
1195 1195
 	 */
1196 1196
 	public function sanitizeUsername($name) {
1197
-		if($this->connection->ldapIgnoreNamingRules) {
1197
+		if ($this->connection->ldapIgnoreNamingRules) {
1198 1198
 			return $name;
1199 1199
 		}
1200 1200
 
@@ -1219,13 +1219,13 @@  discard block
 block discarded – undo
1219 1219
 	*/
1220 1220
 	public function escapeFilterPart($input, $allowAsterisk = false) {
1221 1221
 		$asterisk = '';
1222
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1222
+		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1223 1223
 			$asterisk = '*';
1224 1224
 			$input = mb_substr($input, 1, null, 'UTF-8');
1225 1225
 		}
1226 1226
 		$search  = array('*', '\\', '(', ')');
1227 1227
 		$replace = array('\\*', '\\\\', '\\(', '\\)');
1228
-		return $asterisk . str_replace($search, $replace, $input);
1228
+		return $asterisk.str_replace($search, $replace, $input);
1229 1229
 	}
1230 1230
 
1231 1231
 	/**
@@ -1255,13 +1255,13 @@  discard block
 block discarded – undo
1255 1255
 	 */
1256 1256
 	private function combineFilter($filters, $operator) {
1257 1257
 		$combinedFilter = '('.$operator;
1258
-		foreach($filters as $filter) {
1258
+		foreach ($filters as $filter) {
1259 1259
 			if ($filter !== '' && $filter[0] !== '(') {
1260 1260
 				$filter = '('.$filter.')';
1261 1261
 			}
1262
-			$combinedFilter.=$filter;
1262
+			$combinedFilter .= $filter;
1263 1263
 		}
1264
-		$combinedFilter.=')';
1264
+		$combinedFilter .= ')';
1265 1265
 		return $combinedFilter;
1266 1266
 	}
1267 1267
 
@@ -1297,17 +1297,17 @@  discard block
 block discarded – undo
1297 1297
 	 * @throws \Exception
1298 1298
 	 */
1299 1299
 	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1300
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1300
+		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1301 1301
 			throw new \Exception('searchAttributes must be an array with at least two string');
1302 1302
 		}
1303 1303
 		$searchWords = explode(' ', trim($search));
1304 1304
 		$wordFilters = array();
1305
-		foreach($searchWords as $word) {
1305
+		foreach ($searchWords as $word) {
1306 1306
 			$word = $this->prepareSearchTerm($word);
1307 1307
 			//every word needs to appear at least once
1308 1308
 			$wordMatchOneAttrFilters = array();
1309
-			foreach($searchAttributes as $attr) {
1310
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1309
+			foreach ($searchAttributes as $attr) {
1310
+				$wordMatchOneAttrFilters[] = $attr.'='.$word;
1311 1311
 			}
1312 1312
 			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1313 1313
 		}
@@ -1325,10 +1325,10 @@  discard block
 block discarded – undo
1325 1325
 	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1326 1326
 		$filter = array();
1327 1327
 		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1328
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1328
+		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1329 1329
 			try {
1330 1330
 				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1331
-			} catch(\Exception $e) {
1331
+			} catch (\Exception $e) {
1332 1332
 				\OCP\Util::writeLog(
1333 1333
 					'user_ldap',
1334 1334
 					'Creating advanced filter for search failed, falling back to simple method.',
@@ -1338,17 +1338,17 @@  discard block
 block discarded – undo
1338 1338
 		}
1339 1339
 
1340 1340
 		$search = $this->prepareSearchTerm($search);
1341
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1341
+		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1342 1342
 			if ($fallbackAttribute === '') {
1343 1343
 				return '';
1344 1344
 			}
1345
-			$filter[] = $fallbackAttribute . '=' . $search;
1345
+			$filter[] = $fallbackAttribute.'='.$search;
1346 1346
 		} else {
1347
-			foreach($searchAttributes as $attribute) {
1348
-				$filter[] = $attribute . '=' . $search;
1347
+			foreach ($searchAttributes as $attribute) {
1348
+				$filter[] = $attribute.'='.$search;
1349 1349
 			}
1350 1350
 		}
1351
-		if(count($filter) === 1) {
1351
+		if (count($filter) === 1) {
1352 1352
 			return '('.$filter[0].')';
1353 1353
 		}
1354 1354
 		return $this->combineFilterWithOr($filter);
@@ -1369,7 +1369,7 @@  discard block
 block discarded – undo
1369 1369
 		if ($term === '') {
1370 1370
 			$result = '*';
1371 1371
 		} else if ($allowEnum !== 'no') {
1372
-			$result = $term . '*';
1372
+			$result = $term.'*';
1373 1373
 		}
1374 1374
 		return $result;
1375 1375
 	}
@@ -1381,7 +1381,7 @@  discard block
 block discarded – undo
1381 1381
 	public function getFilterForUserCount() {
1382 1382
 		$filter = $this->combineFilterWithAnd(array(
1383 1383
 			$this->connection->ldapUserFilter,
1384
-			$this->connection->ldapUserDisplayName . '=*'
1384
+			$this->connection->ldapUserDisplayName.'=*'
1385 1385
 		));
1386 1386
 
1387 1387
 		return $filter;
@@ -1399,7 +1399,7 @@  discard block
 block discarded – undo
1399 1399
 			'ldapAgentName' => $name,
1400 1400
 			'ldapAgentPassword' => $password
1401 1401
 		);
1402
-		if(!$testConnection->setConfiguration($credentials)) {
1402
+		if (!$testConnection->setConfiguration($credentials)) {
1403 1403
 			return false;
1404 1404
 		}
1405 1405
 		return $testConnection->bind();
@@ -1421,30 +1421,30 @@  discard block
 block discarded – undo
1421 1421
 			// Sacrebleu! The UUID attribute is unknown :( We need first an
1422 1422
 			// existing DN to be able to reliably detect it.
1423 1423
 			$result = $this->search($filter, $base, ['dn'], 1);
1424
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1424
+			if (!isset($result[0]) || !isset($result[0]['dn'])) {
1425 1425
 				throw new \Exception('Cannot determine UUID attribute');
1426 1426
 			}
1427 1427
 			$dn = $result[0]['dn'][0];
1428
-			if(!$this->detectUuidAttribute($dn, true)) {
1428
+			if (!$this->detectUuidAttribute($dn, true)) {
1429 1429
 				throw new \Exception('Cannot determine UUID attribute');
1430 1430
 			}
1431 1431
 		} else {
1432 1432
 			// The UUID attribute is either known or an override is given.
1433 1433
 			// By calling this method we ensure that $this->connection->$uuidAttr
1434 1434
 			// is definitely set
1435
-			if(!$this->detectUuidAttribute('', true)) {
1435
+			if (!$this->detectUuidAttribute('', true)) {
1436 1436
 				throw new \Exception('Cannot determine UUID attribute');
1437 1437
 			}
1438 1438
 		}
1439 1439
 
1440 1440
 		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1441
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1441
+		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1442 1442
 			$uuid = $this->formatGuid2ForFilterUser($uuid);
1443 1443
 		}
1444 1444
 
1445
-		$filter = $uuidAttr . '=' . $uuid;
1445
+		$filter = $uuidAttr.'='.$uuid;
1446 1446
 		$result = $this->searchUsers($filter, ['dn'], 2);
1447
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1447
+		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1448 1448
 			// we put the count into account to make sure that this is
1449 1449
 			// really unique
1450 1450
 			return $result[0]['dn'][0];
@@ -1461,7 +1461,7 @@  discard block
 block discarded – undo
1461 1461
 	 * @return bool true on success, false otherwise
1462 1462
 	 */
1463 1463
 	private function detectUuidAttribute($dn, $isUser = true, $force = false) {
1464
-		if($isUser) {
1464
+		if ($isUser) {
1465 1465
 			$uuidAttr     = 'ldapUuidUserAttribute';
1466 1466
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1467 1467
 		} else {
@@ -1469,7 +1469,7 @@  discard block
 block discarded – undo
1469 1469
 			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1470 1470
 		}
1471 1471
 
1472
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1472
+		if (($this->connection->$uuidAttr !== 'auto') && !$force) {
1473 1473
 			return true;
1474 1474
 		}
1475 1475
 
@@ -1481,9 +1481,9 @@  discard block
 block discarded – undo
1481 1481
 		// for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID
1482 1482
 		$testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid');
1483 1483
 
1484
-		foreach($testAttributes as $attribute) {
1484
+		foreach ($testAttributes as $attribute) {
1485 1485
 			$value = $this->readAttribute($dn, $attribute);
1486
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1486
+			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1487 1487
 				\OCP\Util::writeLog('user_ldap',
1488 1488
 									'Setting '.$attribute.' as '.$uuidAttr,
1489 1489
 									\OCP\Util::DEBUG);
@@ -1504,7 +1504,7 @@  discard block
 block discarded – undo
1504 1504
 	 * @return string|bool
1505 1505
 	 */
1506 1506
 	public function getUUID($dn, $isUser = true) {
1507
-		if($isUser) {
1507
+		if ($isUser) {
1508 1508
 			$uuidAttr     = 'ldapUuidUserAttribute';
1509 1509
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1510 1510
 		} else {
@@ -1513,15 +1513,15 @@  discard block
 block discarded – undo
1513 1513
 		}
1514 1514
 
1515 1515
 		$uuid = false;
1516
-		if($this->detectUuidAttribute($dn, $isUser)) {
1516
+		if ($this->detectUuidAttribute($dn, $isUser)) {
1517 1517
 			$uuid = $this->readAttribute($dn, $this->connection->$uuidAttr);
1518
-			if( !is_array($uuid)
1518
+			if (!is_array($uuid)
1519 1519
 				&& $uuidOverride !== ''
1520 1520
 				&& $this->detectUuidAttribute($dn, $isUser, true)) {
1521 1521
 					$uuid = $this->readAttribute($dn,
1522 1522
 												 $this->connection->$uuidAttr);
1523 1523
 			}
1524
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1524
+			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1525 1525
 				$uuid = $uuid[0];
1526 1526
 			}
1527 1527
 		}
@@ -1538,19 +1538,19 @@  discard block
 block discarded – undo
1538 1538
 	private function convertObjectGUID2Str($oguid) {
1539 1539
 		$hex_guid = bin2hex($oguid);
1540 1540
 		$hex_guid_to_guid_str = '';
1541
-		for($k = 1; $k <= 4; ++$k) {
1541
+		for ($k = 1; $k <= 4; ++$k) {
1542 1542
 			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1543 1543
 		}
1544 1544
 		$hex_guid_to_guid_str .= '-';
1545
-		for($k = 1; $k <= 2; ++$k) {
1545
+		for ($k = 1; $k <= 2; ++$k) {
1546 1546
 			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1547 1547
 		}
1548 1548
 		$hex_guid_to_guid_str .= '-';
1549
-		for($k = 1; $k <= 2; ++$k) {
1549
+		for ($k = 1; $k <= 2; ++$k) {
1550 1550
 			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1551 1551
 		}
1552
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1553
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1552
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 16, 4);
1553
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 20);
1554 1554
 
1555 1555
 		return strtoupper($hex_guid_to_guid_str);
1556 1556
 	}
@@ -1567,11 +1567,11 @@  discard block
 block discarded – undo
1567 1567
 	 * @return string
1568 1568
 	 */
1569 1569
 	public function formatGuid2ForFilterUser($guid) {
1570
-		if(!is_string($guid)) {
1570
+		if (!is_string($guid)) {
1571 1571
 			throw new \InvalidArgumentException('String expected');
1572 1572
 		}
1573 1573
 		$blocks = explode('-', $guid);
1574
-		if(count($blocks) !== 5) {
1574
+		if (count($blocks) !== 5) {
1575 1575
 			/*
1576 1576
 			 * Why not throw an Exception instead? This method is a utility
1577 1577
 			 * called only when trying to figure out whether a "missing" known
@@ -1584,20 +1584,20 @@  discard block
 block discarded – undo
1584 1584
 			 * user. Instead we write a log message.
1585 1585
 			 */
1586 1586
 			\OC::$server->getLogger()->info(
1587
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1587
+				'Passed string does not resemble a valid GUID. Known UUID '.
1588 1588
 				'({uuid}) probably does not match UUID configuration.',
1589
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1589
+				['app' => 'user_ldap', 'uuid' => $guid]
1590 1590
 			);
1591 1591
 			return $guid;
1592 1592
 		}
1593
-		for($i=0; $i < 3; $i++) {
1593
+		for ($i = 0; $i < 3; $i++) {
1594 1594
 			$pairs = str_split($blocks[$i], 2);
1595 1595
 			$pairs = array_reverse($pairs);
1596 1596
 			$blocks[$i] = implode('', $pairs);
1597 1597
 		}
1598
-		for($i=0; $i < 5; $i++) {
1598
+		for ($i = 0; $i < 5; $i++) {
1599 1599
 			$pairs = str_split($blocks[$i], 2);
1600
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1600
+			$blocks[$i] = '\\'.implode('\\', $pairs);
1601 1601
 		}
1602 1602
 		return implode('', $blocks);
1603 1603
 	}
@@ -1611,12 +1611,12 @@  discard block
 block discarded – undo
1611 1611
 		$domainDN = $this->getDomainDNFromDN($dn);
1612 1612
 		$cacheKey = 'getSID-'.$domainDN;
1613 1613
 		$sid = $this->connection->getFromCache($cacheKey);
1614
-		if(!is_null($sid)) {
1614
+		if (!is_null($sid)) {
1615 1615
 			return $sid;
1616 1616
 		}
1617 1617
 
1618 1618
 		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1619
-		if(!is_array($objectSid) || empty($objectSid)) {
1619
+		if (!is_array($objectSid) || empty($objectSid)) {
1620 1620
 			$this->connection->writeToCache($cacheKey, false);
1621 1621
 			return false;
1622 1622
 		}
@@ -1674,12 +1674,12 @@  discard block
 block discarded – undo
1674 1674
 		$belongsToBase = false;
1675 1675
 		$bases = $this->helper->sanitizeDN($bases);
1676 1676
 
1677
-		foreach($bases as $base) {
1677
+		foreach ($bases as $base) {
1678 1678
 			$belongsToBase = true;
1679
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1679
+			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1680 1680
 				$belongsToBase = false;
1681 1681
 			}
1682
-			if($belongsToBase) {
1682
+			if ($belongsToBase) {
1683 1683
 				break;
1684 1684
 			}
1685 1685
 		}
@@ -1690,7 +1690,7 @@  discard block
 block discarded – undo
1690 1690
 	 * resets a running Paged Search operation
1691 1691
 	 */
1692 1692
 	private function abandonPagedSearch() {
1693
-		if($this->connection->hasPagedResultSupport) {
1693
+		if ($this->connection->hasPagedResultSupport) {
1694 1694
 			$cr = $this->connection->getConnectionResource();
1695 1695
 			$this->ldap->controlPagedResult($cr, 0, false, $this->lastCookie);
1696 1696
 			$this->getPagedSearchResultState();
@@ -1708,16 +1708,16 @@  discard block
 block discarded – undo
1708 1708
 	 * @return string containing the key or empty if none is cached
1709 1709
 	 */
1710 1710
 	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1711
-		if($offset === 0) {
1711
+		if ($offset === 0) {
1712 1712
 			return '';
1713 1713
 		}
1714 1714
 		$offset -= $limit;
1715 1715
 		//we work with cache here
1716
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1716
+		$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1717 1717
 		$cookie = '';
1718
-		if(isset($this->cookies[$cacheKey])) {
1718
+		if (isset($this->cookies[$cacheKey])) {
1719 1719
 			$cookie = $this->cookies[$cacheKey];
1720
-			if(is_null($cookie)) {
1720
+			if (is_null($cookie)) {
1721 1721
 				$cookie = '';
1722 1722
 			}
1723 1723
 		}
@@ -1735,11 +1735,11 @@  discard block
 block discarded – undo
1735 1735
 	 * @return bool
1736 1736
 	 */
1737 1737
 	public function hasMoreResults() {
1738
-		if(!$this->connection->hasPagedResultSupport) {
1738
+		if (!$this->connection->hasPagedResultSupport) {
1739 1739
 			return false;
1740 1740
 		}
1741 1741
 
1742
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1742
+		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1743 1743
 			// as in RFC 2696, when all results are returned, the cookie will
1744 1744
 			// be empty.
1745 1745
 			return false;
@@ -1759,8 +1759,8 @@  discard block
 block discarded – undo
1759 1759
 	 */
1760 1760
 	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1761 1761
 		// allow '0' for 389ds
1762
-		if(!empty($cookie) || $cookie === '0') {
1763
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1762
+		if (!empty($cookie) || $cookie === '0') {
1763
+			$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1764 1764
 			$this->cookies[$cacheKey] = $cookie;
1765 1765
 			$this->lastCookie = $cookie;
1766 1766
 		}
@@ -1787,17 +1787,17 @@  discard block
 block discarded – undo
1787 1787
 	 */
1788 1788
 	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1789 1789
 		$pagedSearchOK = false;
1790
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1790
+		if ($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1791 1791
 			$offset = intval($offset); //can be null
1792 1792
 			\OCP\Util::writeLog('user_ldap',
1793 1793
 				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1794
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1794
+				.' attr '.print_r($attr, true).' limit '.$limit.' offset '.$offset,
1795 1795
 				\OCP\Util::DEBUG);
1796 1796
 			//get the cookie from the search for the previous search, required by LDAP
1797
-			foreach($bases as $base) {
1797
+			foreach ($bases as $base) {
1798 1798
 
1799 1799
 				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1800
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1800
+				if (empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1801 1801
 					// no cookie known, although the offset is not 0. Maybe cache run out. We need
1802 1802
 					// to start all over *sigh* (btw, Dear Reader, did you know LDAP paged
1803 1803
 					// searching was designed by MSFT?)
@@ -1810,18 +1810,18 @@  discard block
 block discarded – undo
1810 1810
 					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1811 1811
 					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1812 1812
 					//TODO: remember this, probably does not change in the next request...
1813
-					if(empty($cookie) && $cookie !== '0') {
1813
+					if (empty($cookie) && $cookie !== '0') {
1814 1814
 						// '0' is valid, because 389ds
1815 1815
 						$cookie = null;
1816 1816
 					}
1817 1817
 				}
1818
-				if(!is_null($cookie)) {
1818
+				if (!is_null($cookie)) {
1819 1819
 					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1820 1820
 					$this->abandonPagedSearch();
1821 1821
 					$pagedSearchOK = $this->ldap->controlPagedResult(
1822 1822
 						$this->connection->getConnectionResource(), $limit,
1823 1823
 						false, $cookie);
1824
-					if(!$pagedSearchOK) {
1824
+					if (!$pagedSearchOK) {
1825 1825
 						return false;
1826 1826
 					}
1827 1827
 					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1839 1839
 		 * if we don't have a previous paged search.
1840 1840
 		 */
1841
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1841
+		} else if ($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1842 1842
 			// a search without limit was requested. However, if we do use
1843 1843
 			// Paged Search once, we always must do it. This requires us to
1844 1844
 			// initialize it with the configured page size.
Please login to merge, or discard this patch.
apps/user_ldap/appinfo/app.php 2 patches
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -32,44 +32,44 @@
 block discarded – undo
32 32
 $ldapWrapper = new OCA\User_LDAP\LDAP();
33 33
 $ocConfig = \OC::$server->getConfig();
34 34
 if(count($configPrefixes) === 1) {
35
-	$dbc = \OC::$server->getDatabaseConnection();
36
-	$userManager = new OCA\User_LDAP\User\Manager($ocConfig,
37
-		new OCA\User_LDAP\FilesystemHelper(),
38
-		new OCA\User_LDAP\LogWrapper(),
39
-		\OC::$server->getAvatarManager(),
40
-		new \OCP\Image(),
41
-		$dbc,
42
-		\OC::$server->getUserManager()
43
-	);
44
-	$connector = new OCA\User_LDAP\Connection($ldapWrapper, $configPrefixes[0]);
45
-	$ldapAccess = new OCA\User_LDAP\Access($connector, $ldapWrapper, $userManager, $helper);
35
+    $dbc = \OC::$server->getDatabaseConnection();
36
+    $userManager = new OCA\User_LDAP\User\Manager($ocConfig,
37
+        new OCA\User_LDAP\FilesystemHelper(),
38
+        new OCA\User_LDAP\LogWrapper(),
39
+        \OC::$server->getAvatarManager(),
40
+        new \OCP\Image(),
41
+        $dbc,
42
+        \OC::$server->getUserManager()
43
+    );
44
+    $connector = new OCA\User_LDAP\Connection($ldapWrapper, $configPrefixes[0]);
45
+    $ldapAccess = new OCA\User_LDAP\Access($connector, $ldapWrapper, $userManager, $helper);
46 46
 
47
-	$ldapAccess->setUserMapper(new OCA\User_LDAP\Mapping\UserMapping($dbc));
48
-	$ldapAccess->setGroupMapper(new OCA\User_LDAP\Mapping\GroupMapping($dbc));
49
-	$userBackend  = new OCA\User_LDAP\User_LDAP($ldapAccess, $ocConfig);
50
-	$groupBackend = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
47
+    $ldapAccess->setUserMapper(new OCA\User_LDAP\Mapping\UserMapping($dbc));
48
+    $ldapAccess->setGroupMapper(new OCA\User_LDAP\Mapping\GroupMapping($dbc));
49
+    $userBackend  = new OCA\User_LDAP\User_LDAP($ldapAccess, $ocConfig);
50
+    $groupBackend = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
51 51
 } else if(count($configPrefixes) > 1) {
52
-	$userBackend  = new OCA\User_LDAP\User_Proxy(
53
-		$configPrefixes, $ldapWrapper, $ocConfig
54
-	);
55
-	$groupBackend  = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
52
+    $userBackend  = new OCA\User_LDAP\User_Proxy(
53
+        $configPrefixes, $ldapWrapper, $ocConfig
54
+    );
55
+    $groupBackend  = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
56 56
 }
57 57
 
58 58
 if(count($configPrefixes) > 0) {
59
-	// register user backend
60
-	OC_User::useBackend($userBackend);
61
-	\OC::$server->getGroupManager()->addBackend($groupBackend);
59
+    // register user backend
60
+    OC_User::useBackend($userBackend);
61
+    \OC::$server->getGroupManager()->addBackend($groupBackend);
62 62
 }
63 63
 
64 64
 \OCP\Util::connectHook(
65
-	'\OCA\Files_Sharing\API\Server2Server',
66
-	'preLoginNameUsedAsUserName',
67
-	'\OCA\User_LDAP\Helper',
68
-	'loginName2UserName'
65
+    '\OCA\Files_Sharing\API\Server2Server',
66
+    'preLoginNameUsedAsUserName',
67
+    '\OCA\User_LDAP\Helper',
68
+    'loginName2UserName'
69 69
 );
70 70
 
71 71
 if(OCP\App::isEnabled('user_webdavauth')) {
72
-	OCP\Util::writeLog('user_ldap',
73
-		'user_ldap and user_webdavauth are incompatible. You may experience unexpected behaviour',
74
-		OCP\Util::WARN);
72
+    OCP\Util::writeLog('user_ldap',
73
+        'user_ldap and user_webdavauth are incompatible. You may experience unexpected behaviour',
74
+        OCP\Util::WARN);
75 75
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 $configPrefixes = $helper->getServerConfigurationPrefixes(true);
32 32
 $ldapWrapper = new OCA\User_LDAP\LDAP();
33 33
 $ocConfig = \OC::$server->getConfig();
34
-if(count($configPrefixes) === 1) {
34
+if (count($configPrefixes) === 1) {
35 35
 	$dbc = \OC::$server->getDatabaseConnection();
36 36
 	$userManager = new OCA\User_LDAP\User\Manager($ocConfig,
37 37
 		new OCA\User_LDAP\FilesystemHelper(),
@@ -48,14 +48,14 @@  discard block
 block discarded – undo
48 48
 	$ldapAccess->setGroupMapper(new OCA\User_LDAP\Mapping\GroupMapping($dbc));
49 49
 	$userBackend  = new OCA\User_LDAP\User_LDAP($ldapAccess, $ocConfig);
50 50
 	$groupBackend = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
51
-} else if(count($configPrefixes) > 1) {
51
+} else if (count($configPrefixes) > 1) {
52 52
 	$userBackend  = new OCA\User_LDAP\User_Proxy(
53 53
 		$configPrefixes, $ldapWrapper, $ocConfig
54 54
 	);
55
-	$groupBackend  = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
55
+	$groupBackend = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
56 56
 }
57 57
 
58
-if(count($configPrefixes) > 0) {
58
+if (count($configPrefixes) > 0) {
59 59
 	// register user backend
60 60
 	OC_User::useBackend($userBackend);
61 61
 	\OC::$server->getGroupManager()->addBackend($groupBackend);
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	'loginName2UserName'
69 69
 );
70 70
 
71
-if(OCP\App::isEnabled('user_webdavauth')) {
71
+if (OCP\App::isEnabled('user_webdavauth')) {
72 72
 	OCP\Util::writeLog('user_ldap',
73 73
 		'user_ldap and user_webdavauth are incompatible. You may experience unexpected behaviour',
74 74
 		OCP\Util::WARN);
Please login to merge, or discard this patch.
lib/private/Encryption/Util.php 1 patch
Indentation   +365 added lines, -365 removed lines patch added patch discarded remove patch
@@ -36,370 +36,370 @@
 block discarded – undo
36 36
 
37 37
 class Util {
38 38
 
39
-	const HEADER_START = 'HBEGIN';
40
-	const HEADER_END = 'HEND';
41
-	const HEADER_PADDING_CHAR = '-';
42
-
43
-	const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
44
-
45
-	/**
46
-	 * block size will always be 8192 for a PHP stream
47
-	 * @see https://bugs.php.net/bug.php?id=21641
48
-	 * @var integer
49
-	 */
50
-	protected $headerSize = 8192;
51
-
52
-	/**
53
-	 * block size will always be 8192 for a PHP stream
54
-	 * @see https://bugs.php.net/bug.php?id=21641
55
-	 * @var integer
56
-	 */
57
-	protected $blockSize = 8192;
58
-
59
-	/** @var View */
60
-	protected $rootView;
61
-
62
-	/** @var array */
63
-	protected $ocHeaderKeys;
64
-
65
-	/** @var \OC\User\Manager */
66
-	protected $userManager;
67
-
68
-	/** @var IConfig */
69
-	protected $config;
70
-
71
-	/** @var array paths excluded from encryption */
72
-	protected $excludedPaths;
73
-
74
-	/** @var \OC\Group\Manager $manager */
75
-	protected $groupManager;
76
-
77
-	/**
78
-	 *
79
-	 * @param View $rootView
80
-	 * @param \OC\User\Manager $userManager
81
-	 * @param \OC\Group\Manager $groupManager
82
-	 * @param IConfig $config
83
-	 */
84
-	public function __construct(
85
-		View $rootView,
86
-		\OC\User\Manager $userManager,
87
-		\OC\Group\Manager $groupManager,
88
-		IConfig $config) {
89
-
90
-		$this->ocHeaderKeys = [
91
-			self::HEADER_ENCRYPTION_MODULE_KEY
92
-		];
93
-
94
-		$this->rootView = $rootView;
95
-		$this->userManager = $userManager;
96
-		$this->groupManager = $groupManager;
97
-		$this->config = $config;
98
-
99
-		$this->excludedPaths[] = 'files_encryption';
100
-		$this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null);
101
-	}
102
-
103
-	/**
104
-	 * read encryption module ID from header
105
-	 *
106
-	 * @param array $header
107
-	 * @return string
108
-	 * @throws ModuleDoesNotExistsException
109
-	 */
110
-	public function getEncryptionModuleId(array $header = null) {
111
-		$id = '';
112
-		$encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
113
-
114
-		if (isset($header[$encryptionModuleKey])) {
115
-			$id = $header[$encryptionModuleKey];
116
-		} elseif (isset($header['cipher'])) {
117
-			if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
118
-				// fall back to default encryption if the user migrated from
119
-				// ownCloud <= 8.0 with the old encryption
120
-				$id = \OCA\Encryption\Crypto\Encryption::ID;
121
-			} else {
122
-				throw new ModuleDoesNotExistsException('Default encryption module missing');
123
-			}
124
-		}
125
-
126
-		return $id;
127
-	}
128
-
129
-	/**
130
-	 * create header for encrypted file
131
-	 *
132
-	 * @param array $headerData
133
-	 * @param IEncryptionModule $encryptionModule
134
-	 * @return string
135
-	 * @throws EncryptionHeaderToLargeException if header has to many arguments
136
-	 * @throws EncryptionHeaderKeyExistsException if header key is already in use
137
-	 */
138
-	public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
139
-		$header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
140
-		foreach ($headerData as $key => $value) {
141
-			if (in_array($key, $this->ocHeaderKeys)) {
142
-				throw new EncryptionHeaderKeyExistsException($key);
143
-			}
144
-			$header .= $key . ':' . $value . ':';
145
-		}
146
-		$header .= self::HEADER_END;
147
-
148
-		if (strlen($header) > $this->getHeaderSize()) {
149
-			throw new EncryptionHeaderToLargeException();
150
-		}
151
-
152
-		$paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
153
-
154
-		return $paddedHeader;
155
-	}
156
-
157
-	/**
158
-	 * go recursively through a dir and collect all files and sub files.
159
-	 *
160
-	 * @param string $dir relative to the users files folder
161
-	 * @return array with list of files relative to the users files folder
162
-	 */
163
-	public function getAllFiles($dir) {
164
-		$result = array();
165
-		$dirList = array($dir);
166
-
167
-		while ($dirList) {
168
-			$dir = array_pop($dirList);
169
-			$content = $this->rootView->getDirectoryContent($dir);
170
-
171
-			foreach ($content as $c) {
172
-				if ($c->getType() === 'dir') {
173
-					$dirList[] = $c->getPath();
174
-				} else {
175
-					$result[] =  $c->getPath();
176
-				}
177
-			}
178
-
179
-		}
180
-
181
-		return $result;
182
-	}
183
-
184
-	/**
185
-	 * check if it is a file uploaded by the user stored in data/user/files
186
-	 * or a metadata file
187
-	 *
188
-	 * @param string $path relative to the data/ folder
189
-	 * @return boolean
190
-	 */
191
-	public function isFile($path) {
192
-		$parts = explode('/', Filesystem::normalizePath($path), 4);
193
-		if (isset($parts[2]) && $parts[2] === 'files') {
194
-			return true;
195
-		}
196
-		return false;
197
-	}
198
-
199
-	/**
200
-	 * return size of encryption header
201
-	 *
202
-	 * @return integer
203
-	 */
204
-	public function getHeaderSize() {
205
-		return $this->headerSize;
206
-	}
207
-
208
-	/**
209
-	 * return size of block read by a PHP stream
210
-	 *
211
-	 * @return integer
212
-	 */
213
-	public function getBlockSize() {
214
-		return $this->blockSize;
215
-	}
216
-
217
-	/**
218
-	 * get the owner and the path for the file relative to the owners files folder
219
-	 *
220
-	 * @param string $path
221
-	 * @return array
222
-	 * @throws \BadMethodCallException
223
-	 */
224
-	public function getUidAndFilename($path) {
225
-
226
-		$parts = explode('/', $path);
227
-		$uid = '';
228
-		if (count($parts) > 2) {
229
-			$uid = $parts[1];
230
-		}
231
-		if (!$this->userManager->userExists($uid)) {
232
-			throw new \BadMethodCallException(
233
-				'path needs to be relative to the system wide data folder and point to a user specific file'
234
-			);
235
-		}
236
-
237
-		$ownerPath = implode('/', array_slice($parts, 2));
238
-
239
-		return array($uid, Filesystem::normalizePath($ownerPath));
240
-
241
-	}
242
-
243
-	/**
244
-	 * Remove .path extension from a file path
245
-	 * @param string $path Path that may identify a .part file
246
-	 * @return string File path without .part extension
247
-	 * @note this is needed for reusing keys
248
-	 */
249
-	public function stripPartialFileExtension($path) {
250
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
251
-
252
-		if ( $extension === 'part') {
253
-
254
-			$newLength = strlen($path) - 5; // 5 = strlen(".part")
255
-			$fPath = substr($path, 0, $newLength);
256
-
257
-			// if path also contains a transaction id, we remove it too
258
-			$extension = pathinfo($fPath, PATHINFO_EXTENSION);
259
-			if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
260
-				$newLength = strlen($fPath) - strlen($extension) -1;
261
-				$fPath = substr($fPath, 0, $newLength);
262
-			}
263
-			return $fPath;
264
-
265
-		} else {
266
-			return $path;
267
-		}
268
-	}
269
-
270
-	public function getUserWithAccessToMountPoint($users, $groups) {
271
-		$result = array();
272
-		if (in_array('all', $users)) {
273
-			$result = \OCP\User::getUsers();
274
-		} else {
275
-			$result = array_merge($result, $users);
276
-
277
-			$groupManager = \OC::$server->getGroupManager();
278
-			foreach ($groups as $group) {
279
-				$groupObject = $groupManager->get($group);
280
-				if ($groupObject) {
281
-					$foundUsers = $groupObject->searchUsers('', -1, 0);
282
-					$userIds = [];
283
-					foreach ($foundUsers as $user) {
284
-						$userIds[] = $user->getUID();
285
-					}
286
-					$result = array_merge($result, $userIds);
287
-				}
288
-			}
289
-		}
290
-
291
-		return $result;
292
-	}
293
-
294
-	/**
295
-	 * check if the file is stored on a system wide mount point
296
-	 * @param string $path relative to /data/user with leading '/'
297
-	 * @param string $uid
298
-	 * @return boolean
299
-	 */
300
-	public function isSystemWideMountPoint($path, $uid) {
301
-		if (\OCP\App::isEnabled("files_external")) {
302
-			$mounts = \OC_Mount_Config::getSystemMountPoints();
303
-			foreach ($mounts as $mount) {
304
-				if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
305
-					if ($this->isMountPointApplicableToUser($mount, $uid)) {
306
-						return true;
307
-					}
308
-				}
309
-			}
310
-		}
311
-		return false;
312
-	}
313
-
314
-	/**
315
-	 * check if mount point is applicable to user
316
-	 *
317
-	 * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
318
-	 * @param string $uid
319
-	 * @return boolean
320
-	 */
321
-	private function isMountPointApplicableToUser($mount, $uid) {
322
-		$acceptedUids = array('all', $uid);
323
-		// check if mount point is applicable for the user
324
-		$intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
325
-		if (!empty($intersection)) {
326
-			return true;
327
-		}
328
-		// check if mount point is applicable for group where the user is a member
329
-		foreach ($mount['applicable']['groups'] as $gid) {
330
-			if ($this->groupManager->isInGroup($uid, $gid)) {
331
-				return true;
332
-			}
333
-		}
334
-		return false;
335
-	}
336
-
337
-	/**
338
-	 * check if it is a path which is excluded by ownCloud from encryption
339
-	 *
340
-	 * @param string $path
341
-	 * @return boolean
342
-	 */
343
-	public function isExcluded($path) {
344
-		$normalizedPath = Filesystem::normalizePath($path);
345
-		$root = explode('/', $normalizedPath, 4);
346
-		if (count($root) > 1) {
347
-
348
-			// detect alternative key storage root
349
-			$rootDir = $this->getKeyStorageRoot();
350
-			if ($rootDir !== '' &&
351
-				0 === strpos(
352
-					Filesystem::normalizePath($path),
353
-					Filesystem::normalizePath($rootDir)
354
-				)
355
-			) {
356
-				return true;
357
-			}
358
-
359
-
360
-			//detect system wide folders
361
-			if (in_array($root[1], $this->excludedPaths)) {
362
-				return true;
363
-			}
364
-
365
-			// detect user specific folders
366
-			if ($this->userManager->userExists($root[1])
367
-				&& in_array($root[2], $this->excludedPaths)) {
368
-
369
-				return true;
370
-			}
371
-		}
372
-		return false;
373
-	}
374
-
375
-	/**
376
-	 * check if recovery key is enabled for user
377
-	 *
378
-	 * @param string $uid
379
-	 * @return boolean
380
-	 */
381
-	public function recoveryEnabled($uid) {
382
-		$enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
383
-
384
-		return ($enabled === '1') ? true : false;
385
-	}
386
-
387
-	/**
388
-	 * set new key storage root
389
-	 *
390
-	 * @param string $root new key store root relative to the data folder
391
-	 */
392
-	public function setKeyStorageRoot($root) {
393
-		$this->config->setAppValue('core', 'encryption_key_storage_root', $root);
394
-	}
395
-
396
-	/**
397
-	 * get key storage root
398
-	 *
399
-	 * @return string key storage root
400
-	 */
401
-	public function getKeyStorageRoot() {
402
-		return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
403
-	}
39
+    const HEADER_START = 'HBEGIN';
40
+    const HEADER_END = 'HEND';
41
+    const HEADER_PADDING_CHAR = '-';
42
+
43
+    const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
44
+
45
+    /**
46
+     * block size will always be 8192 for a PHP stream
47
+     * @see https://bugs.php.net/bug.php?id=21641
48
+     * @var integer
49
+     */
50
+    protected $headerSize = 8192;
51
+
52
+    /**
53
+     * block size will always be 8192 for a PHP stream
54
+     * @see https://bugs.php.net/bug.php?id=21641
55
+     * @var integer
56
+     */
57
+    protected $blockSize = 8192;
58
+
59
+    /** @var View */
60
+    protected $rootView;
61
+
62
+    /** @var array */
63
+    protected $ocHeaderKeys;
64
+
65
+    /** @var \OC\User\Manager */
66
+    protected $userManager;
67
+
68
+    /** @var IConfig */
69
+    protected $config;
70
+
71
+    /** @var array paths excluded from encryption */
72
+    protected $excludedPaths;
73
+
74
+    /** @var \OC\Group\Manager $manager */
75
+    protected $groupManager;
76
+
77
+    /**
78
+     *
79
+     * @param View $rootView
80
+     * @param \OC\User\Manager $userManager
81
+     * @param \OC\Group\Manager $groupManager
82
+     * @param IConfig $config
83
+     */
84
+    public function __construct(
85
+        View $rootView,
86
+        \OC\User\Manager $userManager,
87
+        \OC\Group\Manager $groupManager,
88
+        IConfig $config) {
89
+
90
+        $this->ocHeaderKeys = [
91
+            self::HEADER_ENCRYPTION_MODULE_KEY
92
+        ];
93
+
94
+        $this->rootView = $rootView;
95
+        $this->userManager = $userManager;
96
+        $this->groupManager = $groupManager;
97
+        $this->config = $config;
98
+
99
+        $this->excludedPaths[] = 'files_encryption';
100
+        $this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null);
101
+    }
102
+
103
+    /**
104
+     * read encryption module ID from header
105
+     *
106
+     * @param array $header
107
+     * @return string
108
+     * @throws ModuleDoesNotExistsException
109
+     */
110
+    public function getEncryptionModuleId(array $header = null) {
111
+        $id = '';
112
+        $encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
113
+
114
+        if (isset($header[$encryptionModuleKey])) {
115
+            $id = $header[$encryptionModuleKey];
116
+        } elseif (isset($header['cipher'])) {
117
+            if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
118
+                // fall back to default encryption if the user migrated from
119
+                // ownCloud <= 8.0 with the old encryption
120
+                $id = \OCA\Encryption\Crypto\Encryption::ID;
121
+            } else {
122
+                throw new ModuleDoesNotExistsException('Default encryption module missing');
123
+            }
124
+        }
125
+
126
+        return $id;
127
+    }
128
+
129
+    /**
130
+     * create header for encrypted file
131
+     *
132
+     * @param array $headerData
133
+     * @param IEncryptionModule $encryptionModule
134
+     * @return string
135
+     * @throws EncryptionHeaderToLargeException if header has to many arguments
136
+     * @throws EncryptionHeaderKeyExistsException if header key is already in use
137
+     */
138
+    public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
139
+        $header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
140
+        foreach ($headerData as $key => $value) {
141
+            if (in_array($key, $this->ocHeaderKeys)) {
142
+                throw new EncryptionHeaderKeyExistsException($key);
143
+            }
144
+            $header .= $key . ':' . $value . ':';
145
+        }
146
+        $header .= self::HEADER_END;
147
+
148
+        if (strlen($header) > $this->getHeaderSize()) {
149
+            throw new EncryptionHeaderToLargeException();
150
+        }
151
+
152
+        $paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
153
+
154
+        return $paddedHeader;
155
+    }
156
+
157
+    /**
158
+     * go recursively through a dir and collect all files and sub files.
159
+     *
160
+     * @param string $dir relative to the users files folder
161
+     * @return array with list of files relative to the users files folder
162
+     */
163
+    public function getAllFiles($dir) {
164
+        $result = array();
165
+        $dirList = array($dir);
166
+
167
+        while ($dirList) {
168
+            $dir = array_pop($dirList);
169
+            $content = $this->rootView->getDirectoryContent($dir);
170
+
171
+            foreach ($content as $c) {
172
+                if ($c->getType() === 'dir') {
173
+                    $dirList[] = $c->getPath();
174
+                } else {
175
+                    $result[] =  $c->getPath();
176
+                }
177
+            }
178
+
179
+        }
180
+
181
+        return $result;
182
+    }
183
+
184
+    /**
185
+     * check if it is a file uploaded by the user stored in data/user/files
186
+     * or a metadata file
187
+     *
188
+     * @param string $path relative to the data/ folder
189
+     * @return boolean
190
+     */
191
+    public function isFile($path) {
192
+        $parts = explode('/', Filesystem::normalizePath($path), 4);
193
+        if (isset($parts[2]) && $parts[2] === 'files') {
194
+            return true;
195
+        }
196
+        return false;
197
+    }
198
+
199
+    /**
200
+     * return size of encryption header
201
+     *
202
+     * @return integer
203
+     */
204
+    public function getHeaderSize() {
205
+        return $this->headerSize;
206
+    }
207
+
208
+    /**
209
+     * return size of block read by a PHP stream
210
+     *
211
+     * @return integer
212
+     */
213
+    public function getBlockSize() {
214
+        return $this->blockSize;
215
+    }
216
+
217
+    /**
218
+     * get the owner and the path for the file relative to the owners files folder
219
+     *
220
+     * @param string $path
221
+     * @return array
222
+     * @throws \BadMethodCallException
223
+     */
224
+    public function getUidAndFilename($path) {
225
+
226
+        $parts = explode('/', $path);
227
+        $uid = '';
228
+        if (count($parts) > 2) {
229
+            $uid = $parts[1];
230
+        }
231
+        if (!$this->userManager->userExists($uid)) {
232
+            throw new \BadMethodCallException(
233
+                'path needs to be relative to the system wide data folder and point to a user specific file'
234
+            );
235
+        }
236
+
237
+        $ownerPath = implode('/', array_slice($parts, 2));
238
+
239
+        return array($uid, Filesystem::normalizePath($ownerPath));
240
+
241
+    }
242
+
243
+    /**
244
+     * Remove .path extension from a file path
245
+     * @param string $path Path that may identify a .part file
246
+     * @return string File path without .part extension
247
+     * @note this is needed for reusing keys
248
+     */
249
+    public function stripPartialFileExtension($path) {
250
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
251
+
252
+        if ( $extension === 'part') {
253
+
254
+            $newLength = strlen($path) - 5; // 5 = strlen(".part")
255
+            $fPath = substr($path, 0, $newLength);
256
+
257
+            // if path also contains a transaction id, we remove it too
258
+            $extension = pathinfo($fPath, PATHINFO_EXTENSION);
259
+            if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
260
+                $newLength = strlen($fPath) - strlen($extension) -1;
261
+                $fPath = substr($fPath, 0, $newLength);
262
+            }
263
+            return $fPath;
264
+
265
+        } else {
266
+            return $path;
267
+        }
268
+    }
269
+
270
+    public function getUserWithAccessToMountPoint($users, $groups) {
271
+        $result = array();
272
+        if (in_array('all', $users)) {
273
+            $result = \OCP\User::getUsers();
274
+        } else {
275
+            $result = array_merge($result, $users);
276
+
277
+            $groupManager = \OC::$server->getGroupManager();
278
+            foreach ($groups as $group) {
279
+                $groupObject = $groupManager->get($group);
280
+                if ($groupObject) {
281
+                    $foundUsers = $groupObject->searchUsers('', -1, 0);
282
+                    $userIds = [];
283
+                    foreach ($foundUsers as $user) {
284
+                        $userIds[] = $user->getUID();
285
+                    }
286
+                    $result = array_merge($result, $userIds);
287
+                }
288
+            }
289
+        }
290
+
291
+        return $result;
292
+    }
293
+
294
+    /**
295
+     * check if the file is stored on a system wide mount point
296
+     * @param string $path relative to /data/user with leading '/'
297
+     * @param string $uid
298
+     * @return boolean
299
+     */
300
+    public function isSystemWideMountPoint($path, $uid) {
301
+        if (\OCP\App::isEnabled("files_external")) {
302
+            $mounts = \OC_Mount_Config::getSystemMountPoints();
303
+            foreach ($mounts as $mount) {
304
+                if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
305
+                    if ($this->isMountPointApplicableToUser($mount, $uid)) {
306
+                        return true;
307
+                    }
308
+                }
309
+            }
310
+        }
311
+        return false;
312
+    }
313
+
314
+    /**
315
+     * check if mount point is applicable to user
316
+     *
317
+     * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
318
+     * @param string $uid
319
+     * @return boolean
320
+     */
321
+    private function isMountPointApplicableToUser($mount, $uid) {
322
+        $acceptedUids = array('all', $uid);
323
+        // check if mount point is applicable for the user
324
+        $intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
325
+        if (!empty($intersection)) {
326
+            return true;
327
+        }
328
+        // check if mount point is applicable for group where the user is a member
329
+        foreach ($mount['applicable']['groups'] as $gid) {
330
+            if ($this->groupManager->isInGroup($uid, $gid)) {
331
+                return true;
332
+            }
333
+        }
334
+        return false;
335
+    }
336
+
337
+    /**
338
+     * check if it is a path which is excluded by ownCloud from encryption
339
+     *
340
+     * @param string $path
341
+     * @return boolean
342
+     */
343
+    public function isExcluded($path) {
344
+        $normalizedPath = Filesystem::normalizePath($path);
345
+        $root = explode('/', $normalizedPath, 4);
346
+        if (count($root) > 1) {
347
+
348
+            // detect alternative key storage root
349
+            $rootDir = $this->getKeyStorageRoot();
350
+            if ($rootDir !== '' &&
351
+                0 === strpos(
352
+                    Filesystem::normalizePath($path),
353
+                    Filesystem::normalizePath($rootDir)
354
+                )
355
+            ) {
356
+                return true;
357
+            }
358
+
359
+
360
+            //detect system wide folders
361
+            if (in_array($root[1], $this->excludedPaths)) {
362
+                return true;
363
+            }
364
+
365
+            // detect user specific folders
366
+            if ($this->userManager->userExists($root[1])
367
+                && in_array($root[2], $this->excludedPaths)) {
368
+
369
+                return true;
370
+            }
371
+        }
372
+        return false;
373
+    }
374
+
375
+    /**
376
+     * check if recovery key is enabled for user
377
+     *
378
+     * @param string $uid
379
+     * @return boolean
380
+     */
381
+    public function recoveryEnabled($uid) {
382
+        $enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
383
+
384
+        return ($enabled === '1') ? true : false;
385
+    }
386
+
387
+    /**
388
+     * set new key storage root
389
+     *
390
+     * @param string $root new key store root relative to the data folder
391
+     */
392
+    public function setKeyStorageRoot($root) {
393
+        $this->config->setAppValue('core', 'encryption_key_storage_root', $root);
394
+    }
395
+
396
+    /**
397
+     * get key storage root
398
+     *
399
+     * @return string key storage root
400
+     */
401
+    public function getKeyStorageRoot() {
402
+        return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
403
+    }
404 404
 
405 405
 }
Please login to merge, or discard this patch.
lib/private/legacy/user.php 1 patch
Indentation   +559 added lines, -560 removed lines patch added patch discarded remove patch
@@ -57,564 +57,563 @@
 block discarded – undo
57 57
  */
58 58
 class OC_User {
59 59
 
60
-	/**
61
-	 * @return \OC\User\Session
62
-	 */
63
-	public static function getUserSession() {
64
-		return OC::$server->getUserSession();
65
-	}
66
-
67
-	private static $_usedBackends = array();
68
-
69
-	private static $_setupedBackends = array();
70
-
71
-	// bool, stores if a user want to access a resource anonymously, e.g if they open a public link
72
-	private static $incognitoMode = false;
73
-
74
-	/**
75
-	 * Adds the backend to the list of used backends
76
-	 *
77
-	 * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
78
-	 * @return bool
79
-	 *
80
-	 * Set the User Authentication Module
81
-	 */
82
-	public static function useBackend($backend = 'database') {
83
-		if ($backend instanceof \OCP\UserInterface) {
84
-			self::$_usedBackends[get_class($backend)] = $backend;
85
-			\OC::$server->getUserManager()->registerBackend($backend);
86
-		} else {
87
-			// You'll never know what happens
88
-			if (null === $backend OR !is_string($backend)) {
89
-				$backend = 'database';
90
-			}
91
-
92
-			// Load backend
93
-			switch ($backend) {
94
-				case 'database':
95
-				case 'mysql':
96
-				case 'sqlite':
97
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
98
-					self::$_usedBackends[$backend] = new \OC\User\Database();
99
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
100
-					break;
101
-				case 'dummy':
102
-					self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
103
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
104
-					break;
105
-				default:
106
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
107
-					$className = 'OC_USER_' . strtoupper($backend);
108
-					self::$_usedBackends[$backend] = new $className();
109
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
110
-					break;
111
-			}
112
-		}
113
-		return true;
114
-	}
115
-
116
-	/**
117
-	 * remove all used backends
118
-	 */
119
-	public static function clearBackends() {
120
-		self::$_usedBackends = array();
121
-		\OC::$server->getUserManager()->clearBackends();
122
-	}
123
-
124
-	/**
125
-	 * setup the configured backends in config.php
126
-	 */
127
-	public static function setupBackends() {
128
-		OC_App::loadApps(['prelogin']);
129
-		$backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
130
-		if (isset($backends['default']) && !$backends['default']) {
131
-			// clear default backends
132
-			self::clearBackends();
133
-		}
134
-		foreach ($backends as $i => $config) {
135
-			if (!is_array($config)) {
136
-				continue;
137
-			}
138
-			$class = $config['class'];
139
-			$arguments = $config['arguments'];
140
-			if (class_exists($class)) {
141
-				if (array_search($i, self::$_setupedBackends) === false) {
142
-					// make a reflection object
143
-					$reflectionObj = new ReflectionClass($class);
144
-
145
-					// use Reflection to create a new instance, using the $args
146
-					$backend = $reflectionObj->newInstanceArgs($arguments);
147
-					self::useBackend($backend);
148
-					self::$_setupedBackends[] = $i;
149
-				} else {
150
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
151
-				}
152
-			} else {
153
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
154
-			}
155
-		}
156
-	}
157
-
158
-	/**
159
-
160
-	 * Try to login a user using the magic cookie (remember login)
161
-	 *
162
-	 * @deprecated use \OCP\IUserSession::loginWithCookie()
163
-	 * @param string $uid The username of the user to log in
164
-	 * @param string $token
165
-	 * @param string $oldSessionId
166
-	 * @return bool
167
-	 */
168
-	public static function loginWithCookie($uid, $token, $oldSessionId) {
169
-		return self::getUserSession()->loginWithCookie($uid, $token, $oldSessionId);
170
-	}
171
-
172
-	/**
173
-	 * Try to login a user, assuming authentication
174
-	 * has already happened (e.g. via Single Sign On).
175
-	 *
176
-	 * Log in a user and regenerate a new session.
177
-	 *
178
-	 * @param \OCP\Authentication\IApacheBackend $backend
179
-	 * @return bool
180
-	 */
181
-	public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
182
-
183
-		$uid = $backend->getCurrentUserId();
184
-		$run = true;
185
-		OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
186
-
187
-		if ($uid) {
188
-			if (self::getUser() !== $uid) {
189
-				self::setUserId($uid);
190
-				$setUidAsDisplayName = true;
191
-				if($backend instanceof \OCP\UserInterface
192
-					&& $backend->implementsActions(OC_User_Backend::GET_DISPLAYNAME)) {
193
-
194
-					$backendDisplayName = $backend->getDisplayName($uid);
195
-					if(is_string($backendDisplayName) && trim($backendDisplayName) !== '') {
196
-						$setUidAsDisplayName = false;
197
-					}
198
-				}
199
-				if($setUidAsDisplayName) {
200
-					self::setDisplayName($uid);
201
-				}
202
-				self::getUserSession()->setLoginName($uid);
203
-				$request = OC::$server->getRequest();
204
-				self::getUserSession()->createSessionToken($request, $uid, $uid);
205
-				// setup the filesystem
206
-				OC_Util::setupFS($uid);
207
-				// first call the post_login hooks, the login-process needs to be
208
-				// completed before we can safely create the users folder.
209
-				// For example encryption needs to initialize the users keys first
210
-				// before we can create the user folder with the skeleton files
211
-				OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
212
-				//trigger creation of user home and /files folder
213
-				\OC::$server->getUserFolder($uid);
214
-			}
215
-			return true;
216
-		}
217
-		return false;
218
-	}
219
-
220
-	/**
221
-	 * Verify with Apache whether user is authenticated.
222
-	 *
223
-	 * @return boolean|null
224
-	 *          true: authenticated
225
-	 *          false: not authenticated
226
-	 *          null: not handled / no backend available
227
-	 */
228
-	public static function handleApacheAuth() {
229
-		$backend = self::findFirstActiveUsedBackend();
230
-		if ($backend) {
231
-			OC_App::loadApps();
232
-
233
-			//setup extra user backends
234
-			self::setupBackends();
235
-			self::unsetMagicInCookie();
236
-
237
-			return self::loginWithApache($backend);
238
-		}
239
-
240
-		return null;
241
-	}
242
-
243
-
244
-	/**
245
-	 * Sets user id for session and triggers emit
246
-	 *
247
-	 * @param string $uid
248
-	 */
249
-	public static function setUserId($uid) {
250
-		$userSession = \OC::$server->getUserSession();
251
-		$userManager = \OC::$server->getUserManager();
252
-		if ($user = $userManager->get($uid)) {
253
-			$userSession->setUser($user);
254
-		} else {
255
-			\OC::$server->getSession()->set('user_id', $uid);
256
-		}
257
-	}
258
-
259
-	/**
260
-	 * Sets user display name for session
261
-	 *
262
-	 * @param string $uid
263
-	 * @param string $displayName
264
-	 * @return bool Whether the display name could get set
265
-	 */
266
-	public static function setDisplayName($uid, $displayName = null) {
267
-		if (is_null($displayName)) {
268
-			$displayName = $uid;
269
-		}
270
-		$user = \OC::$server->getUserManager()->get($uid);
271
-		if ($user) {
272
-			return $user->setDisplayName($displayName);
273
-		} else {
274
-			return false;
275
-		}
276
-	}
277
-
278
-	/**
279
-	 * Check if the user is logged in, considers also the HTTP basic credentials
280
-	 *
281
-	 * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
282
-	 * @return bool
283
-	 */
284
-	public static function isLoggedIn() {
285
-		return \OC::$server->getUserSession()->isLoggedIn();
286
-	}
287
-
288
-	/**
289
-	 * set incognito mode, e.g. if a user wants to open a public link
290
-	 *
291
-	 * @param bool $status
292
-	 */
293
-	public static function setIncognitoMode($status) {
294
-		self::$incognitoMode = $status;
295
-	}
296
-
297
-	/**
298
-	 * get incognito mode status
299
-	 *
300
-	 * @return bool
301
-	 */
302
-	public static function isIncognitoMode() {
303
-		return self::$incognitoMode;
304
-	}
305
-
306
-	/**
307
-	 * Supplies an attribute to the logout hyperlink. The default behaviour
308
-	 * is to return an href with '?logout=true' appended. However, it can
309
-	 * supply any attribute(s) which are valid for <a>.
310
-	 *
311
-	 * @return string with one or more HTML attributes.
312
-	 */
313
-	public static function getLogoutAttribute() {
314
-		$backend = self::findFirstActiveUsedBackend();
315
-		if ($backend) {
316
-			return $backend->getLogoutAttribute();
317
-		}
318
-
319
-		$logoutUrl = \OC::$server->getURLGenerator()->linkToRouteAbsolute(
320
-			'core.login.logout',
321
-			[
322
-				'requesttoken' => \OCP\Util::callRegister(),
323
-			]
324
-		);
325
-
326
-		return 'href="'.$logoutUrl.'"';
327
-	}
328
-
329
-	/**
330
-	 * Check if the user is an admin user
331
-	 *
332
-	 * @param string $uid uid of the admin
333
-	 * @return bool
334
-	 */
335
-	public static function isAdminUser($uid) {
336
-		$group = \OC::$server->getGroupManager()->get('admin');
337
-		$user = \OC::$server->getUserManager()->get($uid);
338
-		if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
339
-			return true;
340
-		}
341
-		return false;
342
-	}
343
-
344
-
345
-	/**
346
-	 * get the user id of the user currently logged in.
347
-	 *
348
-	 * @return string|bool uid or false
349
-	 */
350
-	public static function getUser() {
351
-		$uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
352
-		if (!is_null($uid) && self::$incognitoMode === false) {
353
-			return $uid;
354
-		} else {
355
-			return false;
356
-		}
357
-	}
358
-
359
-	/**
360
-	 * get the display name of the user currently logged in.
361
-	 *
362
-	 * @param string $uid
363
-	 * @return string uid or false
364
-	 */
365
-	public static function getDisplayName($uid = null) {
366
-		if ($uid) {
367
-			$user = \OC::$server->getUserManager()->get($uid);
368
-			if ($user) {
369
-				return $user->getDisplayName();
370
-			} else {
371
-				return $uid;
372
-			}
373
-		} else {
374
-			$user = self::getUserSession()->getUser();
375
-			if ($user) {
376
-				return $user->getDisplayName();
377
-			} else {
378
-				return false;
379
-			}
380
-		}
381
-	}
382
-
383
-	/**
384
-	 * Autogenerate a password
385
-	 *
386
-	 * @return string
387
-	 *
388
-	 * generates a password
389
-	 */
390
-	public static function generatePassword() {
391
-		return \OC::$server->getSecureRandom()->generate(30);
392
-	}
393
-
394
-	/**
395
-	 * Set password
396
-	 *
397
-	 * @param string $uid The username
398
-	 * @param string $password The new password
399
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
400
-	 * @return bool
401
-	 *
402
-	 * Change the password of a user
403
-	 */
404
-	public static function setPassword($uid, $password, $recoveryPassword = null) {
405
-		$user = \OC::$server->getUserManager()->get($uid);
406
-		if ($user) {
407
-			return $user->setPassword($password, $recoveryPassword);
408
-		} else {
409
-			return false;
410
-		}
411
-	}
412
-
413
-	/**
414
-	 * Check whether user can change his avatar
415
-	 *
416
-	 * @param string $uid The username
417
-	 * @return bool
418
-	 *
419
-	 * Check whether a specified user can change his avatar
420
-	 */
421
-	public static function canUserChangeAvatar($uid) {
422
-		$user = \OC::$server->getUserManager()->get($uid);
423
-		if ($user) {
424
-			return $user->canChangeAvatar();
425
-		} else {
426
-			return false;
427
-		}
428
-	}
429
-
430
-	/**
431
-	 * Check whether user can change his password
432
-	 *
433
-	 * @param string $uid The username
434
-	 * @return bool
435
-	 *
436
-	 * Check whether a specified user can change his password
437
-	 */
438
-	public static function canUserChangePassword($uid) {
439
-		$user = \OC::$server->getUserManager()->get($uid);
440
-		if ($user) {
441
-			return $user->canChangePassword();
442
-		} else {
443
-			return false;
444
-		}
445
-	}
446
-
447
-	/**
448
-	 * Check whether user can change his display name
449
-	 *
450
-	 * @param string $uid The username
451
-	 * @return bool
452
-	 *
453
-	 * Check whether a specified user can change his display name
454
-	 */
455
-	public static function canUserChangeDisplayName($uid) {
456
-		$user = \OC::$server->getUserManager()->get($uid);
457
-		if ($user) {
458
-			return $user->canChangeDisplayName();
459
-		} else {
460
-			return false;
461
-		}
462
-	}
463
-
464
-	/**
465
-	 * Check if the password is correct
466
-	 *
467
-	 * @param string $uid The username
468
-	 * @param string $password The password
469
-	 * @return string|false user id a string on success, false otherwise
470
-	 *
471
-	 * Check if the password is correct without logging in the user
472
-	 * returns the user id or false
473
-	 */
474
-	public static function checkPassword($uid, $password) {
475
-		$manager = \OC::$server->getUserManager();
476
-		$username = $manager->checkPassword($uid, $password);
477
-		if ($username !== false) {
478
-			return $username->getUID();
479
-		}
480
-		return false;
481
-	}
482
-
483
-	/**
484
-	 * @param string $uid The username
485
-	 * @return string
486
-	 *
487
-	 * returns the path to the users home directory
488
-	 * @deprecated Use \OC::$server->getUserManager->getHome()
489
-	 */
490
-	public static function getHome($uid) {
491
-		$user = \OC::$server->getUserManager()->get($uid);
492
-		if ($user) {
493
-			return $user->getHome();
494
-		} else {
495
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
496
-		}
497
-	}
498
-
499
-	/**
500
-	 * Get a list of all users
501
-	 *
502
-	 * @return array an array of all uids
503
-	 *
504
-	 * Get a list of all users.
505
-	 * @param string $search
506
-	 * @param integer $limit
507
-	 * @param integer $offset
508
-	 */
509
-	public static function getUsers($search = '', $limit = null, $offset = null) {
510
-		$users = \OC::$server->getUserManager()->search($search, $limit, $offset);
511
-		$uids = array();
512
-		foreach ($users as $user) {
513
-			$uids[] = $user->getUID();
514
-		}
515
-		return $uids;
516
-	}
517
-
518
-	/**
519
-	 * Get a list of all users display name
520
-	 *
521
-	 * @param string $search
522
-	 * @param int $limit
523
-	 * @param int $offset
524
-	 * @return array associative array with all display names (value) and corresponding uids (key)
525
-	 *
526
-	 * Get a list of all display names and user ids.
527
-	 * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
528
-	 */
529
-	public static function getDisplayNames($search = '', $limit = null, $offset = null) {
530
-		$displayNames = array();
531
-		$users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
532
-		foreach ($users as $user) {
533
-			$displayNames[$user->getUID()] = $user->getDisplayName();
534
-		}
535
-		return $displayNames;
536
-	}
537
-
538
-	/**
539
-	 * check if a user exists
540
-	 *
541
-	 * @param string $uid the username
542
-	 * @return boolean
543
-	 */
544
-	public static function userExists($uid) {
545
-		return \OC::$server->getUserManager()->userExists($uid);
546
-	}
547
-
548
-	/**
549
-	 * disables a user
550
-	 *
551
-	 * @param string $uid the user to disable
552
-	 */
553
-	public static function disableUser($uid) {
554
-		$user = \OC::$server->getUserManager()->get($uid);
555
-		if ($user) {
556
-			$user->setEnabled(false);
557
-		}
558
-	}
559
-
560
-	/**
561
-	 * enable a user
562
-	 *
563
-	 * @param string $uid
564
-	 */
565
-	public static function enableUser($uid) {
566
-		$user = \OC::$server->getUserManager()->get($uid);
567
-		if ($user) {
568
-			$user->setEnabled(true);
569
-		}
570
-	}
571
-
572
-	/**
573
-	 * checks if a user is enabled
574
-	 *
575
-	 * @param string $uid
576
-	 * @return bool
577
-	 */
578
-	public static function isEnabled($uid) {
579
-		$user = \OC::$server->getUserManager()->get($uid);
580
-		if ($user) {
581
-			return $user->isEnabled();
582
-		} else {
583
-			return false;
584
-		}
585
-	}
586
-
587
-	/**
588
-	 * Set cookie value to use in next page load
589
-	 *
590
-	 * @param string $username username to be set
591
-	 * @param string $token
592
-	 */
593
-	public static function setMagicInCookie($username, $token) {
594
-		self::getUserSession()->setMagicInCookie($username, $token);
595
-	}
596
-
597
-	/**
598
-	 * Remove cookie for "remember username"
599
-	 */
600
-	public static function unsetMagicInCookie() {
601
-		self::getUserSession()->unsetMagicInCookie();
602
-	}
603
-
604
-	/**
605
-	 * Returns the first active backend from self::$_usedBackends.
606
-	 *
607
-	 * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
608
-	 */
609
-	private static function findFirstActiveUsedBackend() {
610
-		foreach (self::$_usedBackends as $backend) {
611
-			if ($backend instanceof OCP\Authentication\IApacheBackend) {
612
-				if ($backend->isSessionActive()) {
613
-					return $backend;
614
-				}
615
-			}
616
-		}
617
-
618
-		return null;
619
-	}
60
+    /**
61
+     * @return \OC\User\Session
62
+     */
63
+    public static function getUserSession() {
64
+        return OC::$server->getUserSession();
65
+    }
66
+
67
+    private static $_usedBackends = array();
68
+
69
+    private static $_setupedBackends = array();
70
+
71
+    // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
72
+    private static $incognitoMode = false;
73
+
74
+    /**
75
+     * Adds the backend to the list of used backends
76
+     *
77
+     * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
78
+     * @return bool
79
+     *
80
+     * Set the User Authentication Module
81
+     */
82
+    public static function useBackend($backend = 'database') {
83
+        if ($backend instanceof \OCP\UserInterface) {
84
+            self::$_usedBackends[get_class($backend)] = $backend;
85
+            \OC::$server->getUserManager()->registerBackend($backend);
86
+        } else {
87
+            // You'll never know what happens
88
+            if (null === $backend OR !is_string($backend)) {
89
+                $backend = 'database';
90
+            }
91
+
92
+            // Load backend
93
+            switch ($backend) {
94
+                case 'database':
95
+                case 'mysql':
96
+                case 'sqlite':
97
+                    \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
98
+                    self::$_usedBackends[$backend] = new \OC\User\Database();
99
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
100
+                    break;
101
+                case 'dummy':
102
+                    self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
103
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
104
+                    break;
105
+                default:
106
+                    \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
107
+                    $className = 'OC_USER_' . strtoupper($backend);
108
+                    self::$_usedBackends[$backend] = new $className();
109
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
110
+                    break;
111
+            }
112
+        }
113
+        return true;
114
+    }
115
+
116
+    /**
117
+     * remove all used backends
118
+     */
119
+    public static function clearBackends() {
120
+        self::$_usedBackends = array();
121
+        \OC::$server->getUserManager()->clearBackends();
122
+    }
123
+
124
+    /**
125
+     * setup the configured backends in config.php
126
+     */
127
+    public static function setupBackends() {
128
+        OC_App::loadApps(['prelogin']);
129
+        $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
130
+        if (isset($backends['default']) && !$backends['default']) {
131
+            // clear default backends
132
+            self::clearBackends();
133
+        }
134
+        foreach ($backends as $i => $config) {
135
+            if (!is_array($config)) {
136
+                continue;
137
+            }
138
+            $class = $config['class'];
139
+            $arguments = $config['arguments'];
140
+            if (class_exists($class)) {
141
+                if (array_search($i, self::$_setupedBackends) === false) {
142
+                    // make a reflection object
143
+                    $reflectionObj = new ReflectionClass($class);
144
+
145
+                    // use Reflection to create a new instance, using the $args
146
+                    $backend = $reflectionObj->newInstanceArgs($arguments);
147
+                    self::useBackend($backend);
148
+                    self::$_setupedBackends[] = $i;
149
+                } else {
150
+                    \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
151
+                }
152
+            } else {
153
+                \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
154
+            }
155
+        }
156
+    }
157
+
158
+    /**
159
+     * Try to login a user using the magic cookie (remember login)
160
+     *
161
+     * @deprecated use \OCP\IUserSession::loginWithCookie()
162
+     * @param string $uid The username of the user to log in
163
+     * @param string $token
164
+     * @param string $oldSessionId
165
+     * @return bool
166
+     */
167
+    public static function loginWithCookie($uid, $token, $oldSessionId) {
168
+        return self::getUserSession()->loginWithCookie($uid, $token, $oldSessionId);
169
+    }
170
+
171
+    /**
172
+     * Try to login a user, assuming authentication
173
+     * has already happened (e.g. via Single Sign On).
174
+     *
175
+     * Log in a user and regenerate a new session.
176
+     *
177
+     * @param \OCP\Authentication\IApacheBackend $backend
178
+     * @return bool
179
+     */
180
+    public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
181
+
182
+        $uid = $backend->getCurrentUserId();
183
+        $run = true;
184
+        OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
185
+
186
+        if ($uid) {
187
+            if (self::getUser() !== $uid) {
188
+                self::setUserId($uid);
189
+                $setUidAsDisplayName = true;
190
+                if($backend instanceof \OCP\UserInterface
191
+                    && $backend->implementsActions(OC_User_Backend::GET_DISPLAYNAME)) {
192
+
193
+                    $backendDisplayName = $backend->getDisplayName($uid);
194
+                    if(is_string($backendDisplayName) && trim($backendDisplayName) !== '') {
195
+                        $setUidAsDisplayName = false;
196
+                    }
197
+                }
198
+                if($setUidAsDisplayName) {
199
+                    self::setDisplayName($uid);
200
+                }
201
+                self::getUserSession()->setLoginName($uid);
202
+                $request = OC::$server->getRequest();
203
+                self::getUserSession()->createSessionToken($request, $uid, $uid);
204
+                // setup the filesystem
205
+                OC_Util::setupFS($uid);
206
+                // first call the post_login hooks, the login-process needs to be
207
+                // completed before we can safely create the users folder.
208
+                // For example encryption needs to initialize the users keys first
209
+                // before we can create the user folder with the skeleton files
210
+                OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
211
+                //trigger creation of user home and /files folder
212
+                \OC::$server->getUserFolder($uid);
213
+            }
214
+            return true;
215
+        }
216
+        return false;
217
+    }
218
+
219
+    /**
220
+     * Verify with Apache whether user is authenticated.
221
+     *
222
+     * @return boolean|null
223
+     *          true: authenticated
224
+     *          false: not authenticated
225
+     *          null: not handled / no backend available
226
+     */
227
+    public static function handleApacheAuth() {
228
+        $backend = self::findFirstActiveUsedBackend();
229
+        if ($backend) {
230
+            OC_App::loadApps();
231
+
232
+            //setup extra user backends
233
+            self::setupBackends();
234
+            self::unsetMagicInCookie();
235
+
236
+            return self::loginWithApache($backend);
237
+        }
238
+
239
+        return null;
240
+    }
241
+
242
+
243
+    /**
244
+     * Sets user id for session and triggers emit
245
+     *
246
+     * @param string $uid
247
+     */
248
+    public static function setUserId($uid) {
249
+        $userSession = \OC::$server->getUserSession();
250
+        $userManager = \OC::$server->getUserManager();
251
+        if ($user = $userManager->get($uid)) {
252
+            $userSession->setUser($user);
253
+        } else {
254
+            \OC::$server->getSession()->set('user_id', $uid);
255
+        }
256
+    }
257
+
258
+    /**
259
+     * Sets user display name for session
260
+     *
261
+     * @param string $uid
262
+     * @param string $displayName
263
+     * @return bool Whether the display name could get set
264
+     */
265
+    public static function setDisplayName($uid, $displayName = null) {
266
+        if (is_null($displayName)) {
267
+            $displayName = $uid;
268
+        }
269
+        $user = \OC::$server->getUserManager()->get($uid);
270
+        if ($user) {
271
+            return $user->setDisplayName($displayName);
272
+        } else {
273
+            return false;
274
+        }
275
+    }
276
+
277
+    /**
278
+     * Check if the user is logged in, considers also the HTTP basic credentials
279
+     *
280
+     * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
281
+     * @return bool
282
+     */
283
+    public static function isLoggedIn() {
284
+        return \OC::$server->getUserSession()->isLoggedIn();
285
+    }
286
+
287
+    /**
288
+     * set incognito mode, e.g. if a user wants to open a public link
289
+     *
290
+     * @param bool $status
291
+     */
292
+    public static function setIncognitoMode($status) {
293
+        self::$incognitoMode = $status;
294
+    }
295
+
296
+    /**
297
+     * get incognito mode status
298
+     *
299
+     * @return bool
300
+     */
301
+    public static function isIncognitoMode() {
302
+        return self::$incognitoMode;
303
+    }
304
+
305
+    /**
306
+     * Supplies an attribute to the logout hyperlink. The default behaviour
307
+     * is to return an href with '?logout=true' appended. However, it can
308
+     * supply any attribute(s) which are valid for <a>.
309
+     *
310
+     * @return string with one or more HTML attributes.
311
+     */
312
+    public static function getLogoutAttribute() {
313
+        $backend = self::findFirstActiveUsedBackend();
314
+        if ($backend) {
315
+            return $backend->getLogoutAttribute();
316
+        }
317
+
318
+        $logoutUrl = \OC::$server->getURLGenerator()->linkToRouteAbsolute(
319
+            'core.login.logout',
320
+            [
321
+                'requesttoken' => \OCP\Util::callRegister(),
322
+            ]
323
+        );
324
+
325
+        return 'href="'.$logoutUrl.'"';
326
+    }
327
+
328
+    /**
329
+     * Check if the user is an admin user
330
+     *
331
+     * @param string $uid uid of the admin
332
+     * @return bool
333
+     */
334
+    public static function isAdminUser($uid) {
335
+        $group = \OC::$server->getGroupManager()->get('admin');
336
+        $user = \OC::$server->getUserManager()->get($uid);
337
+        if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
338
+            return true;
339
+        }
340
+        return false;
341
+    }
342
+
343
+
344
+    /**
345
+     * get the user id of the user currently logged in.
346
+     *
347
+     * @return string|bool uid or false
348
+     */
349
+    public static function getUser() {
350
+        $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
351
+        if (!is_null($uid) && self::$incognitoMode === false) {
352
+            return $uid;
353
+        } else {
354
+            return false;
355
+        }
356
+    }
357
+
358
+    /**
359
+     * get the display name of the user currently logged in.
360
+     *
361
+     * @param string $uid
362
+     * @return string uid or false
363
+     */
364
+    public static function getDisplayName($uid = null) {
365
+        if ($uid) {
366
+            $user = \OC::$server->getUserManager()->get($uid);
367
+            if ($user) {
368
+                return $user->getDisplayName();
369
+            } else {
370
+                return $uid;
371
+            }
372
+        } else {
373
+            $user = self::getUserSession()->getUser();
374
+            if ($user) {
375
+                return $user->getDisplayName();
376
+            } else {
377
+                return false;
378
+            }
379
+        }
380
+    }
381
+
382
+    /**
383
+     * Autogenerate a password
384
+     *
385
+     * @return string
386
+     *
387
+     * generates a password
388
+     */
389
+    public static function generatePassword() {
390
+        return \OC::$server->getSecureRandom()->generate(30);
391
+    }
392
+
393
+    /**
394
+     * Set password
395
+     *
396
+     * @param string $uid The username
397
+     * @param string $password The new password
398
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
399
+     * @return bool
400
+     *
401
+     * Change the password of a user
402
+     */
403
+    public static function setPassword($uid, $password, $recoveryPassword = null) {
404
+        $user = \OC::$server->getUserManager()->get($uid);
405
+        if ($user) {
406
+            return $user->setPassword($password, $recoveryPassword);
407
+        } else {
408
+            return false;
409
+        }
410
+    }
411
+
412
+    /**
413
+     * Check whether user can change his avatar
414
+     *
415
+     * @param string $uid The username
416
+     * @return bool
417
+     *
418
+     * Check whether a specified user can change his avatar
419
+     */
420
+    public static function canUserChangeAvatar($uid) {
421
+        $user = \OC::$server->getUserManager()->get($uid);
422
+        if ($user) {
423
+            return $user->canChangeAvatar();
424
+        } else {
425
+            return false;
426
+        }
427
+    }
428
+
429
+    /**
430
+     * Check whether user can change his password
431
+     *
432
+     * @param string $uid The username
433
+     * @return bool
434
+     *
435
+     * Check whether a specified user can change his password
436
+     */
437
+    public static function canUserChangePassword($uid) {
438
+        $user = \OC::$server->getUserManager()->get($uid);
439
+        if ($user) {
440
+            return $user->canChangePassword();
441
+        } else {
442
+            return false;
443
+        }
444
+    }
445
+
446
+    /**
447
+     * Check whether user can change his display name
448
+     *
449
+     * @param string $uid The username
450
+     * @return bool
451
+     *
452
+     * Check whether a specified user can change his display name
453
+     */
454
+    public static function canUserChangeDisplayName($uid) {
455
+        $user = \OC::$server->getUserManager()->get($uid);
456
+        if ($user) {
457
+            return $user->canChangeDisplayName();
458
+        } else {
459
+            return false;
460
+        }
461
+    }
462
+
463
+    /**
464
+     * Check if the password is correct
465
+     *
466
+     * @param string $uid The username
467
+     * @param string $password The password
468
+     * @return string|false user id a string on success, false otherwise
469
+     *
470
+     * Check if the password is correct without logging in the user
471
+     * returns the user id or false
472
+     */
473
+    public static function checkPassword($uid, $password) {
474
+        $manager = \OC::$server->getUserManager();
475
+        $username = $manager->checkPassword($uid, $password);
476
+        if ($username !== false) {
477
+            return $username->getUID();
478
+        }
479
+        return false;
480
+    }
481
+
482
+    /**
483
+     * @param string $uid The username
484
+     * @return string
485
+     *
486
+     * returns the path to the users home directory
487
+     * @deprecated Use \OC::$server->getUserManager->getHome()
488
+     */
489
+    public static function getHome($uid) {
490
+        $user = \OC::$server->getUserManager()->get($uid);
491
+        if ($user) {
492
+            return $user->getHome();
493
+        } else {
494
+            return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
495
+        }
496
+    }
497
+
498
+    /**
499
+     * Get a list of all users
500
+     *
501
+     * @return array an array of all uids
502
+     *
503
+     * Get a list of all users.
504
+     * @param string $search
505
+     * @param integer $limit
506
+     * @param integer $offset
507
+     */
508
+    public static function getUsers($search = '', $limit = null, $offset = null) {
509
+        $users = \OC::$server->getUserManager()->search($search, $limit, $offset);
510
+        $uids = array();
511
+        foreach ($users as $user) {
512
+            $uids[] = $user->getUID();
513
+        }
514
+        return $uids;
515
+    }
516
+
517
+    /**
518
+     * Get a list of all users display name
519
+     *
520
+     * @param string $search
521
+     * @param int $limit
522
+     * @param int $offset
523
+     * @return array associative array with all display names (value) and corresponding uids (key)
524
+     *
525
+     * Get a list of all display names and user ids.
526
+     * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
527
+     */
528
+    public static function getDisplayNames($search = '', $limit = null, $offset = null) {
529
+        $displayNames = array();
530
+        $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
531
+        foreach ($users as $user) {
532
+            $displayNames[$user->getUID()] = $user->getDisplayName();
533
+        }
534
+        return $displayNames;
535
+    }
536
+
537
+    /**
538
+     * check if a user exists
539
+     *
540
+     * @param string $uid the username
541
+     * @return boolean
542
+     */
543
+    public static function userExists($uid) {
544
+        return \OC::$server->getUserManager()->userExists($uid);
545
+    }
546
+
547
+    /**
548
+     * disables a user
549
+     *
550
+     * @param string $uid the user to disable
551
+     */
552
+    public static function disableUser($uid) {
553
+        $user = \OC::$server->getUserManager()->get($uid);
554
+        if ($user) {
555
+            $user->setEnabled(false);
556
+        }
557
+    }
558
+
559
+    /**
560
+     * enable a user
561
+     *
562
+     * @param string $uid
563
+     */
564
+    public static function enableUser($uid) {
565
+        $user = \OC::$server->getUserManager()->get($uid);
566
+        if ($user) {
567
+            $user->setEnabled(true);
568
+        }
569
+    }
570
+
571
+    /**
572
+     * checks if a user is enabled
573
+     *
574
+     * @param string $uid
575
+     * @return bool
576
+     */
577
+    public static function isEnabled($uid) {
578
+        $user = \OC::$server->getUserManager()->get($uid);
579
+        if ($user) {
580
+            return $user->isEnabled();
581
+        } else {
582
+            return false;
583
+        }
584
+    }
585
+
586
+    /**
587
+     * Set cookie value to use in next page load
588
+     *
589
+     * @param string $username username to be set
590
+     * @param string $token
591
+     */
592
+    public static function setMagicInCookie($username, $token) {
593
+        self::getUserSession()->setMagicInCookie($username, $token);
594
+    }
595
+
596
+    /**
597
+     * Remove cookie for "remember username"
598
+     */
599
+    public static function unsetMagicInCookie() {
600
+        self::getUserSession()->unsetMagicInCookie();
601
+    }
602
+
603
+    /**
604
+     * Returns the first active backend from self::$_usedBackends.
605
+     *
606
+     * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
607
+     */
608
+    private static function findFirstActiveUsedBackend() {
609
+        foreach (self::$_usedBackends as $backend) {
610
+            if ($backend instanceof OCP\Authentication\IApacheBackend) {
611
+                if ($backend->isSessionActive()) {
612
+                    return $backend;
613
+                }
614
+            }
615
+        }
616
+
617
+        return null;
618
+    }
620 619
 }
Please login to merge, or discard this patch.
lib/public/OCS/IDiscoveryService.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -32,17 +32,17 @@
 block discarded – undo
32 32
  */
33 33
 interface IDiscoveryService {
34 34
 
35
-	/**
36
-	 * Discover OCS end-points
37
-	 *
38
-	 * If no valid discovery data is found the defaults are returned
39
-	 *
40
-	 * @since 12.0.0
41
-	 *
42
-	 * @param string $remote
43
-	 * @param string $service the service you want to discover
44
-	 * @return array
45
-	 */
46
-	public function discover($remote, $service);
35
+    /**
36
+     * Discover OCS end-points
37
+     *
38
+     * If no valid discovery data is found the defaults are returned
39
+     *
40
+     * @since 12.0.0
41
+     *
42
+     * @param string $remote
43
+     * @param string $service the service you want to discover
44
+     * @return array
45
+     */
46
+    public function discover($remote, $service);
47 47
 
48 48
 }
Please login to merge, or discard this patch.