Passed
Push — master ( 2b97f0...20094a )
by Julius
14:15 queued 10s
created
apps/federation/lib/DbHandler.php 2 patches
Indentation   +291 added lines, -291 removed lines patch added patch discarded remove patch
@@ -42,295 +42,295 @@
 block discarded – undo
42 42
  */
43 43
 class DbHandler {
44 44
 
45
-	/** @var  IDBConnection */
46
-	private $connection;
47
-
48
-	/** @var  IL10N */
49
-	private $IL10N;
50
-
51
-	/** @var string  */
52
-	private $dbTable = 'trusted_servers';
53
-
54
-	/**
55
-	 * @param IDBConnection $connection
56
-	 * @param IL10N $il10n
57
-	 */
58
-	public function __construct(
59
-		IDBConnection $connection,
60
-		IL10N $il10n
61
-	) {
62
-		$this->connection = $connection;
63
-		$this->IL10N = $il10n;
64
-	}
65
-
66
-	/**
67
-	 * add server to the list of trusted servers
68
-	 *
69
-	 * @param string $url
70
-	 * @return int
71
-	 * @throws HintException
72
-	 */
73
-	public function addServer($url) {
74
-		$hash = $this->hash($url);
75
-		$url = rtrim($url, '/');
76
-		$query = $this->connection->getQueryBuilder();
77
-		$query->insert($this->dbTable)
78
-			->values(
79
-				[
80
-					'url' => $query->createParameter('url'),
81
-					'url_hash' => $query->createParameter('url_hash'),
82
-				]
83
-			)
84
-			->setParameter('url', $url)
85
-			->setParameter('url_hash', $hash);
86
-
87
-		$result = $query->execute();
88
-
89
-		if ($result) {
90
-			return $query->getLastInsertId();
91
-		}
92
-
93
-		$message = 'Internal failure, Could not add trusted server: ' . $url;
94
-		$message_t = $this->IL10N->t('Could not add server');
95
-		throw new HintException($message, $message_t);
96
-	}
97
-
98
-	/**
99
-	 * remove server from the list of trusted servers
100
-	 *
101
-	 * @param int $id
102
-	 */
103
-	public function removeServer($id) {
104
-		$query = $this->connection->getQueryBuilder();
105
-		$query->delete($this->dbTable)
106
-			->where($query->expr()->eq('id', $query->createParameter('id')))
107
-			->setParameter('id', $id);
108
-		$query->execute();
109
-	}
110
-
111
-	/**
112
-	 * get trusted server with given ID
113
-	 *
114
-	 * @param int $id
115
-	 * @return array
116
-	 * @throws \Exception
117
-	 */
118
-	public function getServerById($id) {
119
-		$query = $this->connection->getQueryBuilder();
120
-		$query->select('*')->from($this->dbTable)
121
-			->where($query->expr()->eq('id', $query->createParameter('id')))
122
-			->setParameter('id', $id);
123
-
124
-		$qResult = $query->execute();
125
-		$result = $qResult->fetchAll();
126
-		$qResult->closeCursor();
127
-
128
-		if (empty($result)) {
129
-			throw new \Exception('No Server found with ID: ' . $id);
130
-		}
131
-
132
-		return $result[0];
133
-	}
134
-
135
-	/**
136
-	 * get all trusted servers
137
-	 *
138
-	 * @return array
139
-	 */
140
-	public function getAllServer() {
141
-		$query = $this->connection->getQueryBuilder();
142
-		$query->select(['url', 'url_hash', 'id', 'status', 'shared_secret', 'sync_token'])
143
-			->from($this->dbTable);
144
-		$statement = $query->execute();
145
-		$result = $statement->fetchAll();
146
-		$statement->closeCursor();
147
-		return $result;
148
-	}
149
-
150
-	/**
151
-	 * check if server already exists in the database table
152
-	 *
153
-	 * @param string $url
154
-	 * @return bool
155
-	 */
156
-	public function serverExists($url) {
157
-		$hash = $this->hash($url);
158
-		$query = $this->connection->getQueryBuilder();
159
-		$query->select('url')
160
-			->from($this->dbTable)
161
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
162
-			->setParameter('url_hash', $hash);
163
-		$statement = $query->execute();
164
-		$result = $statement->fetchAll();
165
-		$statement->closeCursor();
166
-
167
-		return !empty($result);
168
-	}
169
-
170
-	/**
171
-	 * write token to database. Token is used to exchange the secret
172
-	 *
173
-	 * @param string $url
174
-	 * @param string $token
175
-	 */
176
-	public function addToken($url, $token) {
177
-		$hash = $this->hash($url);
178
-		$query = $this->connection->getQueryBuilder();
179
-		$query->update($this->dbTable)
180
-			->set('token', $query->createParameter('token'))
181
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
182
-			->setParameter('url_hash', $hash)
183
-			->setParameter('token', $token);
184
-		$query->execute();
185
-	}
186
-
187
-	/**
188
-	 * get token stored in database
189
-	 *
190
-	 * @param string $url
191
-	 * @return string
192
-	 * @throws \Exception
193
-	 */
194
-	public function getToken($url) {
195
-		$hash = $this->hash($url);
196
-		$query = $this->connection->getQueryBuilder();
197
-		$query->select('token')->from($this->dbTable)
198
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
199
-			->setParameter('url_hash', $hash);
200
-
201
-		$statement = $query->execute();
202
-		$result = $statement->fetch();
203
-		$statement->closeCursor();
204
-
205
-		if (!isset($result['token'])) {
206
-			throw new \Exception('No token found for: ' . $url);
207
-		}
208
-
209
-		return $result['token'];
210
-	}
211
-
212
-	/**
213
-	 * add shared Secret to database
214
-	 *
215
-	 * @param string $url
216
-	 * @param string $sharedSecret
217
-	 */
218
-	public function addSharedSecret($url, $sharedSecret) {
219
-		$hash = $this->hash($url);
220
-		$query = $this->connection->getQueryBuilder();
221
-		$query->update($this->dbTable)
222
-			->set('shared_secret', $query->createParameter('sharedSecret'))
223
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
224
-			->setParameter('url_hash', $hash)
225
-			->setParameter('sharedSecret', $sharedSecret);
226
-		$query->execute();
227
-	}
228
-
229
-	/**
230
-	 * get shared secret from database
231
-	 *
232
-	 * @param string $url
233
-	 * @return string
234
-	 */
235
-	public function getSharedSecret($url) {
236
-		$hash = $this->hash($url);
237
-		$query = $this->connection->getQueryBuilder();
238
-		$query->select('shared_secret')->from($this->dbTable)
239
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
240
-			->setParameter('url_hash', $hash);
241
-
242
-		$statement = $query->execute();
243
-		$result = $statement->fetch();
244
-		$statement->closeCursor();
245
-		return $result['shared_secret'];
246
-	}
247
-
248
-	/**
249
-	 * set server status
250
-	 *
251
-	 * @param string $url
252
-	 * @param int $status
253
-	 * @param string|null $token
254
-	 */
255
-	public function setServerStatus($url, $status, $token = null) {
256
-		$hash = $this->hash($url);
257
-		$query = $this->connection->getQueryBuilder();
258
-		$query->update($this->dbTable)
259
-				->set('status', $query->createNamedParameter($status))
260
-				->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash)));
261
-		if (!is_null($token)) {
262
-			$query->set('sync_token', $query->createNamedParameter($token));
263
-		}
264
-		$query->execute();
265
-	}
266
-
267
-	/**
268
-	 * get server status
269
-	 *
270
-	 * @param string $url
271
-	 * @return int
272
-	 */
273
-	public function getServerStatus($url) {
274
-		$hash = $this->hash($url);
275
-		$query = $this->connection->getQueryBuilder();
276
-		$query->select('status')->from($this->dbTable)
277
-				->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
278
-				->setParameter('url_hash', $hash);
279
-
280
-		$statement = $query->execute();
281
-		$result = $statement->fetch();
282
-		$statement->closeCursor();
283
-		return (int)$result['status'];
284
-	}
285
-
286
-	/**
287
-	 * create hash from URL
288
-	 *
289
-	 * @param string $url
290
-	 * @return string
291
-	 */
292
-	protected function hash($url) {
293
-		$normalized = $this->normalizeUrl($url);
294
-		return sha1($normalized);
295
-	}
296
-
297
-	/**
298
-	 * normalize URL, used to create the sha1 hash
299
-	 *
300
-	 * @param string $url
301
-	 * @return string
302
-	 */
303
-	protected function normalizeUrl($url) {
304
-		$normalized = $url;
305
-
306
-		if (strpos($url, 'https://') === 0) {
307
-			$normalized = substr($url, strlen('https://'));
308
-		} elseif (strpos($url, 'http://') === 0) {
309
-			$normalized = substr($url, strlen('http://'));
310
-		}
311
-
312
-		$normalized = Filesystem::normalizePath($normalized);
313
-		$normalized = trim($normalized, '/');
314
-
315
-		return $normalized;
316
-	}
317
-
318
-	/**
319
-	 * @param $username
320
-	 * @param $password
321
-	 * @return bool
322
-	 */
323
-	public function auth($username, $password) {
324
-		if ($username !== 'system') {
325
-			return false;
326
-		}
327
-		$query = $this->connection->getQueryBuilder();
328
-		$query->select('url')->from($this->dbTable)
329
-				->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password)));
330
-
331
-		$statement = $query->execute();
332
-		$result = $statement->fetch();
333
-		$statement->closeCursor();
334
-		return !empty($result);
335
-	}
45
+    /** @var  IDBConnection */
46
+    private $connection;
47
+
48
+    /** @var  IL10N */
49
+    private $IL10N;
50
+
51
+    /** @var string  */
52
+    private $dbTable = 'trusted_servers';
53
+
54
+    /**
55
+     * @param IDBConnection $connection
56
+     * @param IL10N $il10n
57
+     */
58
+    public function __construct(
59
+        IDBConnection $connection,
60
+        IL10N $il10n
61
+    ) {
62
+        $this->connection = $connection;
63
+        $this->IL10N = $il10n;
64
+    }
65
+
66
+    /**
67
+     * add server to the list of trusted servers
68
+     *
69
+     * @param string $url
70
+     * @return int
71
+     * @throws HintException
72
+     */
73
+    public function addServer($url) {
74
+        $hash = $this->hash($url);
75
+        $url = rtrim($url, '/');
76
+        $query = $this->connection->getQueryBuilder();
77
+        $query->insert($this->dbTable)
78
+            ->values(
79
+                [
80
+                    'url' => $query->createParameter('url'),
81
+                    'url_hash' => $query->createParameter('url_hash'),
82
+                ]
83
+            )
84
+            ->setParameter('url', $url)
85
+            ->setParameter('url_hash', $hash);
86
+
87
+        $result = $query->execute();
88
+
89
+        if ($result) {
90
+            return $query->getLastInsertId();
91
+        }
92
+
93
+        $message = 'Internal failure, Could not add trusted server: ' . $url;
94
+        $message_t = $this->IL10N->t('Could not add server');
95
+        throw new HintException($message, $message_t);
96
+    }
97
+
98
+    /**
99
+     * remove server from the list of trusted servers
100
+     *
101
+     * @param int $id
102
+     */
103
+    public function removeServer($id) {
104
+        $query = $this->connection->getQueryBuilder();
105
+        $query->delete($this->dbTable)
106
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
107
+            ->setParameter('id', $id);
108
+        $query->execute();
109
+    }
110
+
111
+    /**
112
+     * get trusted server with given ID
113
+     *
114
+     * @param int $id
115
+     * @return array
116
+     * @throws \Exception
117
+     */
118
+    public function getServerById($id) {
119
+        $query = $this->connection->getQueryBuilder();
120
+        $query->select('*')->from($this->dbTable)
121
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
122
+            ->setParameter('id', $id);
123
+
124
+        $qResult = $query->execute();
125
+        $result = $qResult->fetchAll();
126
+        $qResult->closeCursor();
127
+
128
+        if (empty($result)) {
129
+            throw new \Exception('No Server found with ID: ' . $id);
130
+        }
131
+
132
+        return $result[0];
133
+    }
134
+
135
+    /**
136
+     * get all trusted servers
137
+     *
138
+     * @return array
139
+     */
140
+    public function getAllServer() {
141
+        $query = $this->connection->getQueryBuilder();
142
+        $query->select(['url', 'url_hash', 'id', 'status', 'shared_secret', 'sync_token'])
143
+            ->from($this->dbTable);
144
+        $statement = $query->execute();
145
+        $result = $statement->fetchAll();
146
+        $statement->closeCursor();
147
+        return $result;
148
+    }
149
+
150
+    /**
151
+     * check if server already exists in the database table
152
+     *
153
+     * @param string $url
154
+     * @return bool
155
+     */
156
+    public function serverExists($url) {
157
+        $hash = $this->hash($url);
158
+        $query = $this->connection->getQueryBuilder();
159
+        $query->select('url')
160
+            ->from($this->dbTable)
161
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
162
+            ->setParameter('url_hash', $hash);
163
+        $statement = $query->execute();
164
+        $result = $statement->fetchAll();
165
+        $statement->closeCursor();
166
+
167
+        return !empty($result);
168
+    }
169
+
170
+    /**
171
+     * write token to database. Token is used to exchange the secret
172
+     *
173
+     * @param string $url
174
+     * @param string $token
175
+     */
176
+    public function addToken($url, $token) {
177
+        $hash = $this->hash($url);
178
+        $query = $this->connection->getQueryBuilder();
179
+        $query->update($this->dbTable)
180
+            ->set('token', $query->createParameter('token'))
181
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
182
+            ->setParameter('url_hash', $hash)
183
+            ->setParameter('token', $token);
184
+        $query->execute();
185
+    }
186
+
187
+    /**
188
+     * get token stored in database
189
+     *
190
+     * @param string $url
191
+     * @return string
192
+     * @throws \Exception
193
+     */
194
+    public function getToken($url) {
195
+        $hash = $this->hash($url);
196
+        $query = $this->connection->getQueryBuilder();
197
+        $query->select('token')->from($this->dbTable)
198
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
199
+            ->setParameter('url_hash', $hash);
200
+
201
+        $statement = $query->execute();
202
+        $result = $statement->fetch();
203
+        $statement->closeCursor();
204
+
205
+        if (!isset($result['token'])) {
206
+            throw new \Exception('No token found for: ' . $url);
207
+        }
208
+
209
+        return $result['token'];
210
+    }
211
+
212
+    /**
213
+     * add shared Secret to database
214
+     *
215
+     * @param string $url
216
+     * @param string $sharedSecret
217
+     */
218
+    public function addSharedSecret($url, $sharedSecret) {
219
+        $hash = $this->hash($url);
220
+        $query = $this->connection->getQueryBuilder();
221
+        $query->update($this->dbTable)
222
+            ->set('shared_secret', $query->createParameter('sharedSecret'))
223
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
224
+            ->setParameter('url_hash', $hash)
225
+            ->setParameter('sharedSecret', $sharedSecret);
226
+        $query->execute();
227
+    }
228
+
229
+    /**
230
+     * get shared secret from database
231
+     *
232
+     * @param string $url
233
+     * @return string
234
+     */
235
+    public function getSharedSecret($url) {
236
+        $hash = $this->hash($url);
237
+        $query = $this->connection->getQueryBuilder();
238
+        $query->select('shared_secret')->from($this->dbTable)
239
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
240
+            ->setParameter('url_hash', $hash);
241
+
242
+        $statement = $query->execute();
243
+        $result = $statement->fetch();
244
+        $statement->closeCursor();
245
+        return $result['shared_secret'];
246
+    }
247
+
248
+    /**
249
+     * set server status
250
+     *
251
+     * @param string $url
252
+     * @param int $status
253
+     * @param string|null $token
254
+     */
255
+    public function setServerStatus($url, $status, $token = null) {
256
+        $hash = $this->hash($url);
257
+        $query = $this->connection->getQueryBuilder();
258
+        $query->update($this->dbTable)
259
+                ->set('status', $query->createNamedParameter($status))
260
+                ->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash)));
261
+        if (!is_null($token)) {
262
+            $query->set('sync_token', $query->createNamedParameter($token));
263
+        }
264
+        $query->execute();
265
+    }
266
+
267
+    /**
268
+     * get server status
269
+     *
270
+     * @param string $url
271
+     * @return int
272
+     */
273
+    public function getServerStatus($url) {
274
+        $hash = $this->hash($url);
275
+        $query = $this->connection->getQueryBuilder();
276
+        $query->select('status')->from($this->dbTable)
277
+                ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
278
+                ->setParameter('url_hash', $hash);
279
+
280
+        $statement = $query->execute();
281
+        $result = $statement->fetch();
282
+        $statement->closeCursor();
283
+        return (int)$result['status'];
284
+    }
285
+
286
+    /**
287
+     * create hash from URL
288
+     *
289
+     * @param string $url
290
+     * @return string
291
+     */
292
+    protected function hash($url) {
293
+        $normalized = $this->normalizeUrl($url);
294
+        return sha1($normalized);
295
+    }
296
+
297
+    /**
298
+     * normalize URL, used to create the sha1 hash
299
+     *
300
+     * @param string $url
301
+     * @return string
302
+     */
303
+    protected function normalizeUrl($url) {
304
+        $normalized = $url;
305
+
306
+        if (strpos($url, 'https://') === 0) {
307
+            $normalized = substr($url, strlen('https://'));
308
+        } elseif (strpos($url, 'http://') === 0) {
309
+            $normalized = substr($url, strlen('http://'));
310
+        }
311
+
312
+        $normalized = Filesystem::normalizePath($normalized);
313
+        $normalized = trim($normalized, '/');
314
+
315
+        return $normalized;
316
+    }
317
+
318
+    /**
319
+     * @param $username
320
+     * @param $password
321
+     * @return bool
322
+     */
323
+    public function auth($username, $password) {
324
+        if ($username !== 'system') {
325
+            return false;
326
+        }
327
+        $query = $this->connection->getQueryBuilder();
328
+        $query->select('url')->from($this->dbTable)
329
+                ->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password)));
330
+
331
+        $statement = $query->execute();
332
+        $result = $statement->fetch();
333
+        $statement->closeCursor();
334
+        return !empty($result);
335
+    }
336 336
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			return $query->getLastInsertId();
91 91
 		}
92 92
 
93
-		$message = 'Internal failure, Could not add trusted server: ' . $url;
93
+		$message = 'Internal failure, Could not add trusted server: '.$url;
94 94
 		$message_t = $this->IL10N->t('Could not add server');
95 95
 		throw new HintException($message, $message_t);
96 96
 	}
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 		$qResult->closeCursor();
127 127
 
128 128
 		if (empty($result)) {
129
-			throw new \Exception('No Server found with ID: ' . $id);
129
+			throw new \Exception('No Server found with ID: '.$id);
130 130
 		}
131 131
 
132 132
 		return $result[0];
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 		$statement->closeCursor();
204 204
 
205 205
 		if (!isset($result['token'])) {
206
-			throw new \Exception('No token found for: ' . $url);
206
+			throw new \Exception('No token found for: '.$url);
207 207
 		}
208 208
 
209 209
 		return $result['token'];
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 		$statement = $query->execute();
281 281
 		$result = $statement->fetch();
282 282
 		$statement->closeCursor();
283
-		return (int)$result['status'];
283
+		return (int) $result['status'];
284 284
 	}
285 285
 
286 286
 	/**
Please login to merge, or discard this patch.
apps/files_external/lib/Service/DBConfigService.php 2 patches
Indentation   +496 added lines, -496 removed lines patch added patch discarded remove patch
@@ -36,500 +36,500 @@
 block discarded – undo
36 36
  * Stores the mount config in the database
37 37
  */
38 38
 class DBConfigService {
39
-	public const MOUNT_TYPE_ADMIN = 1;
40
-	public const MOUNT_TYPE_PERSONAl = 2;
41
-
42
-	public const APPLICABLE_TYPE_GLOBAL = 1;
43
-	public const APPLICABLE_TYPE_GROUP = 2;
44
-	public const APPLICABLE_TYPE_USER = 3;
45
-
46
-	/**
47
-	 * @var IDBConnection
48
-	 */
49
-	private $connection;
50
-
51
-	/**
52
-	 * @var ICrypto
53
-	 */
54
-	private $crypto;
55
-
56
-	/**
57
-	 * DBConfigService constructor.
58
-	 *
59
-	 * @param IDBConnection $connection
60
-	 * @param ICrypto $crypto
61
-	 */
62
-	public function __construct(IDBConnection $connection, ICrypto $crypto) {
63
-		$this->connection = $connection;
64
-		$this->crypto = $crypto;
65
-	}
66
-
67
-	/**
68
-	 * @param int $mountId
69
-	 * @return array
70
-	 */
71
-	public function getMountById($mountId) {
72
-		$builder = $this->connection->getQueryBuilder();
73
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
74
-			->from('external_mounts', 'm')
75
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
76
-		$mounts = $this->getMountsFromQuery($query);
77
-		if (count($mounts) > 0) {
78
-			return $mounts[0];
79
-		} else {
80
-			return null;
81
-		}
82
-	}
83
-
84
-	/**
85
-	 * Get all configured mounts
86
-	 *
87
-	 * @return array
88
-	 */
89
-	public function getAllMounts() {
90
-		$builder = $this->connection->getQueryBuilder();
91
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
92
-			->from('external_mounts');
93
-		return $this->getMountsFromQuery($query);
94
-	}
95
-
96
-	public function getMountsForUser($userId, $groupIds) {
97
-		$builder = $this->connection->getQueryBuilder();
98
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
99
-			->from('external_mounts', 'm')
100
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
101
-			->where($builder->expr()->orX(
102
-				$builder->expr()->andX( // global mounts
103
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
104
-					$builder->expr()->isNull('a.value')
105
-				),
106
-				$builder->expr()->andX( // mounts for user
107
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
108
-					$builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
109
-				),
110
-				$builder->expr()->andX( // mounts for group
111
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
112
-					$builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_STR_ARRAY))
113
-				)
114
-			));
115
-
116
-		return $this->getMountsFromQuery($query);
117
-	}
118
-
119
-	public function modifyMountsOnUserDelete(string $uid): void {
120
-		$this->modifyMountsOnDelete($uid, self::APPLICABLE_TYPE_USER);
121
-	}
122
-
123
-	public function modifyMountsOnGroupDelete(string $gid): void {
124
-		$this->modifyMountsOnDelete($gid, self::APPLICABLE_TYPE_GROUP);
125
-	}
126
-
127
-	protected function modifyMountsOnDelete(string $applicableId, int $applicableType): void {
128
-		$builder = $this->connection->getQueryBuilder();
129
-		$query = $builder->select(['a.mount_id', $builder->func()->count('a.mount_id', 'count')])
130
-			->from('external_applicable', 'a')
131
-			->leftJoin('a', 'external_applicable', 'b', $builder->expr()->eq('a.mount_id', 'b.mount_id'))
132
-			->where($builder->expr()->andX(
133
-				$builder->expr()->eq('b.type', $builder->createNamedParameter($applicableType, IQueryBuilder::PARAM_INT)),
134
-				$builder->expr()->eq('b.value', $builder->createNamedParameter($applicableId))
135
-			)
136
-			)
137
-			->groupBy(['a.mount_id']);
138
-		$stmt = $query->execute();
139
-		$result = $stmt->fetchAll();
140
-		$stmt->closeCursor();
141
-
142
-		foreach ($result as $row) {
143
-			if ((int)$row['count'] > 1) {
144
-				$this->removeApplicable($row['mount_id'], $applicableType, $applicableId);
145
-			} else {
146
-				$this->removeMount($row['mount_id']);
147
-			}
148
-		}
149
-	}
150
-
151
-	/**
152
-	 * Get admin defined mounts
153
-	 *
154
-	 * @return array
155
-	 */
156
-	public function getAdminMounts() {
157
-		$builder = $this->connection->getQueryBuilder();
158
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
159
-			->from('external_mounts')
160
-			->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
161
-		return $this->getMountsFromQuery($query);
162
-	}
163
-
164
-	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
165
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
166
-			->from('external_mounts', 'm')
167
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
168
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
169
-
170
-		if (is_null($value)) {
171
-			$query = $query->andWhere($builder->expr()->isNull('a.value'));
172
-		} else {
173
-			$query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
174
-		}
175
-
176
-		return $query;
177
-	}
178
-
179
-	/**
180
-	 * Get mounts by applicable
181
-	 *
182
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
183
-	 * @param string|null $value user_id, group_id or null for global mounts
184
-	 * @return array
185
-	 */
186
-	public function getMountsFor($type, $value) {
187
-		$builder = $this->connection->getQueryBuilder();
188
-		$query = $this->getForQuery($builder, $type, $value);
189
-
190
-		return $this->getMountsFromQuery($query);
191
-	}
192
-
193
-	/**
194
-	 * Get admin defined mounts by applicable
195
-	 *
196
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
197
-	 * @param string|null $value user_id, group_id or null for global mounts
198
-	 * @return array
199
-	 */
200
-	public function getAdminMountsFor($type, $value) {
201
-		$builder = $this->connection->getQueryBuilder();
202
-		$query = $this->getForQuery($builder, $type, $value);
203
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
204
-
205
-		return $this->getMountsFromQuery($query);
206
-	}
207
-
208
-	/**
209
-	 * Get admin defined mounts for multiple applicable
210
-	 *
211
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
212
-	 * @param string[] $values user_ids or group_ids
213
-	 * @return array
214
-	 */
215
-	public function getAdminMountsForMultiple($type, array $values) {
216
-		$builder = $this->connection->getQueryBuilder();
217
-		$params = array_map(function ($value) use ($builder) {
218
-			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
219
-		}, $values);
220
-
221
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
222
-			->from('external_mounts', 'm')
223
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
224
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
225
-			->andWhere($builder->expr()->in('a.value', $params));
226
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
227
-
228
-		return $this->getMountsFromQuery($query);
229
-	}
230
-
231
-	/**
232
-	 * Get user defined mounts by applicable
233
-	 *
234
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
235
-	 * @param string|null $value user_id, group_id or null for global mounts
236
-	 * @return array
237
-	 */
238
-	public function getUserMountsFor($type, $value) {
239
-		$builder = $this->connection->getQueryBuilder();
240
-		$query = $this->getForQuery($builder, $type, $value);
241
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
242
-
243
-		return $this->getMountsFromQuery($query);
244
-	}
245
-
246
-	/**
247
-	 * Add a mount to the database
248
-	 *
249
-	 * @param string $mountPoint
250
-	 * @param string $storageBackend
251
-	 * @param string $authBackend
252
-	 * @param int $priority
253
-	 * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
254
-	 * @return int the id of the new mount
255
-	 */
256
-	public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
257
-		if (!$priority) {
258
-			$priority = 100;
259
-		}
260
-		$builder = $this->connection->getQueryBuilder();
261
-		$query = $builder->insert('external_mounts')
262
-			->values([
263
-				'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
264
-				'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
265
-				'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
266
-				'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
267
-				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
268
-			]);
269
-		$query->execute();
270
-		return $query->getLastInsertId();
271
-	}
272
-
273
-	/**
274
-	 * Remove a mount from the database
275
-	 *
276
-	 * @param int $mountId
277
-	 */
278
-	public function removeMount($mountId) {
279
-		$builder = $this->connection->getQueryBuilder();
280
-		$query = $builder->delete('external_mounts')
281
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
282
-		$query->execute();
283
-
284
-		$query = $builder->delete('external_applicable')
285
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
286
-		$query->execute();
287
-
288
-		$query = $builder->delete('external_config')
289
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
290
-		$query->execute();
291
-
292
-		$query = $builder->delete('external_options')
293
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
294
-		$query->execute();
295
-	}
296
-
297
-	/**
298
-	 * @param int $mountId
299
-	 * @param string $newMountPoint
300
-	 */
301
-	public function setMountPoint($mountId, $newMountPoint) {
302
-		$builder = $this->connection->getQueryBuilder();
303
-
304
-		$query = $builder->update('external_mounts')
305
-			->set('mount_point', $builder->createNamedParameter($newMountPoint))
306
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
307
-
308
-		$query->execute();
309
-	}
310
-
311
-	/**
312
-	 * @param int $mountId
313
-	 * @param string $newAuthBackend
314
-	 */
315
-	public function setAuthBackend($mountId, $newAuthBackend) {
316
-		$builder = $this->connection->getQueryBuilder();
317
-
318
-		$query = $builder->update('external_mounts')
319
-			->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
320
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
321
-
322
-		$query->execute();
323
-	}
324
-
325
-	/**
326
-	 * @param int $mountId
327
-	 * @param string $key
328
-	 * @param string $value
329
-	 */
330
-	public function setConfig($mountId, $key, $value) {
331
-		if ($key === 'password') {
332
-			$value = $this->encryptValue($value);
333
-		}
334
-
335
-		try {
336
-			$builder = $this->connection->getQueryBuilder();
337
-			$builder->insert('external_config')
338
-				->setValue('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT))
339
-				->setValue('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR))
340
-				->setValue('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
341
-				->execute();
342
-		} catch (UniqueConstraintViolationException $e) {
343
-			$builder = $this->connection->getQueryBuilder();
344
-			$query = $builder->update('external_config')
345
-				->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
346
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
347
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
348
-			$query->execute();
349
-		}
350
-	}
351
-
352
-	/**
353
-	 * @param int $mountId
354
-	 * @param string $key
355
-	 * @param string $value
356
-	 */
357
-	public function setOption($mountId, $key, $value) {
358
-		try {
359
-			$builder = $this->connection->getQueryBuilder();
360
-			$builder->insert('external_options')
361
-				->setValue('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT))
362
-				->setValue('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR))
363
-				->setValue('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
364
-				->execute();
365
-		} catch (UniqueConstraintViolationException $e) {
366
-			$builder = $this->connection->getQueryBuilder();
367
-			$query = $builder->update('external_options')
368
-				->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
369
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
370
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
371
-			$query->execute();
372
-		}
373
-	}
374
-
375
-	public function addApplicable($mountId, $type, $value) {
376
-		try {
377
-			$builder = $this->connection->getQueryBuilder();
378
-			$builder->insert('external_applicable')
379
-				->setValue('mount_id', $builder->createNamedParameter($mountId))
380
-				->setValue('type', $builder->createNamedParameter($type))
381
-				->setValue('value', $builder->createNamedParameter($value))
382
-				->execute();
383
-		} catch (UniqueConstraintViolationException $e) {
384
-			// applicable exists already
385
-		}
386
-	}
387
-
388
-	public function removeApplicable($mountId, $type, $value) {
389
-		$builder = $this->connection->getQueryBuilder();
390
-		$query = $builder->delete('external_applicable')
391
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
392
-			->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
393
-
394
-		if (is_null($value)) {
395
-			$query = $query->andWhere($builder->expr()->isNull('value'));
396
-		} else {
397
-			$query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
398
-		}
399
-
400
-		$query->execute();
401
-	}
402
-
403
-	private function getMountsFromQuery(IQueryBuilder $query) {
404
-		$result = $query->execute();
405
-		$mounts = $result->fetchAll();
406
-		$uniqueMounts = [];
407
-		foreach ($mounts as $mount) {
408
-			$id = $mount['mount_id'];
409
-			if (!isset($uniqueMounts[$id])) {
410
-				$uniqueMounts[$id] = $mount;
411
-			}
412
-		}
413
-		$uniqueMounts = array_values($uniqueMounts);
414
-
415
-		$mountIds = array_map(function ($mount) {
416
-			return $mount['mount_id'];
417
-		}, $uniqueMounts);
418
-		$mountIds = array_values(array_unique($mountIds));
419
-
420
-		$applicable = $this->getApplicableForMounts($mountIds);
421
-		$config = $this->getConfigForMounts($mountIds);
422
-		$options = $this->getOptionsForMounts($mountIds);
423
-
424
-		return array_map(function ($mount, $applicable, $config, $options) {
425
-			$mount['type'] = (int)$mount['type'];
426
-			$mount['priority'] = (int)$mount['priority'];
427
-			$mount['applicable'] = $applicable;
428
-			$mount['config'] = $config;
429
-			$mount['options'] = $options;
430
-			return $mount;
431
-		}, $uniqueMounts, $applicable, $config, $options);
432
-	}
433
-
434
-	/**
435
-	 * Get mount options from a table grouped by mount id
436
-	 *
437
-	 * @param string $table
438
-	 * @param string[] $fields
439
-	 * @param int[] $mountIds
440
-	 * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
441
-	 */
442
-	private function selectForMounts($table, array $fields, array $mountIds) {
443
-		if (count($mountIds) === 0) {
444
-			return [];
445
-		}
446
-		$builder = $this->connection->getQueryBuilder();
447
-		$fields[] = 'mount_id';
448
-		$placeHolders = array_map(function ($id) use ($builder) {
449
-			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
450
-		}, $mountIds);
451
-		$query = $builder->select($fields)
452
-			->from($table)
453
-			->where($builder->expr()->in('mount_id', $placeHolders));
454
-
455
-		$result = $query->execute();
456
-		$rows = $result->fetchAll();
457
-		$result->closeCursor();
458
-
459
-		$result = [];
460
-		foreach ($mountIds as $mountId) {
461
-			$result[$mountId] = [];
462
-		}
463
-		foreach ($rows as $row) {
464
-			if (isset($row['type'])) {
465
-				$row['type'] = (int)$row['type'];
466
-			}
467
-			$result[$row['mount_id']][] = $row;
468
-		}
469
-		return $result;
470
-	}
471
-
472
-	/**
473
-	 * @param int[] $mountIds
474
-	 * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
475
-	 */
476
-	public function getApplicableForMounts($mountIds) {
477
-		return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
478
-	}
479
-
480
-	/**
481
-	 * @param int[] $mountIds
482
-	 * @return array [$id => ['key1' => $value1, ...], ...]
483
-	 */
484
-	public function getConfigForMounts($mountIds) {
485
-		$mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
486
-		return array_map([$this, 'createKeyValueMap'], $mountConfigs);
487
-	}
488
-
489
-	/**
490
-	 * @param int[] $mountIds
491
-	 * @return array [$id => ['key1' => $value1, ...], ...]
492
-	 */
493
-	public function getOptionsForMounts($mountIds) {
494
-		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
495
-		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
496
-		return array_map(function (array $options) {
497
-			return array_map(function ($option) {
498
-				return json_decode($option);
499
-			}, $options);
500
-		}, $optionsMap);
501
-	}
502
-
503
-	/**
504
-	 * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
505
-	 * @return array ['key1' => $value1, ...]
506
-	 */
507
-	private function createKeyValueMap(array $keyValuePairs) {
508
-		$decryptedPairts = array_map(function ($pair) {
509
-			if ($pair['key'] === 'password') {
510
-				$pair['value'] = $this->decryptValue($pair['value']);
511
-			}
512
-			return $pair;
513
-		}, $keyValuePairs);
514
-		$keys = array_map(function ($pair) {
515
-			return $pair['key'];
516
-		}, $decryptedPairts);
517
-		$values = array_map(function ($pair) {
518
-			return $pair['value'];
519
-		}, $decryptedPairts);
520
-
521
-		return array_combine($keys, $values);
522
-	}
523
-
524
-	private function encryptValue($value) {
525
-		return $this->crypto->encrypt($value);
526
-	}
527
-
528
-	private function decryptValue($value) {
529
-		try {
530
-			return $this->crypto->decrypt($value);
531
-		} catch (\Exception $e) {
532
-			return $value;
533
-		}
534
-	}
39
+    public const MOUNT_TYPE_ADMIN = 1;
40
+    public const MOUNT_TYPE_PERSONAl = 2;
41
+
42
+    public const APPLICABLE_TYPE_GLOBAL = 1;
43
+    public const APPLICABLE_TYPE_GROUP = 2;
44
+    public const APPLICABLE_TYPE_USER = 3;
45
+
46
+    /**
47
+     * @var IDBConnection
48
+     */
49
+    private $connection;
50
+
51
+    /**
52
+     * @var ICrypto
53
+     */
54
+    private $crypto;
55
+
56
+    /**
57
+     * DBConfigService constructor.
58
+     *
59
+     * @param IDBConnection $connection
60
+     * @param ICrypto $crypto
61
+     */
62
+    public function __construct(IDBConnection $connection, ICrypto $crypto) {
63
+        $this->connection = $connection;
64
+        $this->crypto = $crypto;
65
+    }
66
+
67
+    /**
68
+     * @param int $mountId
69
+     * @return array
70
+     */
71
+    public function getMountById($mountId) {
72
+        $builder = $this->connection->getQueryBuilder();
73
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
74
+            ->from('external_mounts', 'm')
75
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
76
+        $mounts = $this->getMountsFromQuery($query);
77
+        if (count($mounts) > 0) {
78
+            return $mounts[0];
79
+        } else {
80
+            return null;
81
+        }
82
+    }
83
+
84
+    /**
85
+     * Get all configured mounts
86
+     *
87
+     * @return array
88
+     */
89
+    public function getAllMounts() {
90
+        $builder = $this->connection->getQueryBuilder();
91
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
92
+            ->from('external_mounts');
93
+        return $this->getMountsFromQuery($query);
94
+    }
95
+
96
+    public function getMountsForUser($userId, $groupIds) {
97
+        $builder = $this->connection->getQueryBuilder();
98
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
99
+            ->from('external_mounts', 'm')
100
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
101
+            ->where($builder->expr()->orX(
102
+                $builder->expr()->andX( // global mounts
103
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
104
+                    $builder->expr()->isNull('a.value')
105
+                ),
106
+                $builder->expr()->andX( // mounts for user
107
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
108
+                    $builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
109
+                ),
110
+                $builder->expr()->andX( // mounts for group
111
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
112
+                    $builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_STR_ARRAY))
113
+                )
114
+            ));
115
+
116
+        return $this->getMountsFromQuery($query);
117
+    }
118
+
119
+    public function modifyMountsOnUserDelete(string $uid): void {
120
+        $this->modifyMountsOnDelete($uid, self::APPLICABLE_TYPE_USER);
121
+    }
122
+
123
+    public function modifyMountsOnGroupDelete(string $gid): void {
124
+        $this->modifyMountsOnDelete($gid, self::APPLICABLE_TYPE_GROUP);
125
+    }
126
+
127
+    protected function modifyMountsOnDelete(string $applicableId, int $applicableType): void {
128
+        $builder = $this->connection->getQueryBuilder();
129
+        $query = $builder->select(['a.mount_id', $builder->func()->count('a.mount_id', 'count')])
130
+            ->from('external_applicable', 'a')
131
+            ->leftJoin('a', 'external_applicable', 'b', $builder->expr()->eq('a.mount_id', 'b.mount_id'))
132
+            ->where($builder->expr()->andX(
133
+                $builder->expr()->eq('b.type', $builder->createNamedParameter($applicableType, IQueryBuilder::PARAM_INT)),
134
+                $builder->expr()->eq('b.value', $builder->createNamedParameter($applicableId))
135
+            )
136
+            )
137
+            ->groupBy(['a.mount_id']);
138
+        $stmt = $query->execute();
139
+        $result = $stmt->fetchAll();
140
+        $stmt->closeCursor();
141
+
142
+        foreach ($result as $row) {
143
+            if ((int)$row['count'] > 1) {
144
+                $this->removeApplicable($row['mount_id'], $applicableType, $applicableId);
145
+            } else {
146
+                $this->removeMount($row['mount_id']);
147
+            }
148
+        }
149
+    }
150
+
151
+    /**
152
+     * Get admin defined mounts
153
+     *
154
+     * @return array
155
+     */
156
+    public function getAdminMounts() {
157
+        $builder = $this->connection->getQueryBuilder();
158
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
159
+            ->from('external_mounts')
160
+            ->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
161
+        return $this->getMountsFromQuery($query);
162
+    }
163
+
164
+    protected function getForQuery(IQueryBuilder $builder, $type, $value) {
165
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
166
+            ->from('external_mounts', 'm')
167
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
168
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
169
+
170
+        if (is_null($value)) {
171
+            $query = $query->andWhere($builder->expr()->isNull('a.value'));
172
+        } else {
173
+            $query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
174
+        }
175
+
176
+        return $query;
177
+    }
178
+
179
+    /**
180
+     * Get mounts by applicable
181
+     *
182
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
183
+     * @param string|null $value user_id, group_id or null for global mounts
184
+     * @return array
185
+     */
186
+    public function getMountsFor($type, $value) {
187
+        $builder = $this->connection->getQueryBuilder();
188
+        $query = $this->getForQuery($builder, $type, $value);
189
+
190
+        return $this->getMountsFromQuery($query);
191
+    }
192
+
193
+    /**
194
+     * Get admin defined mounts by applicable
195
+     *
196
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
197
+     * @param string|null $value user_id, group_id or null for global mounts
198
+     * @return array
199
+     */
200
+    public function getAdminMountsFor($type, $value) {
201
+        $builder = $this->connection->getQueryBuilder();
202
+        $query = $this->getForQuery($builder, $type, $value);
203
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
204
+
205
+        return $this->getMountsFromQuery($query);
206
+    }
207
+
208
+    /**
209
+     * Get admin defined mounts for multiple applicable
210
+     *
211
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
212
+     * @param string[] $values user_ids or group_ids
213
+     * @return array
214
+     */
215
+    public function getAdminMountsForMultiple($type, array $values) {
216
+        $builder = $this->connection->getQueryBuilder();
217
+        $params = array_map(function ($value) use ($builder) {
218
+            return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
219
+        }, $values);
220
+
221
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
222
+            ->from('external_mounts', 'm')
223
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
224
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
225
+            ->andWhere($builder->expr()->in('a.value', $params));
226
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
227
+
228
+        return $this->getMountsFromQuery($query);
229
+    }
230
+
231
+    /**
232
+     * Get user defined mounts by applicable
233
+     *
234
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
235
+     * @param string|null $value user_id, group_id or null for global mounts
236
+     * @return array
237
+     */
238
+    public function getUserMountsFor($type, $value) {
239
+        $builder = $this->connection->getQueryBuilder();
240
+        $query = $this->getForQuery($builder, $type, $value);
241
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
242
+
243
+        return $this->getMountsFromQuery($query);
244
+    }
245
+
246
+    /**
247
+     * Add a mount to the database
248
+     *
249
+     * @param string $mountPoint
250
+     * @param string $storageBackend
251
+     * @param string $authBackend
252
+     * @param int $priority
253
+     * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
254
+     * @return int the id of the new mount
255
+     */
256
+    public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
257
+        if (!$priority) {
258
+            $priority = 100;
259
+        }
260
+        $builder = $this->connection->getQueryBuilder();
261
+        $query = $builder->insert('external_mounts')
262
+            ->values([
263
+                'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
264
+                'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
265
+                'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
266
+                'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
267
+                'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
268
+            ]);
269
+        $query->execute();
270
+        return $query->getLastInsertId();
271
+    }
272
+
273
+    /**
274
+     * Remove a mount from the database
275
+     *
276
+     * @param int $mountId
277
+     */
278
+    public function removeMount($mountId) {
279
+        $builder = $this->connection->getQueryBuilder();
280
+        $query = $builder->delete('external_mounts')
281
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
282
+        $query->execute();
283
+
284
+        $query = $builder->delete('external_applicable')
285
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
286
+        $query->execute();
287
+
288
+        $query = $builder->delete('external_config')
289
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
290
+        $query->execute();
291
+
292
+        $query = $builder->delete('external_options')
293
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
294
+        $query->execute();
295
+    }
296
+
297
+    /**
298
+     * @param int $mountId
299
+     * @param string $newMountPoint
300
+     */
301
+    public function setMountPoint($mountId, $newMountPoint) {
302
+        $builder = $this->connection->getQueryBuilder();
303
+
304
+        $query = $builder->update('external_mounts')
305
+            ->set('mount_point', $builder->createNamedParameter($newMountPoint))
306
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
307
+
308
+        $query->execute();
309
+    }
310
+
311
+    /**
312
+     * @param int $mountId
313
+     * @param string $newAuthBackend
314
+     */
315
+    public function setAuthBackend($mountId, $newAuthBackend) {
316
+        $builder = $this->connection->getQueryBuilder();
317
+
318
+        $query = $builder->update('external_mounts')
319
+            ->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
320
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
321
+
322
+        $query->execute();
323
+    }
324
+
325
+    /**
326
+     * @param int $mountId
327
+     * @param string $key
328
+     * @param string $value
329
+     */
330
+    public function setConfig($mountId, $key, $value) {
331
+        if ($key === 'password') {
332
+            $value = $this->encryptValue($value);
333
+        }
334
+
335
+        try {
336
+            $builder = $this->connection->getQueryBuilder();
337
+            $builder->insert('external_config')
338
+                ->setValue('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT))
339
+                ->setValue('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR))
340
+                ->setValue('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
341
+                ->execute();
342
+        } catch (UniqueConstraintViolationException $e) {
343
+            $builder = $this->connection->getQueryBuilder();
344
+            $query = $builder->update('external_config')
345
+                ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
346
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
347
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
348
+            $query->execute();
349
+        }
350
+    }
351
+
352
+    /**
353
+     * @param int $mountId
354
+     * @param string $key
355
+     * @param string $value
356
+     */
357
+    public function setOption($mountId, $key, $value) {
358
+        try {
359
+            $builder = $this->connection->getQueryBuilder();
360
+            $builder->insert('external_options')
361
+                ->setValue('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT))
362
+                ->setValue('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR))
363
+                ->setValue('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
364
+                ->execute();
365
+        } catch (UniqueConstraintViolationException $e) {
366
+            $builder = $this->connection->getQueryBuilder();
367
+            $query = $builder->update('external_options')
368
+                ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
369
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
370
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
371
+            $query->execute();
372
+        }
373
+    }
374
+
375
+    public function addApplicable($mountId, $type, $value) {
376
+        try {
377
+            $builder = $this->connection->getQueryBuilder();
378
+            $builder->insert('external_applicable')
379
+                ->setValue('mount_id', $builder->createNamedParameter($mountId))
380
+                ->setValue('type', $builder->createNamedParameter($type))
381
+                ->setValue('value', $builder->createNamedParameter($value))
382
+                ->execute();
383
+        } catch (UniqueConstraintViolationException $e) {
384
+            // applicable exists already
385
+        }
386
+    }
387
+
388
+    public function removeApplicable($mountId, $type, $value) {
389
+        $builder = $this->connection->getQueryBuilder();
390
+        $query = $builder->delete('external_applicable')
391
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
392
+            ->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
393
+
394
+        if (is_null($value)) {
395
+            $query = $query->andWhere($builder->expr()->isNull('value'));
396
+        } else {
397
+            $query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
398
+        }
399
+
400
+        $query->execute();
401
+    }
402
+
403
+    private function getMountsFromQuery(IQueryBuilder $query) {
404
+        $result = $query->execute();
405
+        $mounts = $result->fetchAll();
406
+        $uniqueMounts = [];
407
+        foreach ($mounts as $mount) {
408
+            $id = $mount['mount_id'];
409
+            if (!isset($uniqueMounts[$id])) {
410
+                $uniqueMounts[$id] = $mount;
411
+            }
412
+        }
413
+        $uniqueMounts = array_values($uniqueMounts);
414
+
415
+        $mountIds = array_map(function ($mount) {
416
+            return $mount['mount_id'];
417
+        }, $uniqueMounts);
418
+        $mountIds = array_values(array_unique($mountIds));
419
+
420
+        $applicable = $this->getApplicableForMounts($mountIds);
421
+        $config = $this->getConfigForMounts($mountIds);
422
+        $options = $this->getOptionsForMounts($mountIds);
423
+
424
+        return array_map(function ($mount, $applicable, $config, $options) {
425
+            $mount['type'] = (int)$mount['type'];
426
+            $mount['priority'] = (int)$mount['priority'];
427
+            $mount['applicable'] = $applicable;
428
+            $mount['config'] = $config;
429
+            $mount['options'] = $options;
430
+            return $mount;
431
+        }, $uniqueMounts, $applicable, $config, $options);
432
+    }
433
+
434
+    /**
435
+     * Get mount options from a table grouped by mount id
436
+     *
437
+     * @param string $table
438
+     * @param string[] $fields
439
+     * @param int[] $mountIds
440
+     * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
441
+     */
442
+    private function selectForMounts($table, array $fields, array $mountIds) {
443
+        if (count($mountIds) === 0) {
444
+            return [];
445
+        }
446
+        $builder = $this->connection->getQueryBuilder();
447
+        $fields[] = 'mount_id';
448
+        $placeHolders = array_map(function ($id) use ($builder) {
449
+            return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
450
+        }, $mountIds);
451
+        $query = $builder->select($fields)
452
+            ->from($table)
453
+            ->where($builder->expr()->in('mount_id', $placeHolders));
454
+
455
+        $result = $query->execute();
456
+        $rows = $result->fetchAll();
457
+        $result->closeCursor();
458
+
459
+        $result = [];
460
+        foreach ($mountIds as $mountId) {
461
+            $result[$mountId] = [];
462
+        }
463
+        foreach ($rows as $row) {
464
+            if (isset($row['type'])) {
465
+                $row['type'] = (int)$row['type'];
466
+            }
467
+            $result[$row['mount_id']][] = $row;
468
+        }
469
+        return $result;
470
+    }
471
+
472
+    /**
473
+     * @param int[] $mountIds
474
+     * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
475
+     */
476
+    public function getApplicableForMounts($mountIds) {
477
+        return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
478
+    }
479
+
480
+    /**
481
+     * @param int[] $mountIds
482
+     * @return array [$id => ['key1' => $value1, ...], ...]
483
+     */
484
+    public function getConfigForMounts($mountIds) {
485
+        $mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
486
+        return array_map([$this, 'createKeyValueMap'], $mountConfigs);
487
+    }
488
+
489
+    /**
490
+     * @param int[] $mountIds
491
+     * @return array [$id => ['key1' => $value1, ...], ...]
492
+     */
493
+    public function getOptionsForMounts($mountIds) {
494
+        $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
495
+        $optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
496
+        return array_map(function (array $options) {
497
+            return array_map(function ($option) {
498
+                return json_decode($option);
499
+            }, $options);
500
+        }, $optionsMap);
501
+    }
502
+
503
+    /**
504
+     * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
505
+     * @return array ['key1' => $value1, ...]
506
+     */
507
+    private function createKeyValueMap(array $keyValuePairs) {
508
+        $decryptedPairts = array_map(function ($pair) {
509
+            if ($pair['key'] === 'password') {
510
+                $pair['value'] = $this->decryptValue($pair['value']);
511
+            }
512
+            return $pair;
513
+        }, $keyValuePairs);
514
+        $keys = array_map(function ($pair) {
515
+            return $pair['key'];
516
+        }, $decryptedPairts);
517
+        $values = array_map(function ($pair) {
518
+            return $pair['value'];
519
+        }, $decryptedPairts);
520
+
521
+        return array_combine($keys, $values);
522
+    }
523
+
524
+    private function encryptValue($value) {
525
+        return $this->crypto->encrypt($value);
526
+    }
527
+
528
+    private function decryptValue($value) {
529
+        try {
530
+            return $this->crypto->decrypt($value);
531
+        } catch (\Exception $e) {
532
+            return $value;
533
+        }
534
+    }
535 535
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 		$stmt->closeCursor();
141 141
 
142 142
 		foreach ($result as $row) {
143
-			if ((int)$row['count'] > 1) {
143
+			if ((int) $row['count'] > 1) {
144 144
 				$this->removeApplicable($row['mount_id'], $applicableType, $applicableId);
145 145
 			} else {
146 146
 				$this->removeMount($row['mount_id']);
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 	 */
215 215
 	public function getAdminMountsForMultiple($type, array $values) {
216 216
 		$builder = $this->connection->getQueryBuilder();
217
-		$params = array_map(function ($value) use ($builder) {
217
+		$params = array_map(function($value) use ($builder) {
218 218
 			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
219 219
 		}, $values);
220 220
 
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
 		}
413 413
 		$uniqueMounts = array_values($uniqueMounts);
414 414
 
415
-		$mountIds = array_map(function ($mount) {
415
+		$mountIds = array_map(function($mount) {
416 416
 			return $mount['mount_id'];
417 417
 		}, $uniqueMounts);
418 418
 		$mountIds = array_values(array_unique($mountIds));
@@ -421,9 +421,9 @@  discard block
 block discarded – undo
421 421
 		$config = $this->getConfigForMounts($mountIds);
422 422
 		$options = $this->getOptionsForMounts($mountIds);
423 423
 
424
-		return array_map(function ($mount, $applicable, $config, $options) {
425
-			$mount['type'] = (int)$mount['type'];
426
-			$mount['priority'] = (int)$mount['priority'];
424
+		return array_map(function($mount, $applicable, $config, $options) {
425
+			$mount['type'] = (int) $mount['type'];
426
+			$mount['priority'] = (int) $mount['priority'];
427 427
 			$mount['applicable'] = $applicable;
428 428
 			$mount['config'] = $config;
429 429
 			$mount['options'] = $options;
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
 		}
446 446
 		$builder = $this->connection->getQueryBuilder();
447 447
 		$fields[] = 'mount_id';
448
-		$placeHolders = array_map(function ($id) use ($builder) {
448
+		$placeHolders = array_map(function($id) use ($builder) {
449 449
 			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
450 450
 		}, $mountIds);
451 451
 		$query = $builder->select($fields)
@@ -462,7 +462,7 @@  discard block
 block discarded – undo
462 462
 		}
463 463
 		foreach ($rows as $row) {
464 464
 			if (isset($row['type'])) {
465
-				$row['type'] = (int)$row['type'];
465
+				$row['type'] = (int) $row['type'];
466 466
 			}
467 467
 			$result[$row['mount_id']][] = $row;
468 468
 		}
@@ -493,8 +493,8 @@  discard block
 block discarded – undo
493 493
 	public function getOptionsForMounts($mountIds) {
494 494
 		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
495 495
 		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
496
-		return array_map(function (array $options) {
497
-			return array_map(function ($option) {
496
+		return array_map(function(array $options) {
497
+			return array_map(function($option) {
498 498
 				return json_decode($option);
499 499
 			}, $options);
500 500
 		}, $optionsMap);
@@ -505,16 +505,16 @@  discard block
 block discarded – undo
505 505
 	 * @return array ['key1' => $value1, ...]
506 506
 	 */
507 507
 	private function createKeyValueMap(array $keyValuePairs) {
508
-		$decryptedPairts = array_map(function ($pair) {
508
+		$decryptedPairts = array_map(function($pair) {
509 509
 			if ($pair['key'] === 'password') {
510 510
 				$pair['value'] = $this->decryptValue($pair['value']);
511 511
 			}
512 512
 			return $pair;
513 513
 		}, $keyValuePairs);
514
-		$keys = array_map(function ($pair) {
514
+		$keys = array_map(function($pair) {
515 515
 			return $pair['key'];
516 516
 		}, $decryptedPairts);
517
-		$values = array_map(function ($pair) {
517
+		$values = array_map(function($pair) {
518 518
 			return $pair['value'];
519 519
 		}, $decryptedPairts);
520 520
 
Please login to merge, or discard this patch.