@@ -112,7 +112,7 @@ |
||
112 | 112 | * Looks up a system wide defined value |
113 | 113 | * |
114 | 114 | * @param string $key the key of the value, under which it was saved |
115 | - * @param mixed $default the default value to be returned if the value isn't set |
|
115 | + * @param string $default the default value to be returned if the value isn't set |
|
116 | 116 | * @return mixed the value or $default |
117 | 117 | */ |
118 | 118 | public function getSystemValue($key, $default = '') { |
@@ -37,427 +37,427 @@ |
||
37 | 37 | * Class to combine all the configuration options ownCloud offers |
38 | 38 | */ |
39 | 39 | class AllConfig implements \OCP\IConfig { |
40 | - /** @var SystemConfig */ |
|
41 | - private $systemConfig; |
|
42 | - |
|
43 | - /** @var IDBConnection */ |
|
44 | - private $connection; |
|
45 | - |
|
46 | - /** |
|
47 | - * 3 dimensional array with the following structure: |
|
48 | - * [ $userId => |
|
49 | - * [ $appId => |
|
50 | - * [ $key => $value ] |
|
51 | - * ] |
|
52 | - * ] |
|
53 | - * |
|
54 | - * database table: preferences |
|
55 | - * |
|
56 | - * methods that use this: |
|
57 | - * - setUserValue |
|
58 | - * - getUserValue |
|
59 | - * - getUserKeys |
|
60 | - * - deleteUserValue |
|
61 | - * - deleteAllUserValues |
|
62 | - * - deleteAppFromAllUsers |
|
63 | - * |
|
64 | - * @var CappedMemoryCache $userCache |
|
65 | - */ |
|
66 | - private $userCache; |
|
67 | - |
|
68 | - /** |
|
69 | - * @param SystemConfig $systemConfig |
|
70 | - */ |
|
71 | - public function __construct(SystemConfig $systemConfig) { |
|
72 | - $this->userCache = new CappedMemoryCache(); |
|
73 | - $this->systemConfig = $systemConfig; |
|
74 | - } |
|
75 | - |
|
76 | - /** |
|
77 | - * TODO - FIXME This fixes an issue with base.php that cause cyclic |
|
78 | - * dependencies, especially with autoconfig setup |
|
79 | - * |
|
80 | - * Replace this by properly injected database connection. Currently the |
|
81 | - * base.php triggers the getDatabaseConnection too early which causes in |
|
82 | - * autoconfig setup case a too early distributed database connection and |
|
83 | - * the autoconfig then needs to reinit all already initialized dependencies |
|
84 | - * that use the database connection. |
|
85 | - * |
|
86 | - * otherwise a SQLite database is created in the wrong directory |
|
87 | - * because the database connection was created with an uninitialized config |
|
88 | - */ |
|
89 | - private function fixDIInit() { |
|
90 | - if($this->connection === null) { |
|
91 | - $this->connection = \OC::$server->getDatabaseConnection(); |
|
92 | - } |
|
93 | - } |
|
94 | - |
|
95 | - /** |
|
96 | - * Sets and deletes system wide values |
|
97 | - * |
|
98 | - * @param array $configs Associative array with `key => value` pairs |
|
99 | - * If value is null, the config key will be deleted |
|
100 | - */ |
|
101 | - public function setSystemValues(array $configs) { |
|
102 | - $this->systemConfig->setValues($configs); |
|
103 | - } |
|
104 | - |
|
105 | - /** |
|
106 | - * Sets a new system wide value |
|
107 | - * |
|
108 | - * @param string $key the key of the value, under which will be saved |
|
109 | - * @param mixed $value the value that should be stored |
|
110 | - */ |
|
111 | - public function setSystemValue($key, $value) { |
|
112 | - $this->systemConfig->setValue($key, $value); |
|
113 | - } |
|
114 | - |
|
115 | - /** |
|
116 | - * Looks up a system wide defined value |
|
117 | - * |
|
118 | - * @param string $key the key of the value, under which it was saved |
|
119 | - * @param mixed $default the default value to be returned if the value isn't set |
|
120 | - * @return mixed the value or $default |
|
121 | - */ |
|
122 | - public function getSystemValue($key, $default = '') { |
|
123 | - return $this->systemConfig->getValue($key, $default); |
|
124 | - } |
|
125 | - |
|
126 | - /** |
|
127 | - * Looks up a system wide defined value and filters out sensitive data |
|
128 | - * |
|
129 | - * @param string $key the key of the value, under which it was saved |
|
130 | - * @param mixed $default the default value to be returned if the value isn't set |
|
131 | - * @return mixed the value or $default |
|
132 | - */ |
|
133 | - public function getFilteredSystemValue($key, $default = '') { |
|
134 | - return $this->systemConfig->getFilteredValue($key, $default); |
|
135 | - } |
|
136 | - |
|
137 | - /** |
|
138 | - * Delete a system wide defined value |
|
139 | - * |
|
140 | - * @param string $key the key of the value, under which it was saved |
|
141 | - */ |
|
142 | - public function deleteSystemValue($key) { |
|
143 | - $this->systemConfig->deleteValue($key); |
|
144 | - } |
|
145 | - |
|
146 | - /** |
|
147 | - * Get all keys stored for an app |
|
148 | - * |
|
149 | - * @param string $appName the appName that we stored the value under |
|
150 | - * @return string[] the keys stored for the app |
|
151 | - */ |
|
152 | - public function getAppKeys($appName) { |
|
153 | - return \OC::$server->getAppConfig()->getKeys($appName); |
|
154 | - } |
|
155 | - |
|
156 | - /** |
|
157 | - * Writes a new app wide value |
|
158 | - * |
|
159 | - * @param string $appName the appName that we want to store the value under |
|
160 | - * @param string $key the key of the value, under which will be saved |
|
161 | - * @param string|float|int $value the value that should be stored |
|
162 | - */ |
|
163 | - public function setAppValue($appName, $key, $value) { |
|
164 | - \OC::$server->getAppConfig()->setValue($appName, $key, $value); |
|
165 | - } |
|
166 | - |
|
167 | - /** |
|
168 | - * Looks up an app wide defined value |
|
169 | - * |
|
170 | - * @param string $appName the appName that we stored the value under |
|
171 | - * @param string $key the key of the value, under which it was saved |
|
172 | - * @param string $default the default value to be returned if the value isn't set |
|
173 | - * @return string the saved value |
|
174 | - */ |
|
175 | - public function getAppValue($appName, $key, $default = '') { |
|
176 | - return \OC::$server->getAppConfig()->getValue($appName, $key, $default); |
|
177 | - } |
|
178 | - |
|
179 | - /** |
|
180 | - * Delete an app wide defined value |
|
181 | - * |
|
182 | - * @param string $appName the appName that we stored the value under |
|
183 | - * @param string $key the key of the value, under which it was saved |
|
184 | - */ |
|
185 | - public function deleteAppValue($appName, $key) { |
|
186 | - \OC::$server->getAppConfig()->deleteKey($appName, $key); |
|
187 | - } |
|
188 | - |
|
189 | - /** |
|
190 | - * Removes all keys in appconfig belonging to the app |
|
191 | - * |
|
192 | - * @param string $appName the appName the configs are stored under |
|
193 | - */ |
|
194 | - public function deleteAppValues($appName) { |
|
195 | - \OC::$server->getAppConfig()->deleteApp($appName); |
|
196 | - } |
|
197 | - |
|
198 | - |
|
199 | - /** |
|
200 | - * Set a user defined value |
|
201 | - * |
|
202 | - * @param string $userId the userId of the user that we want to store the value under |
|
203 | - * @param string $appName the appName that we want to store the value under |
|
204 | - * @param string $key the key under which the value is being stored |
|
205 | - * @param string|float|int $value the value that you want to store |
|
206 | - * @param string $preCondition only update if the config value was previously the value passed as $preCondition |
|
207 | - * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met |
|
208 | - * @throws \UnexpectedValueException when trying to store an unexpected value |
|
209 | - */ |
|
210 | - public function setUserValue($userId, $appName, $key, $value, $preCondition = null) { |
|
211 | - if (!is_int($value) && !is_float($value) && !is_string($value)) { |
|
212 | - throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value'); |
|
213 | - } |
|
214 | - |
|
215 | - // TODO - FIXME |
|
216 | - $this->fixDIInit(); |
|
217 | - |
|
218 | - $prevValue = $this->getUserValue($userId, $appName, $key, null); |
|
219 | - |
|
220 | - if ($prevValue !== null) { |
|
221 | - if ($prevValue === (string)$value) { |
|
222 | - return; |
|
223 | - } else if ($preCondition !== null && $prevValue !== (string)$preCondition) { |
|
224 | - throw new PreConditionNotMetException(); |
|
225 | - } else { |
|
226 | - $qb = $this->connection->getQueryBuilder(); |
|
227 | - $qb->update('preferences') |
|
228 | - ->set('configvalue', $qb->createNamedParameter($value)) |
|
229 | - ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) |
|
230 | - ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName))) |
|
231 | - ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key))); |
|
232 | - $qb->execute(); |
|
233 | - |
|
234 | - $this->userCache[$userId][$appName][$key] = $value; |
|
235 | - return; |
|
236 | - } |
|
237 | - } |
|
238 | - |
|
239 | - $preconditionArray = []; |
|
240 | - if (isset($preCondition)) { |
|
241 | - $preconditionArray = [ |
|
242 | - 'configvalue' => $preCondition, |
|
243 | - ]; |
|
244 | - } |
|
245 | - |
|
246 | - $this->connection->setValues('preferences', [ |
|
247 | - 'userid' => $userId, |
|
248 | - 'appid' => $appName, |
|
249 | - 'configkey' => $key, |
|
250 | - ], [ |
|
251 | - 'configvalue' => $value, |
|
252 | - ], $preconditionArray); |
|
253 | - |
|
254 | - // only add to the cache if we already loaded data for the user |
|
255 | - if (isset($this->userCache[$userId])) { |
|
256 | - if (!isset($this->userCache[$userId][$appName])) { |
|
257 | - $this->userCache[$userId][$appName] = array(); |
|
258 | - } |
|
259 | - $this->userCache[$userId][$appName][$key] = $value; |
|
260 | - } |
|
261 | - } |
|
262 | - |
|
263 | - /** |
|
264 | - * Getting a user defined value |
|
265 | - * |
|
266 | - * @param string $userId the userId of the user that we want to store the value under |
|
267 | - * @param string $appName the appName that we stored the value under |
|
268 | - * @param string $key the key under which the value is being stored |
|
269 | - * @param mixed $default the default value to be returned if the value isn't set |
|
270 | - * @return string |
|
271 | - */ |
|
272 | - public function getUserValue($userId, $appName, $key, $default = '') { |
|
273 | - $data = $this->getUserValues($userId); |
|
274 | - if (isset($data[$appName]) and isset($data[$appName][$key])) { |
|
275 | - return $data[$appName][$key]; |
|
276 | - } else { |
|
277 | - return $default; |
|
278 | - } |
|
279 | - } |
|
280 | - |
|
281 | - /** |
|
282 | - * Get the keys of all stored by an app for the user |
|
283 | - * |
|
284 | - * @param string $userId the userId of the user that we want to store the value under |
|
285 | - * @param string $appName the appName that we stored the value under |
|
286 | - * @return string[] |
|
287 | - */ |
|
288 | - public function getUserKeys($userId, $appName) { |
|
289 | - $data = $this->getUserValues($userId); |
|
290 | - if (isset($data[$appName])) { |
|
291 | - return array_keys($data[$appName]); |
|
292 | - } else { |
|
293 | - return array(); |
|
294 | - } |
|
295 | - } |
|
296 | - |
|
297 | - /** |
|
298 | - * Delete a user value |
|
299 | - * |
|
300 | - * @param string $userId the userId of the user that we want to store the value under |
|
301 | - * @param string $appName the appName that we stored the value under |
|
302 | - * @param string $key the key under which the value is being stored |
|
303 | - */ |
|
304 | - public function deleteUserValue($userId, $appName, $key) { |
|
305 | - // TODO - FIXME |
|
306 | - $this->fixDIInit(); |
|
307 | - |
|
308 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
309 | - 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; |
|
310 | - $this->connection->executeUpdate($sql, array($userId, $appName, $key)); |
|
311 | - |
|
312 | - if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) { |
|
313 | - unset($this->userCache[$userId][$appName][$key]); |
|
314 | - } |
|
315 | - } |
|
316 | - |
|
317 | - /** |
|
318 | - * Delete all user values |
|
319 | - * |
|
320 | - * @param string $userId the userId of the user that we want to remove all values from |
|
321 | - */ |
|
322 | - public function deleteAllUserValues($userId) { |
|
323 | - // TODO - FIXME |
|
324 | - $this->fixDIInit(); |
|
325 | - |
|
326 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
327 | - 'WHERE `userid` = ?'; |
|
328 | - $this->connection->executeUpdate($sql, array($userId)); |
|
329 | - |
|
330 | - unset($this->userCache[$userId]); |
|
331 | - } |
|
332 | - |
|
333 | - /** |
|
334 | - * Delete all user related values of one app |
|
335 | - * |
|
336 | - * @param string $appName the appName of the app that we want to remove all values from |
|
337 | - */ |
|
338 | - public function deleteAppFromAllUsers($appName) { |
|
339 | - // TODO - FIXME |
|
340 | - $this->fixDIInit(); |
|
341 | - |
|
342 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
343 | - 'WHERE `appid` = ?'; |
|
344 | - $this->connection->executeUpdate($sql, array($appName)); |
|
345 | - |
|
346 | - foreach ($this->userCache as &$userCache) { |
|
347 | - unset($userCache[$appName]); |
|
348 | - } |
|
349 | - } |
|
350 | - |
|
351 | - /** |
|
352 | - * Returns all user configs sorted by app of one user |
|
353 | - * |
|
354 | - * @param string $userId the user ID to get the app configs from |
|
355 | - * @return array[] - 2 dimensional array with the following structure: |
|
356 | - * [ $appId => |
|
357 | - * [ $key => $value ] |
|
358 | - * ] |
|
359 | - */ |
|
360 | - private function getUserValues($userId) { |
|
361 | - if (isset($this->userCache[$userId])) { |
|
362 | - return $this->userCache[$userId]; |
|
363 | - } |
|
364 | - if ($userId === null || $userId === '') { |
|
365 | - $this->userCache[$userId]=array(); |
|
366 | - return $this->userCache[$userId]; |
|
367 | - } |
|
368 | - |
|
369 | - // TODO - FIXME |
|
370 | - $this->fixDIInit(); |
|
371 | - |
|
372 | - $data = array(); |
|
373 | - $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; |
|
374 | - $result = $this->connection->executeQuery($query, array($userId)); |
|
375 | - while ($row = $result->fetch()) { |
|
376 | - $appId = $row['appid']; |
|
377 | - if (!isset($data[$appId])) { |
|
378 | - $data[$appId] = array(); |
|
379 | - } |
|
380 | - $data[$appId][$row['configkey']] = $row['configvalue']; |
|
381 | - } |
|
382 | - $this->userCache[$userId] = $data; |
|
383 | - return $data; |
|
384 | - } |
|
385 | - |
|
386 | - /** |
|
387 | - * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs. |
|
388 | - * |
|
389 | - * @param string $appName app to get the value for |
|
390 | - * @param string $key the key to get the value for |
|
391 | - * @param array $userIds the user IDs to fetch the values for |
|
392 | - * @return array Mapped values: userId => value |
|
393 | - */ |
|
394 | - public function getUserValueForUsers($appName, $key, $userIds) { |
|
395 | - // TODO - FIXME |
|
396 | - $this->fixDIInit(); |
|
397 | - |
|
398 | - if (empty($userIds) || !is_array($userIds)) { |
|
399 | - return array(); |
|
400 | - } |
|
401 | - |
|
402 | - $chunkedUsers = array_chunk($userIds, 50, true); |
|
403 | - $placeholders50 = implode(',', array_fill(0, 50, '?')); |
|
404 | - |
|
405 | - $userValues = array(); |
|
406 | - foreach ($chunkedUsers as $chunk) { |
|
407 | - $queryParams = $chunk; |
|
408 | - // create [$app, $key, $chunkedUsers] |
|
409 | - array_unshift($queryParams, $key); |
|
410 | - array_unshift($queryParams, $appName); |
|
411 | - |
|
412 | - $placeholders = (sizeof($chunk) == 50) ? $placeholders50 : implode(',', array_fill(0, sizeof($chunk), '?')); |
|
413 | - |
|
414 | - $query = 'SELECT `userid`, `configvalue` ' . |
|
415 | - 'FROM `*PREFIX*preferences` ' . |
|
416 | - 'WHERE `appid` = ? AND `configkey` = ? ' . |
|
417 | - 'AND `userid` IN (' . $placeholders . ')'; |
|
418 | - $result = $this->connection->executeQuery($query, $queryParams); |
|
419 | - |
|
420 | - while ($row = $result->fetch()) { |
|
421 | - $userValues[$row['userid']] = $row['configvalue']; |
|
422 | - } |
|
423 | - } |
|
424 | - |
|
425 | - return $userValues; |
|
426 | - } |
|
427 | - |
|
428 | - /** |
|
429 | - * Determines the users that have the given value set for a specific app-key-pair |
|
430 | - * |
|
431 | - * @param string $appName the app to get the user for |
|
432 | - * @param string $key the key to get the user for |
|
433 | - * @param string $value the value to get the user for |
|
434 | - * @return array of user IDs |
|
435 | - */ |
|
436 | - public function getUsersForUserValue($appName, $key, $value) { |
|
437 | - // TODO - FIXME |
|
438 | - $this->fixDIInit(); |
|
439 | - |
|
440 | - $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . |
|
441 | - 'WHERE `appid` = ? AND `configkey` = ? '; |
|
442 | - |
|
443 | - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
444 | - //oracle hack: need to explicitly cast CLOB to CHAR for comparison |
|
445 | - $sql .= 'AND to_char(`configvalue`) = ?'; |
|
446 | - } else { |
|
447 | - $sql .= 'AND `configvalue` = ?'; |
|
448 | - } |
|
449 | - |
|
450 | - $result = $this->connection->executeQuery($sql, array($appName, $key, $value)); |
|
451 | - |
|
452 | - $userIDs = array(); |
|
453 | - while ($row = $result->fetch()) { |
|
454 | - $userIDs[] = $row['userid']; |
|
455 | - } |
|
456 | - |
|
457 | - return $userIDs; |
|
458 | - } |
|
459 | - |
|
460 | - public function getSystemConfig() { |
|
461 | - return $this->systemConfig; |
|
462 | - } |
|
40 | + /** @var SystemConfig */ |
|
41 | + private $systemConfig; |
|
42 | + |
|
43 | + /** @var IDBConnection */ |
|
44 | + private $connection; |
|
45 | + |
|
46 | + /** |
|
47 | + * 3 dimensional array with the following structure: |
|
48 | + * [ $userId => |
|
49 | + * [ $appId => |
|
50 | + * [ $key => $value ] |
|
51 | + * ] |
|
52 | + * ] |
|
53 | + * |
|
54 | + * database table: preferences |
|
55 | + * |
|
56 | + * methods that use this: |
|
57 | + * - setUserValue |
|
58 | + * - getUserValue |
|
59 | + * - getUserKeys |
|
60 | + * - deleteUserValue |
|
61 | + * - deleteAllUserValues |
|
62 | + * - deleteAppFromAllUsers |
|
63 | + * |
|
64 | + * @var CappedMemoryCache $userCache |
|
65 | + */ |
|
66 | + private $userCache; |
|
67 | + |
|
68 | + /** |
|
69 | + * @param SystemConfig $systemConfig |
|
70 | + */ |
|
71 | + public function __construct(SystemConfig $systemConfig) { |
|
72 | + $this->userCache = new CappedMemoryCache(); |
|
73 | + $this->systemConfig = $systemConfig; |
|
74 | + } |
|
75 | + |
|
76 | + /** |
|
77 | + * TODO - FIXME This fixes an issue with base.php that cause cyclic |
|
78 | + * dependencies, especially with autoconfig setup |
|
79 | + * |
|
80 | + * Replace this by properly injected database connection. Currently the |
|
81 | + * base.php triggers the getDatabaseConnection too early which causes in |
|
82 | + * autoconfig setup case a too early distributed database connection and |
|
83 | + * the autoconfig then needs to reinit all already initialized dependencies |
|
84 | + * that use the database connection. |
|
85 | + * |
|
86 | + * otherwise a SQLite database is created in the wrong directory |
|
87 | + * because the database connection was created with an uninitialized config |
|
88 | + */ |
|
89 | + private function fixDIInit() { |
|
90 | + if($this->connection === null) { |
|
91 | + $this->connection = \OC::$server->getDatabaseConnection(); |
|
92 | + } |
|
93 | + } |
|
94 | + |
|
95 | + /** |
|
96 | + * Sets and deletes system wide values |
|
97 | + * |
|
98 | + * @param array $configs Associative array with `key => value` pairs |
|
99 | + * If value is null, the config key will be deleted |
|
100 | + */ |
|
101 | + public function setSystemValues(array $configs) { |
|
102 | + $this->systemConfig->setValues($configs); |
|
103 | + } |
|
104 | + |
|
105 | + /** |
|
106 | + * Sets a new system wide value |
|
107 | + * |
|
108 | + * @param string $key the key of the value, under which will be saved |
|
109 | + * @param mixed $value the value that should be stored |
|
110 | + */ |
|
111 | + public function setSystemValue($key, $value) { |
|
112 | + $this->systemConfig->setValue($key, $value); |
|
113 | + } |
|
114 | + |
|
115 | + /** |
|
116 | + * Looks up a system wide defined value |
|
117 | + * |
|
118 | + * @param string $key the key of the value, under which it was saved |
|
119 | + * @param mixed $default the default value to be returned if the value isn't set |
|
120 | + * @return mixed the value or $default |
|
121 | + */ |
|
122 | + public function getSystemValue($key, $default = '') { |
|
123 | + return $this->systemConfig->getValue($key, $default); |
|
124 | + } |
|
125 | + |
|
126 | + /** |
|
127 | + * Looks up a system wide defined value and filters out sensitive data |
|
128 | + * |
|
129 | + * @param string $key the key of the value, under which it was saved |
|
130 | + * @param mixed $default the default value to be returned if the value isn't set |
|
131 | + * @return mixed the value or $default |
|
132 | + */ |
|
133 | + public function getFilteredSystemValue($key, $default = '') { |
|
134 | + return $this->systemConfig->getFilteredValue($key, $default); |
|
135 | + } |
|
136 | + |
|
137 | + /** |
|
138 | + * Delete a system wide defined value |
|
139 | + * |
|
140 | + * @param string $key the key of the value, under which it was saved |
|
141 | + */ |
|
142 | + public function deleteSystemValue($key) { |
|
143 | + $this->systemConfig->deleteValue($key); |
|
144 | + } |
|
145 | + |
|
146 | + /** |
|
147 | + * Get all keys stored for an app |
|
148 | + * |
|
149 | + * @param string $appName the appName that we stored the value under |
|
150 | + * @return string[] the keys stored for the app |
|
151 | + */ |
|
152 | + public function getAppKeys($appName) { |
|
153 | + return \OC::$server->getAppConfig()->getKeys($appName); |
|
154 | + } |
|
155 | + |
|
156 | + /** |
|
157 | + * Writes a new app wide value |
|
158 | + * |
|
159 | + * @param string $appName the appName that we want to store the value under |
|
160 | + * @param string $key the key of the value, under which will be saved |
|
161 | + * @param string|float|int $value the value that should be stored |
|
162 | + */ |
|
163 | + public function setAppValue($appName, $key, $value) { |
|
164 | + \OC::$server->getAppConfig()->setValue($appName, $key, $value); |
|
165 | + } |
|
166 | + |
|
167 | + /** |
|
168 | + * Looks up an app wide defined value |
|
169 | + * |
|
170 | + * @param string $appName the appName that we stored the value under |
|
171 | + * @param string $key the key of the value, under which it was saved |
|
172 | + * @param string $default the default value to be returned if the value isn't set |
|
173 | + * @return string the saved value |
|
174 | + */ |
|
175 | + public function getAppValue($appName, $key, $default = '') { |
|
176 | + return \OC::$server->getAppConfig()->getValue($appName, $key, $default); |
|
177 | + } |
|
178 | + |
|
179 | + /** |
|
180 | + * Delete an app wide defined value |
|
181 | + * |
|
182 | + * @param string $appName the appName that we stored the value under |
|
183 | + * @param string $key the key of the value, under which it was saved |
|
184 | + */ |
|
185 | + public function deleteAppValue($appName, $key) { |
|
186 | + \OC::$server->getAppConfig()->deleteKey($appName, $key); |
|
187 | + } |
|
188 | + |
|
189 | + /** |
|
190 | + * Removes all keys in appconfig belonging to the app |
|
191 | + * |
|
192 | + * @param string $appName the appName the configs are stored under |
|
193 | + */ |
|
194 | + public function deleteAppValues($appName) { |
|
195 | + \OC::$server->getAppConfig()->deleteApp($appName); |
|
196 | + } |
|
197 | + |
|
198 | + |
|
199 | + /** |
|
200 | + * Set a user defined value |
|
201 | + * |
|
202 | + * @param string $userId the userId of the user that we want to store the value under |
|
203 | + * @param string $appName the appName that we want to store the value under |
|
204 | + * @param string $key the key under which the value is being stored |
|
205 | + * @param string|float|int $value the value that you want to store |
|
206 | + * @param string $preCondition only update if the config value was previously the value passed as $preCondition |
|
207 | + * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met |
|
208 | + * @throws \UnexpectedValueException when trying to store an unexpected value |
|
209 | + */ |
|
210 | + public function setUserValue($userId, $appName, $key, $value, $preCondition = null) { |
|
211 | + if (!is_int($value) && !is_float($value) && !is_string($value)) { |
|
212 | + throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value'); |
|
213 | + } |
|
214 | + |
|
215 | + // TODO - FIXME |
|
216 | + $this->fixDIInit(); |
|
217 | + |
|
218 | + $prevValue = $this->getUserValue($userId, $appName, $key, null); |
|
219 | + |
|
220 | + if ($prevValue !== null) { |
|
221 | + if ($prevValue === (string)$value) { |
|
222 | + return; |
|
223 | + } else if ($preCondition !== null && $prevValue !== (string)$preCondition) { |
|
224 | + throw new PreConditionNotMetException(); |
|
225 | + } else { |
|
226 | + $qb = $this->connection->getQueryBuilder(); |
|
227 | + $qb->update('preferences') |
|
228 | + ->set('configvalue', $qb->createNamedParameter($value)) |
|
229 | + ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) |
|
230 | + ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName))) |
|
231 | + ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key))); |
|
232 | + $qb->execute(); |
|
233 | + |
|
234 | + $this->userCache[$userId][$appName][$key] = $value; |
|
235 | + return; |
|
236 | + } |
|
237 | + } |
|
238 | + |
|
239 | + $preconditionArray = []; |
|
240 | + if (isset($preCondition)) { |
|
241 | + $preconditionArray = [ |
|
242 | + 'configvalue' => $preCondition, |
|
243 | + ]; |
|
244 | + } |
|
245 | + |
|
246 | + $this->connection->setValues('preferences', [ |
|
247 | + 'userid' => $userId, |
|
248 | + 'appid' => $appName, |
|
249 | + 'configkey' => $key, |
|
250 | + ], [ |
|
251 | + 'configvalue' => $value, |
|
252 | + ], $preconditionArray); |
|
253 | + |
|
254 | + // only add to the cache if we already loaded data for the user |
|
255 | + if (isset($this->userCache[$userId])) { |
|
256 | + if (!isset($this->userCache[$userId][$appName])) { |
|
257 | + $this->userCache[$userId][$appName] = array(); |
|
258 | + } |
|
259 | + $this->userCache[$userId][$appName][$key] = $value; |
|
260 | + } |
|
261 | + } |
|
262 | + |
|
263 | + /** |
|
264 | + * Getting a user defined value |
|
265 | + * |
|
266 | + * @param string $userId the userId of the user that we want to store the value under |
|
267 | + * @param string $appName the appName that we stored the value under |
|
268 | + * @param string $key the key under which the value is being stored |
|
269 | + * @param mixed $default the default value to be returned if the value isn't set |
|
270 | + * @return string |
|
271 | + */ |
|
272 | + public function getUserValue($userId, $appName, $key, $default = '') { |
|
273 | + $data = $this->getUserValues($userId); |
|
274 | + if (isset($data[$appName]) and isset($data[$appName][$key])) { |
|
275 | + return $data[$appName][$key]; |
|
276 | + } else { |
|
277 | + return $default; |
|
278 | + } |
|
279 | + } |
|
280 | + |
|
281 | + /** |
|
282 | + * Get the keys of all stored by an app for the user |
|
283 | + * |
|
284 | + * @param string $userId the userId of the user that we want to store the value under |
|
285 | + * @param string $appName the appName that we stored the value under |
|
286 | + * @return string[] |
|
287 | + */ |
|
288 | + public function getUserKeys($userId, $appName) { |
|
289 | + $data = $this->getUserValues($userId); |
|
290 | + if (isset($data[$appName])) { |
|
291 | + return array_keys($data[$appName]); |
|
292 | + } else { |
|
293 | + return array(); |
|
294 | + } |
|
295 | + } |
|
296 | + |
|
297 | + /** |
|
298 | + * Delete a user value |
|
299 | + * |
|
300 | + * @param string $userId the userId of the user that we want to store the value under |
|
301 | + * @param string $appName the appName that we stored the value under |
|
302 | + * @param string $key the key under which the value is being stored |
|
303 | + */ |
|
304 | + public function deleteUserValue($userId, $appName, $key) { |
|
305 | + // TODO - FIXME |
|
306 | + $this->fixDIInit(); |
|
307 | + |
|
308 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
309 | + 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; |
|
310 | + $this->connection->executeUpdate($sql, array($userId, $appName, $key)); |
|
311 | + |
|
312 | + if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) { |
|
313 | + unset($this->userCache[$userId][$appName][$key]); |
|
314 | + } |
|
315 | + } |
|
316 | + |
|
317 | + /** |
|
318 | + * Delete all user values |
|
319 | + * |
|
320 | + * @param string $userId the userId of the user that we want to remove all values from |
|
321 | + */ |
|
322 | + public function deleteAllUserValues($userId) { |
|
323 | + // TODO - FIXME |
|
324 | + $this->fixDIInit(); |
|
325 | + |
|
326 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
327 | + 'WHERE `userid` = ?'; |
|
328 | + $this->connection->executeUpdate($sql, array($userId)); |
|
329 | + |
|
330 | + unset($this->userCache[$userId]); |
|
331 | + } |
|
332 | + |
|
333 | + /** |
|
334 | + * Delete all user related values of one app |
|
335 | + * |
|
336 | + * @param string $appName the appName of the app that we want to remove all values from |
|
337 | + */ |
|
338 | + public function deleteAppFromAllUsers($appName) { |
|
339 | + // TODO - FIXME |
|
340 | + $this->fixDIInit(); |
|
341 | + |
|
342 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
343 | + 'WHERE `appid` = ?'; |
|
344 | + $this->connection->executeUpdate($sql, array($appName)); |
|
345 | + |
|
346 | + foreach ($this->userCache as &$userCache) { |
|
347 | + unset($userCache[$appName]); |
|
348 | + } |
|
349 | + } |
|
350 | + |
|
351 | + /** |
|
352 | + * Returns all user configs sorted by app of one user |
|
353 | + * |
|
354 | + * @param string $userId the user ID to get the app configs from |
|
355 | + * @return array[] - 2 dimensional array with the following structure: |
|
356 | + * [ $appId => |
|
357 | + * [ $key => $value ] |
|
358 | + * ] |
|
359 | + */ |
|
360 | + private function getUserValues($userId) { |
|
361 | + if (isset($this->userCache[$userId])) { |
|
362 | + return $this->userCache[$userId]; |
|
363 | + } |
|
364 | + if ($userId === null || $userId === '') { |
|
365 | + $this->userCache[$userId]=array(); |
|
366 | + return $this->userCache[$userId]; |
|
367 | + } |
|
368 | + |
|
369 | + // TODO - FIXME |
|
370 | + $this->fixDIInit(); |
|
371 | + |
|
372 | + $data = array(); |
|
373 | + $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; |
|
374 | + $result = $this->connection->executeQuery($query, array($userId)); |
|
375 | + while ($row = $result->fetch()) { |
|
376 | + $appId = $row['appid']; |
|
377 | + if (!isset($data[$appId])) { |
|
378 | + $data[$appId] = array(); |
|
379 | + } |
|
380 | + $data[$appId][$row['configkey']] = $row['configvalue']; |
|
381 | + } |
|
382 | + $this->userCache[$userId] = $data; |
|
383 | + return $data; |
|
384 | + } |
|
385 | + |
|
386 | + /** |
|
387 | + * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs. |
|
388 | + * |
|
389 | + * @param string $appName app to get the value for |
|
390 | + * @param string $key the key to get the value for |
|
391 | + * @param array $userIds the user IDs to fetch the values for |
|
392 | + * @return array Mapped values: userId => value |
|
393 | + */ |
|
394 | + public function getUserValueForUsers($appName, $key, $userIds) { |
|
395 | + // TODO - FIXME |
|
396 | + $this->fixDIInit(); |
|
397 | + |
|
398 | + if (empty($userIds) || !is_array($userIds)) { |
|
399 | + return array(); |
|
400 | + } |
|
401 | + |
|
402 | + $chunkedUsers = array_chunk($userIds, 50, true); |
|
403 | + $placeholders50 = implode(',', array_fill(0, 50, '?')); |
|
404 | + |
|
405 | + $userValues = array(); |
|
406 | + foreach ($chunkedUsers as $chunk) { |
|
407 | + $queryParams = $chunk; |
|
408 | + // create [$app, $key, $chunkedUsers] |
|
409 | + array_unshift($queryParams, $key); |
|
410 | + array_unshift($queryParams, $appName); |
|
411 | + |
|
412 | + $placeholders = (sizeof($chunk) == 50) ? $placeholders50 : implode(',', array_fill(0, sizeof($chunk), '?')); |
|
413 | + |
|
414 | + $query = 'SELECT `userid`, `configvalue` ' . |
|
415 | + 'FROM `*PREFIX*preferences` ' . |
|
416 | + 'WHERE `appid` = ? AND `configkey` = ? ' . |
|
417 | + 'AND `userid` IN (' . $placeholders . ')'; |
|
418 | + $result = $this->connection->executeQuery($query, $queryParams); |
|
419 | + |
|
420 | + while ($row = $result->fetch()) { |
|
421 | + $userValues[$row['userid']] = $row['configvalue']; |
|
422 | + } |
|
423 | + } |
|
424 | + |
|
425 | + return $userValues; |
|
426 | + } |
|
427 | + |
|
428 | + /** |
|
429 | + * Determines the users that have the given value set for a specific app-key-pair |
|
430 | + * |
|
431 | + * @param string $appName the app to get the user for |
|
432 | + * @param string $key the key to get the user for |
|
433 | + * @param string $value the value to get the user for |
|
434 | + * @return array of user IDs |
|
435 | + */ |
|
436 | + public function getUsersForUserValue($appName, $key, $value) { |
|
437 | + // TODO - FIXME |
|
438 | + $this->fixDIInit(); |
|
439 | + |
|
440 | + $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . |
|
441 | + 'WHERE `appid` = ? AND `configkey` = ? '; |
|
442 | + |
|
443 | + if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
444 | + //oracle hack: need to explicitly cast CLOB to CHAR for comparison |
|
445 | + $sql .= 'AND to_char(`configvalue`) = ?'; |
|
446 | + } else { |
|
447 | + $sql .= 'AND `configvalue` = ?'; |
|
448 | + } |
|
449 | + |
|
450 | + $result = $this->connection->executeQuery($sql, array($appName, $key, $value)); |
|
451 | + |
|
452 | + $userIDs = array(); |
|
453 | + while ($row = $result->fetch()) { |
|
454 | + $userIDs[] = $row['userid']; |
|
455 | + } |
|
456 | + |
|
457 | + return $userIDs; |
|
458 | + } |
|
459 | + |
|
460 | + public function getSystemConfig() { |
|
461 | + return $this->systemConfig; |
|
462 | + } |
|
463 | 463 | } |
@@ -87,7 +87,7 @@ discard block |
||
87 | 87 | * because the database connection was created with an uninitialized config |
88 | 88 | */ |
89 | 89 | private function fixDIInit() { |
90 | - if($this->connection === null) { |
|
90 | + if ($this->connection === null) { |
|
91 | 91 | $this->connection = \OC::$server->getDatabaseConnection(); |
92 | 92 | } |
93 | 93 | } |
@@ -218,9 +218,9 @@ discard block |
||
218 | 218 | $prevValue = $this->getUserValue($userId, $appName, $key, null); |
219 | 219 | |
220 | 220 | if ($prevValue !== null) { |
221 | - if ($prevValue === (string)$value) { |
|
221 | + if ($prevValue === (string) $value) { |
|
222 | 222 | return; |
223 | - } else if ($preCondition !== null && $prevValue !== (string)$preCondition) { |
|
223 | + } else if ($preCondition !== null && $prevValue !== (string) $preCondition) { |
|
224 | 224 | throw new PreConditionNotMetException(); |
225 | 225 | } else { |
226 | 226 | $qb = $this->connection->getQueryBuilder(); |
@@ -305,7 +305,7 @@ discard block |
||
305 | 305 | // TODO - FIXME |
306 | 306 | $this->fixDIInit(); |
307 | 307 | |
308 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
308 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
309 | 309 | 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; |
310 | 310 | $this->connection->executeUpdate($sql, array($userId, $appName, $key)); |
311 | 311 | |
@@ -323,7 +323,7 @@ discard block |
||
323 | 323 | // TODO - FIXME |
324 | 324 | $this->fixDIInit(); |
325 | 325 | |
326 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
326 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
327 | 327 | 'WHERE `userid` = ?'; |
328 | 328 | $this->connection->executeUpdate($sql, array($userId)); |
329 | 329 | |
@@ -339,7 +339,7 @@ discard block |
||
339 | 339 | // TODO - FIXME |
340 | 340 | $this->fixDIInit(); |
341 | 341 | |
342 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
342 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
343 | 343 | 'WHERE `appid` = ?'; |
344 | 344 | $this->connection->executeUpdate($sql, array($appName)); |
345 | 345 | |
@@ -362,7 +362,7 @@ discard block |
||
362 | 362 | return $this->userCache[$userId]; |
363 | 363 | } |
364 | 364 | if ($userId === null || $userId === '') { |
365 | - $this->userCache[$userId]=array(); |
|
365 | + $this->userCache[$userId] = array(); |
|
366 | 366 | return $this->userCache[$userId]; |
367 | 367 | } |
368 | 368 | |
@@ -409,12 +409,12 @@ discard block |
||
409 | 409 | array_unshift($queryParams, $key); |
410 | 410 | array_unshift($queryParams, $appName); |
411 | 411 | |
412 | - $placeholders = (sizeof($chunk) == 50) ? $placeholders50 : implode(',', array_fill(0, sizeof($chunk), '?')); |
|
412 | + $placeholders = (sizeof($chunk) == 50) ? $placeholders50 : implode(',', array_fill(0, sizeof($chunk), '?')); |
|
413 | 413 | |
414 | - $query = 'SELECT `userid`, `configvalue` ' . |
|
415 | - 'FROM `*PREFIX*preferences` ' . |
|
416 | - 'WHERE `appid` = ? AND `configkey` = ? ' . |
|
417 | - 'AND `userid` IN (' . $placeholders . ')'; |
|
414 | + $query = 'SELECT `userid`, `configvalue` '. |
|
415 | + 'FROM `*PREFIX*preferences` '. |
|
416 | + 'WHERE `appid` = ? AND `configkey` = ? '. |
|
417 | + 'AND `userid` IN ('.$placeholders.')'; |
|
418 | 418 | $result = $this->connection->executeQuery($query, $queryParams); |
419 | 419 | |
420 | 420 | while ($row = $result->fetch()) { |
@@ -437,10 +437,10 @@ discard block |
||
437 | 437 | // TODO - FIXME |
438 | 438 | $this->fixDIInit(); |
439 | 439 | |
440 | - $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . |
|
440 | + $sql = 'SELECT `userid` FROM `*PREFIX*preferences` '. |
|
441 | 441 | 'WHERE `appid` = ? AND `configkey` = ? '; |
442 | 442 | |
443 | - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
443 | + if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
444 | 444 | //oracle hack: need to explicitly cast CLOB to CHAR for comparison |
445 | 445 | $sql .= 'AND to_char(`configvalue`) = ?'; |
446 | 446 | } else { |
@@ -296,6 +296,9 @@ |
||
296 | 296 | } |
297 | 297 | } |
298 | 298 | |
299 | + /** |
|
300 | + * @param string $name |
|
301 | + */ |
|
299 | 302 | private function buildReason($name, $errorCode) { |
300 | 303 | if (isset($this->errorMessages[$errorCode])) { |
301 | 304 | $desc = $this->list->getDescription($errorCode, $name); |
@@ -29,280 +29,280 @@ |
||
29 | 29 | use PhpParser\NodeVisitorAbstract; |
30 | 30 | |
31 | 31 | class NodeVisitor extends NodeVisitorAbstract { |
32 | - /** @var ICheck */ |
|
33 | - protected $list; |
|
34 | - |
|
35 | - /** @var string */ |
|
36 | - protected $blackListDescription; |
|
37 | - /** @var string[] */ |
|
38 | - protected $blackListedClassNames; |
|
39 | - /** @var string[] */ |
|
40 | - protected $blackListedConstants; |
|
41 | - /** @var string[] */ |
|
42 | - protected $blackListedFunctions; |
|
43 | - /** @var string[] */ |
|
44 | - protected $blackListedMethods; |
|
45 | - /** @var bool */ |
|
46 | - protected $checkEqualOperatorUsage; |
|
47 | - /** @var string[] */ |
|
48 | - protected $errorMessages; |
|
49 | - |
|
50 | - /** |
|
51 | - * @param ICheck $list |
|
52 | - */ |
|
53 | - public function __construct(ICheck $list) { |
|
54 | - $this->list = $list; |
|
55 | - |
|
56 | - $this->blackListedClassNames = []; |
|
57 | - foreach ($list->getClasses() as $class => $blackListInfo) { |
|
58 | - if (is_numeric($class) && is_string($blackListInfo)) { |
|
59 | - $class = $blackListInfo; |
|
60 | - $blackListInfo = null; |
|
61 | - } |
|
62 | - |
|
63 | - $class = strtolower($class); |
|
64 | - $this->blackListedClassNames[$class] = $class; |
|
65 | - } |
|
66 | - |
|
67 | - $this->blackListedConstants = []; |
|
68 | - foreach ($list->getConstants() as $constantName => $blackListInfo) { |
|
69 | - $constantName = strtolower($constantName); |
|
70 | - $this->blackListedConstants[$constantName] = $constantName; |
|
71 | - } |
|
72 | - |
|
73 | - $this->blackListedFunctions = []; |
|
74 | - foreach ($list->getFunctions() as $functionName => $blackListInfo) { |
|
75 | - $functionName = strtolower($functionName); |
|
76 | - $this->blackListedFunctions[$functionName] = $functionName; |
|
77 | - } |
|
78 | - |
|
79 | - $this->blackListedMethods = []; |
|
80 | - foreach ($list->getMethods() as $functionName => $blackListInfo) { |
|
81 | - $functionName = strtolower($functionName); |
|
82 | - $this->blackListedMethods[$functionName] = $functionName; |
|
83 | - } |
|
84 | - |
|
85 | - $this->checkEqualOperatorUsage = $list->checkStrongComparisons(); |
|
86 | - |
|
87 | - $this->errorMessages = [ |
|
88 | - CodeChecker::CLASS_EXTENDS_NOT_ALLOWED => "%s class must not be extended", |
|
89 | - CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED => "%s interface must not be implemented", |
|
90 | - CodeChecker::STATIC_CALL_NOT_ALLOWED => "Static method of %s class must not be called", |
|
91 | - CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED => "Constant of %s class must not not be fetched", |
|
92 | - CodeChecker::CLASS_NEW_NOT_ALLOWED => "%s class must not be instantiated", |
|
93 | - CodeChecker::CLASS_USE_NOT_ALLOWED => "%s class must not be imported with a use statement", |
|
94 | - CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED => "Method of %s class must not be called", |
|
95 | - |
|
96 | - CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED => "is discouraged", |
|
97 | - ]; |
|
98 | - } |
|
99 | - |
|
100 | - /** @var array */ |
|
101 | - public $errors = []; |
|
102 | - |
|
103 | - public function enterNode(Node $node) { |
|
104 | - if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) { |
|
105 | - $this->errors[]= [ |
|
106 | - 'disallowedToken' => '==', |
|
107 | - 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
|
108 | - 'line' => $node->getLine(), |
|
109 | - 'reason' => $this->buildReason('==', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED) |
|
110 | - ]; |
|
111 | - } |
|
112 | - if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) { |
|
113 | - $this->errors[]= [ |
|
114 | - 'disallowedToken' => '!=', |
|
115 | - 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
|
116 | - 'line' => $node->getLine(), |
|
117 | - 'reason' => $this->buildReason('!=', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED) |
|
118 | - ]; |
|
119 | - } |
|
120 | - if ($node instanceof Node\Stmt\Class_) { |
|
121 | - if (!is_null($node->extends)) { |
|
122 | - $this->checkBlackList($node->extends->toString(), CodeChecker::CLASS_EXTENDS_NOT_ALLOWED, $node); |
|
123 | - } |
|
124 | - foreach ($node->implements as $implements) { |
|
125 | - $this->checkBlackList($implements->toString(), CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED, $node); |
|
126 | - } |
|
127 | - } |
|
128 | - if ($node instanceof Node\Expr\StaticCall) { |
|
129 | - if (!is_null($node->class)) { |
|
130 | - if ($node->class instanceof Name) { |
|
131 | - $this->checkBlackList($node->class->toString(), CodeChecker::STATIC_CALL_NOT_ALLOWED, $node); |
|
132 | - |
|
133 | - $this->checkBlackListFunction($node->class->toString(), $node->name, $node); |
|
134 | - $this->checkBlackListMethod($node->class->toString(), $node->name, $node); |
|
135 | - } |
|
136 | - |
|
137 | - if ($node->class instanceof Node\Expr\Variable) { |
|
138 | - /** |
|
139 | - * TODO: find a way to detect something like this: |
|
140 | - * $c = "OC_API"; |
|
141 | - * $n = $c::call(); |
|
142 | - */ |
|
143 | - // $this->checkBlackListMethod($node->class->..., $node->name, $node); |
|
144 | - } |
|
145 | - } |
|
146 | - } |
|
147 | - if ($node instanceof Node\Expr\MethodCall) { |
|
148 | - if (!is_null($node->var)) { |
|
149 | - if ($node->var instanceof Node\Expr\Variable) { |
|
150 | - /** |
|
151 | - * TODO: find a way to detect something like this: |
|
152 | - * $c = new OC_API(); |
|
153 | - * $n = $c::call(); |
|
154 | - * $n = $c->call(); |
|
155 | - */ |
|
156 | - // $this->checkBlackListMethod($node->var->..., $node->name, $node); |
|
157 | - } |
|
158 | - } |
|
159 | - } |
|
160 | - if ($node instanceof Node\Expr\ClassConstFetch) { |
|
161 | - if (!is_null($node->class)) { |
|
162 | - if ($node->class instanceof Name) { |
|
163 | - $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, $node); |
|
164 | - } |
|
165 | - if ($node->class instanceof Node\Expr\Variable) { |
|
166 | - /** |
|
167 | - * TODO: find a way to detect something like this: |
|
168 | - * $c = "OC_API"; |
|
169 | - * $n = $i::ADMIN_AUTH; |
|
170 | - */ |
|
171 | - } else { |
|
172 | - $this->checkBlackListConstant($node->class->toString(), $node->name, $node); |
|
173 | - } |
|
174 | - } |
|
175 | - } |
|
176 | - if ($node instanceof Node\Expr\New_) { |
|
177 | - if (!is_null($node->class)) { |
|
178 | - if ($node->class instanceof Name) { |
|
179 | - $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_NEW_NOT_ALLOWED, $node); |
|
180 | - } |
|
181 | - if ($node->class instanceof Node\Expr\Variable) { |
|
182 | - /** |
|
183 | - * TODO: find a way to detect something like this: |
|
184 | - * $c = "OC_API"; |
|
185 | - * $n = new $i; |
|
186 | - */ |
|
187 | - } |
|
188 | - } |
|
189 | - } |
|
190 | - if ($node instanceof Node\Stmt\UseUse) { |
|
191 | - $this->checkBlackList($node->name->toString(), CodeChecker::CLASS_USE_NOT_ALLOWED, $node); |
|
192 | - if ($node->alias) { |
|
193 | - $this->addUseNameToBlackList($node->name->toString(), $node->alias); |
|
194 | - } else { |
|
195 | - $this->addUseNameToBlackList($node->name->toString(), $node->name->getLast()); |
|
196 | - } |
|
197 | - } |
|
198 | - } |
|
199 | - |
|
200 | - /** |
|
201 | - * Check whether an alias was introduced for a namespace of a blacklisted class |
|
202 | - * |
|
203 | - * Example: |
|
204 | - * - Blacklist entry: OCP\AppFramework\IApi |
|
205 | - * - Name: OCP\AppFramework |
|
206 | - * - Alias: OAF |
|
207 | - * => new blacklist entry: OAF\IApi |
|
208 | - * |
|
209 | - * @param string $name |
|
210 | - * @param string $alias |
|
211 | - */ |
|
212 | - private function addUseNameToBlackList($name, $alias) { |
|
213 | - $name = strtolower($name); |
|
214 | - $alias = strtolower($alias); |
|
215 | - |
|
216 | - foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) { |
|
217 | - if (strpos($blackListedClassName, $name . '\\') === 0) { |
|
218 | - $aliasedClassName = str_replace($name, $alias, $blackListedClassName); |
|
219 | - $this->blackListedClassNames[$aliasedClassName] = $blackListedClassName; |
|
220 | - } |
|
221 | - } |
|
222 | - |
|
223 | - foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) { |
|
224 | - if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) { |
|
225 | - $aliasedConstantName = str_replace($name, $alias, $blackListedConstant); |
|
226 | - $this->blackListedConstants[$aliasedConstantName] = $blackListedConstant; |
|
227 | - } |
|
228 | - } |
|
229 | - |
|
230 | - foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) { |
|
231 | - if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) { |
|
232 | - $aliasedFunctionName = str_replace($name, $alias, $blackListedFunction); |
|
233 | - $this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction; |
|
234 | - } |
|
235 | - } |
|
236 | - |
|
237 | - foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) { |
|
238 | - if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) { |
|
239 | - $aliasedMethodName = str_replace($name, $alias, $blackListedMethod); |
|
240 | - $this->blackListedMethods[$aliasedMethodName] = $blackListedMethod; |
|
241 | - } |
|
242 | - } |
|
243 | - } |
|
244 | - |
|
245 | - private function checkBlackList($name, $errorCode, Node $node) { |
|
246 | - $lowerName = strtolower($name); |
|
247 | - |
|
248 | - if (isset($this->blackListedClassNames[$lowerName])) { |
|
249 | - $this->errors[]= [ |
|
250 | - 'disallowedToken' => $name, |
|
251 | - 'errorCode' => $errorCode, |
|
252 | - 'line' => $node->getLine(), |
|
253 | - 'reason' => $this->buildReason($this->blackListedClassNames[$lowerName], $errorCode) |
|
254 | - ]; |
|
255 | - } |
|
256 | - } |
|
257 | - |
|
258 | - private function checkBlackListConstant($class, $constantName, Node $node) { |
|
259 | - $name = $class . '::' . $constantName; |
|
260 | - $lowerName = strtolower($name); |
|
261 | - |
|
262 | - if (isset($this->blackListedConstants[$lowerName])) { |
|
263 | - $this->errors[]= [ |
|
264 | - 'disallowedToken' => $name, |
|
265 | - 'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, |
|
266 | - 'line' => $node->getLine(), |
|
267 | - 'reason' => $this->buildReason($this->blackListedConstants[$lowerName], CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED) |
|
268 | - ]; |
|
269 | - } |
|
270 | - } |
|
271 | - |
|
272 | - private function checkBlackListFunction($class, $functionName, Node $node) { |
|
273 | - $name = $class . '::' . $functionName; |
|
274 | - $lowerName = strtolower($name); |
|
275 | - |
|
276 | - if (isset($this->blackListedFunctions[$lowerName])) { |
|
277 | - $this->errors[]= [ |
|
278 | - 'disallowedToken' => $name, |
|
279 | - 'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED, |
|
280 | - 'line' => $node->getLine(), |
|
281 | - 'reason' => $this->buildReason($this->blackListedFunctions[$lowerName], CodeChecker::STATIC_CALL_NOT_ALLOWED) |
|
282 | - ]; |
|
283 | - } |
|
284 | - } |
|
285 | - |
|
286 | - private function checkBlackListMethod($class, $functionName, Node $node) { |
|
287 | - $name = $class . '::' . $functionName; |
|
288 | - $lowerName = strtolower($name); |
|
289 | - |
|
290 | - if (isset($this->blackListedMethods[$lowerName])) { |
|
291 | - $this->errors[]= [ |
|
292 | - 'disallowedToken' => $name, |
|
293 | - 'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED, |
|
294 | - 'line' => $node->getLine(), |
|
295 | - 'reason' => $this->buildReason($this->blackListedMethods[$lowerName], CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED) |
|
296 | - ]; |
|
297 | - } |
|
298 | - } |
|
299 | - |
|
300 | - private function buildReason($name, $errorCode) { |
|
301 | - if (isset($this->errorMessages[$errorCode])) { |
|
302 | - $desc = $this->list->getDescription($errorCode, $name); |
|
303 | - return sprintf($this->errorMessages[$errorCode], $desc); |
|
304 | - } |
|
305 | - |
|
306 | - return "$name usage not allowed - error: $errorCode"; |
|
307 | - } |
|
32 | + /** @var ICheck */ |
|
33 | + protected $list; |
|
34 | + |
|
35 | + /** @var string */ |
|
36 | + protected $blackListDescription; |
|
37 | + /** @var string[] */ |
|
38 | + protected $blackListedClassNames; |
|
39 | + /** @var string[] */ |
|
40 | + protected $blackListedConstants; |
|
41 | + /** @var string[] */ |
|
42 | + protected $blackListedFunctions; |
|
43 | + /** @var string[] */ |
|
44 | + protected $blackListedMethods; |
|
45 | + /** @var bool */ |
|
46 | + protected $checkEqualOperatorUsage; |
|
47 | + /** @var string[] */ |
|
48 | + protected $errorMessages; |
|
49 | + |
|
50 | + /** |
|
51 | + * @param ICheck $list |
|
52 | + */ |
|
53 | + public function __construct(ICheck $list) { |
|
54 | + $this->list = $list; |
|
55 | + |
|
56 | + $this->blackListedClassNames = []; |
|
57 | + foreach ($list->getClasses() as $class => $blackListInfo) { |
|
58 | + if (is_numeric($class) && is_string($blackListInfo)) { |
|
59 | + $class = $blackListInfo; |
|
60 | + $blackListInfo = null; |
|
61 | + } |
|
62 | + |
|
63 | + $class = strtolower($class); |
|
64 | + $this->blackListedClassNames[$class] = $class; |
|
65 | + } |
|
66 | + |
|
67 | + $this->blackListedConstants = []; |
|
68 | + foreach ($list->getConstants() as $constantName => $blackListInfo) { |
|
69 | + $constantName = strtolower($constantName); |
|
70 | + $this->blackListedConstants[$constantName] = $constantName; |
|
71 | + } |
|
72 | + |
|
73 | + $this->blackListedFunctions = []; |
|
74 | + foreach ($list->getFunctions() as $functionName => $blackListInfo) { |
|
75 | + $functionName = strtolower($functionName); |
|
76 | + $this->blackListedFunctions[$functionName] = $functionName; |
|
77 | + } |
|
78 | + |
|
79 | + $this->blackListedMethods = []; |
|
80 | + foreach ($list->getMethods() as $functionName => $blackListInfo) { |
|
81 | + $functionName = strtolower($functionName); |
|
82 | + $this->blackListedMethods[$functionName] = $functionName; |
|
83 | + } |
|
84 | + |
|
85 | + $this->checkEqualOperatorUsage = $list->checkStrongComparisons(); |
|
86 | + |
|
87 | + $this->errorMessages = [ |
|
88 | + CodeChecker::CLASS_EXTENDS_NOT_ALLOWED => "%s class must not be extended", |
|
89 | + CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED => "%s interface must not be implemented", |
|
90 | + CodeChecker::STATIC_CALL_NOT_ALLOWED => "Static method of %s class must not be called", |
|
91 | + CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED => "Constant of %s class must not not be fetched", |
|
92 | + CodeChecker::CLASS_NEW_NOT_ALLOWED => "%s class must not be instantiated", |
|
93 | + CodeChecker::CLASS_USE_NOT_ALLOWED => "%s class must not be imported with a use statement", |
|
94 | + CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED => "Method of %s class must not be called", |
|
95 | + |
|
96 | + CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED => "is discouraged", |
|
97 | + ]; |
|
98 | + } |
|
99 | + |
|
100 | + /** @var array */ |
|
101 | + public $errors = []; |
|
102 | + |
|
103 | + public function enterNode(Node $node) { |
|
104 | + if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) { |
|
105 | + $this->errors[]= [ |
|
106 | + 'disallowedToken' => '==', |
|
107 | + 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
|
108 | + 'line' => $node->getLine(), |
|
109 | + 'reason' => $this->buildReason('==', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED) |
|
110 | + ]; |
|
111 | + } |
|
112 | + if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) { |
|
113 | + $this->errors[]= [ |
|
114 | + 'disallowedToken' => '!=', |
|
115 | + 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
|
116 | + 'line' => $node->getLine(), |
|
117 | + 'reason' => $this->buildReason('!=', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED) |
|
118 | + ]; |
|
119 | + } |
|
120 | + if ($node instanceof Node\Stmt\Class_) { |
|
121 | + if (!is_null($node->extends)) { |
|
122 | + $this->checkBlackList($node->extends->toString(), CodeChecker::CLASS_EXTENDS_NOT_ALLOWED, $node); |
|
123 | + } |
|
124 | + foreach ($node->implements as $implements) { |
|
125 | + $this->checkBlackList($implements->toString(), CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED, $node); |
|
126 | + } |
|
127 | + } |
|
128 | + if ($node instanceof Node\Expr\StaticCall) { |
|
129 | + if (!is_null($node->class)) { |
|
130 | + if ($node->class instanceof Name) { |
|
131 | + $this->checkBlackList($node->class->toString(), CodeChecker::STATIC_CALL_NOT_ALLOWED, $node); |
|
132 | + |
|
133 | + $this->checkBlackListFunction($node->class->toString(), $node->name, $node); |
|
134 | + $this->checkBlackListMethod($node->class->toString(), $node->name, $node); |
|
135 | + } |
|
136 | + |
|
137 | + if ($node->class instanceof Node\Expr\Variable) { |
|
138 | + /** |
|
139 | + * TODO: find a way to detect something like this: |
|
140 | + * $c = "OC_API"; |
|
141 | + * $n = $c::call(); |
|
142 | + */ |
|
143 | + // $this->checkBlackListMethod($node->class->..., $node->name, $node); |
|
144 | + } |
|
145 | + } |
|
146 | + } |
|
147 | + if ($node instanceof Node\Expr\MethodCall) { |
|
148 | + if (!is_null($node->var)) { |
|
149 | + if ($node->var instanceof Node\Expr\Variable) { |
|
150 | + /** |
|
151 | + * TODO: find a way to detect something like this: |
|
152 | + * $c = new OC_API(); |
|
153 | + * $n = $c::call(); |
|
154 | + * $n = $c->call(); |
|
155 | + */ |
|
156 | + // $this->checkBlackListMethod($node->var->..., $node->name, $node); |
|
157 | + } |
|
158 | + } |
|
159 | + } |
|
160 | + if ($node instanceof Node\Expr\ClassConstFetch) { |
|
161 | + if (!is_null($node->class)) { |
|
162 | + if ($node->class instanceof Name) { |
|
163 | + $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, $node); |
|
164 | + } |
|
165 | + if ($node->class instanceof Node\Expr\Variable) { |
|
166 | + /** |
|
167 | + * TODO: find a way to detect something like this: |
|
168 | + * $c = "OC_API"; |
|
169 | + * $n = $i::ADMIN_AUTH; |
|
170 | + */ |
|
171 | + } else { |
|
172 | + $this->checkBlackListConstant($node->class->toString(), $node->name, $node); |
|
173 | + } |
|
174 | + } |
|
175 | + } |
|
176 | + if ($node instanceof Node\Expr\New_) { |
|
177 | + if (!is_null($node->class)) { |
|
178 | + if ($node->class instanceof Name) { |
|
179 | + $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_NEW_NOT_ALLOWED, $node); |
|
180 | + } |
|
181 | + if ($node->class instanceof Node\Expr\Variable) { |
|
182 | + /** |
|
183 | + * TODO: find a way to detect something like this: |
|
184 | + * $c = "OC_API"; |
|
185 | + * $n = new $i; |
|
186 | + */ |
|
187 | + } |
|
188 | + } |
|
189 | + } |
|
190 | + if ($node instanceof Node\Stmt\UseUse) { |
|
191 | + $this->checkBlackList($node->name->toString(), CodeChecker::CLASS_USE_NOT_ALLOWED, $node); |
|
192 | + if ($node->alias) { |
|
193 | + $this->addUseNameToBlackList($node->name->toString(), $node->alias); |
|
194 | + } else { |
|
195 | + $this->addUseNameToBlackList($node->name->toString(), $node->name->getLast()); |
|
196 | + } |
|
197 | + } |
|
198 | + } |
|
199 | + |
|
200 | + /** |
|
201 | + * Check whether an alias was introduced for a namespace of a blacklisted class |
|
202 | + * |
|
203 | + * Example: |
|
204 | + * - Blacklist entry: OCP\AppFramework\IApi |
|
205 | + * - Name: OCP\AppFramework |
|
206 | + * - Alias: OAF |
|
207 | + * => new blacklist entry: OAF\IApi |
|
208 | + * |
|
209 | + * @param string $name |
|
210 | + * @param string $alias |
|
211 | + */ |
|
212 | + private function addUseNameToBlackList($name, $alias) { |
|
213 | + $name = strtolower($name); |
|
214 | + $alias = strtolower($alias); |
|
215 | + |
|
216 | + foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) { |
|
217 | + if (strpos($blackListedClassName, $name . '\\') === 0) { |
|
218 | + $aliasedClassName = str_replace($name, $alias, $blackListedClassName); |
|
219 | + $this->blackListedClassNames[$aliasedClassName] = $blackListedClassName; |
|
220 | + } |
|
221 | + } |
|
222 | + |
|
223 | + foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) { |
|
224 | + if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) { |
|
225 | + $aliasedConstantName = str_replace($name, $alias, $blackListedConstant); |
|
226 | + $this->blackListedConstants[$aliasedConstantName] = $blackListedConstant; |
|
227 | + } |
|
228 | + } |
|
229 | + |
|
230 | + foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) { |
|
231 | + if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) { |
|
232 | + $aliasedFunctionName = str_replace($name, $alias, $blackListedFunction); |
|
233 | + $this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction; |
|
234 | + } |
|
235 | + } |
|
236 | + |
|
237 | + foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) { |
|
238 | + if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) { |
|
239 | + $aliasedMethodName = str_replace($name, $alias, $blackListedMethod); |
|
240 | + $this->blackListedMethods[$aliasedMethodName] = $blackListedMethod; |
|
241 | + } |
|
242 | + } |
|
243 | + } |
|
244 | + |
|
245 | + private function checkBlackList($name, $errorCode, Node $node) { |
|
246 | + $lowerName = strtolower($name); |
|
247 | + |
|
248 | + if (isset($this->blackListedClassNames[$lowerName])) { |
|
249 | + $this->errors[]= [ |
|
250 | + 'disallowedToken' => $name, |
|
251 | + 'errorCode' => $errorCode, |
|
252 | + 'line' => $node->getLine(), |
|
253 | + 'reason' => $this->buildReason($this->blackListedClassNames[$lowerName], $errorCode) |
|
254 | + ]; |
|
255 | + } |
|
256 | + } |
|
257 | + |
|
258 | + private function checkBlackListConstant($class, $constantName, Node $node) { |
|
259 | + $name = $class . '::' . $constantName; |
|
260 | + $lowerName = strtolower($name); |
|
261 | + |
|
262 | + if (isset($this->blackListedConstants[$lowerName])) { |
|
263 | + $this->errors[]= [ |
|
264 | + 'disallowedToken' => $name, |
|
265 | + 'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, |
|
266 | + 'line' => $node->getLine(), |
|
267 | + 'reason' => $this->buildReason($this->blackListedConstants[$lowerName], CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED) |
|
268 | + ]; |
|
269 | + } |
|
270 | + } |
|
271 | + |
|
272 | + private function checkBlackListFunction($class, $functionName, Node $node) { |
|
273 | + $name = $class . '::' . $functionName; |
|
274 | + $lowerName = strtolower($name); |
|
275 | + |
|
276 | + if (isset($this->blackListedFunctions[$lowerName])) { |
|
277 | + $this->errors[]= [ |
|
278 | + 'disallowedToken' => $name, |
|
279 | + 'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED, |
|
280 | + 'line' => $node->getLine(), |
|
281 | + 'reason' => $this->buildReason($this->blackListedFunctions[$lowerName], CodeChecker::STATIC_CALL_NOT_ALLOWED) |
|
282 | + ]; |
|
283 | + } |
|
284 | + } |
|
285 | + |
|
286 | + private function checkBlackListMethod($class, $functionName, Node $node) { |
|
287 | + $name = $class . '::' . $functionName; |
|
288 | + $lowerName = strtolower($name); |
|
289 | + |
|
290 | + if (isset($this->blackListedMethods[$lowerName])) { |
|
291 | + $this->errors[]= [ |
|
292 | + 'disallowedToken' => $name, |
|
293 | + 'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED, |
|
294 | + 'line' => $node->getLine(), |
|
295 | + 'reason' => $this->buildReason($this->blackListedMethods[$lowerName], CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED) |
|
296 | + ]; |
|
297 | + } |
|
298 | + } |
|
299 | + |
|
300 | + private function buildReason($name, $errorCode) { |
|
301 | + if (isset($this->errorMessages[$errorCode])) { |
|
302 | + $desc = $this->list->getDescription($errorCode, $name); |
|
303 | + return sprintf($this->errorMessages[$errorCode], $desc); |
|
304 | + } |
|
305 | + |
|
306 | + return "$name usage not allowed - error: $errorCode"; |
|
307 | + } |
|
308 | 308 | } |
@@ -102,7 +102,7 @@ discard block |
||
102 | 102 | |
103 | 103 | public function enterNode(Node $node) { |
104 | 104 | if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) { |
105 | - $this->errors[]= [ |
|
105 | + $this->errors[] = [ |
|
106 | 106 | 'disallowedToken' => '==', |
107 | 107 | 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
108 | 108 | 'line' => $node->getLine(), |
@@ -110,7 +110,7 @@ discard block |
||
110 | 110 | ]; |
111 | 111 | } |
112 | 112 | if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) { |
113 | - $this->errors[]= [ |
|
113 | + $this->errors[] = [ |
|
114 | 114 | 'disallowedToken' => '!=', |
115 | 115 | 'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED, |
116 | 116 | 'line' => $node->getLine(), |
@@ -214,28 +214,28 @@ discard block |
||
214 | 214 | $alias = strtolower($alias); |
215 | 215 | |
216 | 216 | foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) { |
217 | - if (strpos($blackListedClassName, $name . '\\') === 0) { |
|
217 | + if (strpos($blackListedClassName, $name.'\\') === 0) { |
|
218 | 218 | $aliasedClassName = str_replace($name, $alias, $blackListedClassName); |
219 | 219 | $this->blackListedClassNames[$aliasedClassName] = $blackListedClassName; |
220 | 220 | } |
221 | 221 | } |
222 | 222 | |
223 | 223 | foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) { |
224 | - if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) { |
|
224 | + if (strpos($blackListedConstant, $name.'\\') === 0 || strpos($blackListedConstant, $name.'::') === 0) { |
|
225 | 225 | $aliasedConstantName = str_replace($name, $alias, $blackListedConstant); |
226 | 226 | $this->blackListedConstants[$aliasedConstantName] = $blackListedConstant; |
227 | 227 | } |
228 | 228 | } |
229 | 229 | |
230 | 230 | foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) { |
231 | - if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) { |
|
231 | + if (strpos($blackListedFunction, $name.'\\') === 0 || strpos($blackListedFunction, $name.'::') === 0) { |
|
232 | 232 | $aliasedFunctionName = str_replace($name, $alias, $blackListedFunction); |
233 | 233 | $this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction; |
234 | 234 | } |
235 | 235 | } |
236 | 236 | |
237 | 237 | foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) { |
238 | - if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) { |
|
238 | + if (strpos($blackListedMethod, $name.'\\') === 0 || strpos($blackListedMethod, $name.'::') === 0) { |
|
239 | 239 | $aliasedMethodName = str_replace($name, $alias, $blackListedMethod); |
240 | 240 | $this->blackListedMethods[$aliasedMethodName] = $blackListedMethod; |
241 | 241 | } |
@@ -246,7 +246,7 @@ discard block |
||
246 | 246 | $lowerName = strtolower($name); |
247 | 247 | |
248 | 248 | if (isset($this->blackListedClassNames[$lowerName])) { |
249 | - $this->errors[]= [ |
|
249 | + $this->errors[] = [ |
|
250 | 250 | 'disallowedToken' => $name, |
251 | 251 | 'errorCode' => $errorCode, |
252 | 252 | 'line' => $node->getLine(), |
@@ -256,11 +256,11 @@ discard block |
||
256 | 256 | } |
257 | 257 | |
258 | 258 | private function checkBlackListConstant($class, $constantName, Node $node) { |
259 | - $name = $class . '::' . $constantName; |
|
259 | + $name = $class.'::'.$constantName; |
|
260 | 260 | $lowerName = strtolower($name); |
261 | 261 | |
262 | 262 | if (isset($this->blackListedConstants[$lowerName])) { |
263 | - $this->errors[]= [ |
|
263 | + $this->errors[] = [ |
|
264 | 264 | 'disallowedToken' => $name, |
265 | 265 | 'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, |
266 | 266 | 'line' => $node->getLine(), |
@@ -270,11 +270,11 @@ discard block |
||
270 | 270 | } |
271 | 271 | |
272 | 272 | private function checkBlackListFunction($class, $functionName, Node $node) { |
273 | - $name = $class . '::' . $functionName; |
|
273 | + $name = $class.'::'.$functionName; |
|
274 | 274 | $lowerName = strtolower($name); |
275 | 275 | |
276 | 276 | if (isset($this->blackListedFunctions[$lowerName])) { |
277 | - $this->errors[]= [ |
|
277 | + $this->errors[] = [ |
|
278 | 278 | 'disallowedToken' => $name, |
279 | 279 | 'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED, |
280 | 280 | 'line' => $node->getLine(), |
@@ -284,11 +284,11 @@ discard block |
||
284 | 284 | } |
285 | 285 | |
286 | 286 | private function checkBlackListMethod($class, $functionName, Node $node) { |
287 | - $name = $class . '::' . $functionName; |
|
287 | + $name = $class.'::'.$functionName; |
|
288 | 288 | $lowerName = strtolower($name); |
289 | 289 | |
290 | 290 | if (isset($this->blackListedMethods[$lowerName])) { |
291 | - $this->errors[]= [ |
|
291 | + $this->errors[] = [ |
|
292 | 292 | 'disallowedToken' => $name, |
293 | 293 | 'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED, |
294 | 294 | 'line' => $node->getLine(), |
@@ -23,7 +23,6 @@ |
||
23 | 23 | |
24 | 24 | namespace OC\App; |
25 | 25 | |
26 | -use OC_Util; |
|
27 | 26 | use OCP\IConfig; |
28 | 27 | |
29 | 28 | /** |
@@ -36,66 +36,66 @@ |
||
36 | 36 | */ |
37 | 37 | class Platform { |
38 | 38 | |
39 | - /** |
|
40 | - * @param IConfig $config |
|
41 | - */ |
|
42 | - function __construct(IConfig $config) { |
|
43 | - $this->config = $config; |
|
44 | - } |
|
39 | + /** |
|
40 | + * @param IConfig $config |
|
41 | + */ |
|
42 | + function __construct(IConfig $config) { |
|
43 | + $this->config = $config; |
|
44 | + } |
|
45 | 45 | |
46 | - /** |
|
47 | - * @return string |
|
48 | - */ |
|
49 | - public function getPhpVersion() { |
|
50 | - return phpversion(); |
|
51 | - } |
|
46 | + /** |
|
47 | + * @return string |
|
48 | + */ |
|
49 | + public function getPhpVersion() { |
|
50 | + return phpversion(); |
|
51 | + } |
|
52 | 52 | |
53 | - /** |
|
54 | - * @return int |
|
55 | - */ |
|
56 | - public function getIntSize() { |
|
57 | - return PHP_INT_SIZE; |
|
58 | - } |
|
53 | + /** |
|
54 | + * @return int |
|
55 | + */ |
|
56 | + public function getIntSize() { |
|
57 | + return PHP_INT_SIZE; |
|
58 | + } |
|
59 | 59 | |
60 | - /** |
|
61 | - * @return string |
|
62 | - */ |
|
63 | - public function getOcVersion() { |
|
64 | - $v = \OCP\Util::getVersion(); |
|
65 | - return join('.', $v); |
|
66 | - } |
|
60 | + /** |
|
61 | + * @return string |
|
62 | + */ |
|
63 | + public function getOcVersion() { |
|
64 | + $v = \OCP\Util::getVersion(); |
|
65 | + return join('.', $v); |
|
66 | + } |
|
67 | 67 | |
68 | - /** |
|
69 | - * @return string |
|
70 | - */ |
|
71 | - public function getDatabase() { |
|
72 | - $dbType = $this->config->getSystemValue('dbtype', 'sqlite'); |
|
73 | - if ($dbType === 'sqlite3') { |
|
74 | - $dbType = 'sqlite'; |
|
75 | - } |
|
68 | + /** |
|
69 | + * @return string |
|
70 | + */ |
|
71 | + public function getDatabase() { |
|
72 | + $dbType = $this->config->getSystemValue('dbtype', 'sqlite'); |
|
73 | + if ($dbType === 'sqlite3') { |
|
74 | + $dbType = 'sqlite'; |
|
75 | + } |
|
76 | 76 | |
77 | - return $dbType; |
|
78 | - } |
|
77 | + return $dbType; |
|
78 | + } |
|
79 | 79 | |
80 | - /** |
|
81 | - * @return string |
|
82 | - */ |
|
83 | - public function getOS() { |
|
84 | - return php_uname('s'); |
|
85 | - } |
|
80 | + /** |
|
81 | + * @return string |
|
82 | + */ |
|
83 | + public function getOS() { |
|
84 | + return php_uname('s'); |
|
85 | + } |
|
86 | 86 | |
87 | - /** |
|
88 | - * @param $command |
|
89 | - * @return bool |
|
90 | - */ |
|
91 | - public function isCommandKnown($command) { |
|
92 | - $path = \OC_Helper::findBinaryPath($command); |
|
93 | - return ($path !== null); |
|
94 | - } |
|
87 | + /** |
|
88 | + * @param $command |
|
89 | + * @return bool |
|
90 | + */ |
|
91 | + public function isCommandKnown($command) { |
|
92 | + $path = \OC_Helper::findBinaryPath($command); |
|
93 | + return ($path !== null); |
|
94 | + } |
|
95 | 95 | |
96 | - public function getLibraryVersion($name) { |
|
97 | - $repo = new PlatformRepository(); |
|
98 | - $lib = $repo->findLibrary($name); |
|
99 | - return $lib; |
|
100 | - } |
|
96 | + public function getLibraryVersion($name) { |
|
97 | + $repo = new PlatformRepository(); |
|
98 | + $lib = $repo->findLibrary($name); |
|
99 | + return $lib; |
|
100 | + } |
|
101 | 101 | } |
@@ -110,7 +110,7 @@ |
||
110 | 110 | |
111 | 111 | /** |
112 | 112 | * Gets the correct header |
113 | - * @param Http::CONSTANT $status the constant from the Http class |
|
113 | + * @param integer $status the constant from the Http class |
|
114 | 114 | * @param \DateTime $lastModified formatted last modified date |
115 | 115 | * @param string $ETag the etag |
116 | 116 | * @return string |
@@ -33,121 +33,121 @@ |
||
33 | 33 | |
34 | 34 | class Http extends BaseHttp { |
35 | 35 | |
36 | - private $server; |
|
37 | - private $protocolVersion; |
|
38 | - protected $headers; |
|
39 | - |
|
40 | - /** |
|
41 | - * @param array $server $_SERVER |
|
42 | - * @param string $protocolVersion the http version to use defaults to HTTP/1.1 |
|
43 | - */ |
|
44 | - public function __construct($server, $protocolVersion='HTTP/1.1') { |
|
45 | - $this->server = $server; |
|
46 | - $this->protocolVersion = $protocolVersion; |
|
47 | - |
|
48 | - $this->headers = array( |
|
49 | - self::STATUS_CONTINUE => 'Continue', |
|
50 | - self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols', |
|
51 | - self::STATUS_PROCESSING => 'Processing', |
|
52 | - self::STATUS_OK => 'OK', |
|
53 | - self::STATUS_CREATED => 'Created', |
|
54 | - self::STATUS_ACCEPTED => 'Accepted', |
|
55 | - self::STATUS_NON_AUTHORATIVE_INFORMATION => 'Non-Authorative Information', |
|
56 | - self::STATUS_NO_CONTENT => 'No Content', |
|
57 | - self::STATUS_RESET_CONTENT => 'Reset Content', |
|
58 | - self::STATUS_PARTIAL_CONTENT => 'Partial Content', |
|
59 | - self::STATUS_MULTI_STATUS => 'Multi-Status', // RFC 4918 |
|
60 | - self::STATUS_ALREADY_REPORTED => 'Already Reported', // RFC 5842 |
|
61 | - self::STATUS_IM_USED => 'IM Used', // RFC 3229 |
|
62 | - self::STATUS_MULTIPLE_CHOICES => 'Multiple Choices', |
|
63 | - self::STATUS_MOVED_PERMANENTLY => 'Moved Permanently', |
|
64 | - self::STATUS_FOUND => 'Found', |
|
65 | - self::STATUS_SEE_OTHER => 'See Other', |
|
66 | - self::STATUS_NOT_MODIFIED => 'Not Modified', |
|
67 | - self::STATUS_USE_PROXY => 'Use Proxy', |
|
68 | - self::STATUS_RESERVED => 'Reserved', |
|
69 | - self::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect', |
|
70 | - self::STATUS_BAD_REQUEST => 'Bad request', |
|
71 | - self::STATUS_UNAUTHORIZED => 'Unauthorized', |
|
72 | - self::STATUS_PAYMENT_REQUIRED => 'Payment Required', |
|
73 | - self::STATUS_FORBIDDEN => 'Forbidden', |
|
74 | - self::STATUS_NOT_FOUND => 'Not Found', |
|
75 | - self::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed', |
|
76 | - self::STATUS_NOT_ACCEPTABLE => 'Not Acceptable', |
|
77 | - self::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required', |
|
78 | - self::STATUS_REQUEST_TIMEOUT => 'Request Timeout', |
|
79 | - self::STATUS_CONFLICT => 'Conflict', |
|
80 | - self::STATUS_GONE => 'Gone', |
|
81 | - self::STATUS_LENGTH_REQUIRED => 'Length Required', |
|
82 | - self::STATUS_PRECONDITION_FAILED => 'Precondition failed', |
|
83 | - self::STATUS_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large', |
|
84 | - self::STATUS_REQUEST_URI_TOO_LONG => 'Request-URI Too Long', |
|
85 | - self::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type', |
|
86 | - self::STATUS_REQUEST_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable', |
|
87 | - self::STATUS_EXPECTATION_FAILED => 'Expectation Failed', |
|
88 | - self::STATUS_IM_A_TEAPOT => 'I\'m a teapot', // RFC 2324 |
|
89 | - self::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', // RFC 4918 |
|
90 | - self::STATUS_LOCKED => 'Locked', // RFC 4918 |
|
91 | - self::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', // RFC 4918 |
|
92 | - self::STATUS_UPGRADE_REQUIRED => 'Upgrade required', |
|
93 | - self::STATUS_PRECONDITION_REQUIRED => 'Precondition required', // draft-nottingham-http-new-status |
|
94 | - self::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', // draft-nottingham-http-new-status |
|
95 | - self::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', // draft-nottingham-http-new-status |
|
96 | - self::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error', |
|
97 | - self::STATUS_NOT_IMPLEMENTED => 'Not Implemented', |
|
98 | - self::STATUS_BAD_GATEWAY => 'Bad Gateway', |
|
99 | - self::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable', |
|
100 | - self::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout', |
|
101 | - self::STATUS_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported', |
|
102 | - self::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates', |
|
103 | - self::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', // RFC 4918 |
|
104 | - self::STATUS_LOOP_DETECTED => 'Loop Detected', // RFC 5842 |
|
105 | - self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard |
|
106 | - self::STATUS_NOT_EXTENDED => 'Not extended', |
|
107 | - self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status |
|
108 | - ); |
|
109 | - } |
|
110 | - |
|
111 | - |
|
112 | - /** |
|
113 | - * Gets the correct header |
|
114 | - * @param Http::CONSTANT $status the constant from the Http class |
|
115 | - * @param \DateTime $lastModified formatted last modified date |
|
116 | - * @param string $ETag the etag |
|
117 | - * @return string |
|
118 | - */ |
|
119 | - public function getStatusHeader($status, \DateTime $lastModified=null, |
|
120 | - $ETag=null) { |
|
121 | - |
|
122 | - if(!is_null($lastModified)) { |
|
123 | - $lastModified = $lastModified->format(\DateTime::RFC2822); |
|
124 | - } |
|
125 | - |
|
126 | - // if etag or lastmodified have not changed, return a not modified |
|
127 | - if ((isset($this->server['HTTP_IF_NONE_MATCH']) |
|
128 | - && trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag) |
|
129 | - |
|
130 | - || |
|
131 | - |
|
132 | - (isset($this->server['HTTP_IF_MODIFIED_SINCE']) |
|
133 | - && trim($this->server['HTTP_IF_MODIFIED_SINCE']) === |
|
134 | - $lastModified)) { |
|
135 | - |
|
136 | - $status = self::STATUS_NOT_MODIFIED; |
|
137 | - } |
|
138 | - |
|
139 | - // we have one change currently for the http 1.0 header that differs |
|
140 | - // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND |
|
141 | - // if this differs any more, we want to create childclasses for this |
|
142 | - if($status === self::STATUS_TEMPORARY_REDIRECT |
|
143 | - && $this->protocolVersion === 'HTTP/1.0') { |
|
144 | - |
|
145 | - $status = self::STATUS_FOUND; |
|
146 | - } |
|
147 | - |
|
148 | - return $this->protocolVersion . ' ' . $status . ' ' . |
|
149 | - $this->headers[$status]; |
|
150 | - } |
|
36 | + private $server; |
|
37 | + private $protocolVersion; |
|
38 | + protected $headers; |
|
39 | + |
|
40 | + /** |
|
41 | + * @param array $server $_SERVER |
|
42 | + * @param string $protocolVersion the http version to use defaults to HTTP/1.1 |
|
43 | + */ |
|
44 | + public function __construct($server, $protocolVersion='HTTP/1.1') { |
|
45 | + $this->server = $server; |
|
46 | + $this->protocolVersion = $protocolVersion; |
|
47 | + |
|
48 | + $this->headers = array( |
|
49 | + self::STATUS_CONTINUE => 'Continue', |
|
50 | + self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols', |
|
51 | + self::STATUS_PROCESSING => 'Processing', |
|
52 | + self::STATUS_OK => 'OK', |
|
53 | + self::STATUS_CREATED => 'Created', |
|
54 | + self::STATUS_ACCEPTED => 'Accepted', |
|
55 | + self::STATUS_NON_AUTHORATIVE_INFORMATION => 'Non-Authorative Information', |
|
56 | + self::STATUS_NO_CONTENT => 'No Content', |
|
57 | + self::STATUS_RESET_CONTENT => 'Reset Content', |
|
58 | + self::STATUS_PARTIAL_CONTENT => 'Partial Content', |
|
59 | + self::STATUS_MULTI_STATUS => 'Multi-Status', // RFC 4918 |
|
60 | + self::STATUS_ALREADY_REPORTED => 'Already Reported', // RFC 5842 |
|
61 | + self::STATUS_IM_USED => 'IM Used', // RFC 3229 |
|
62 | + self::STATUS_MULTIPLE_CHOICES => 'Multiple Choices', |
|
63 | + self::STATUS_MOVED_PERMANENTLY => 'Moved Permanently', |
|
64 | + self::STATUS_FOUND => 'Found', |
|
65 | + self::STATUS_SEE_OTHER => 'See Other', |
|
66 | + self::STATUS_NOT_MODIFIED => 'Not Modified', |
|
67 | + self::STATUS_USE_PROXY => 'Use Proxy', |
|
68 | + self::STATUS_RESERVED => 'Reserved', |
|
69 | + self::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect', |
|
70 | + self::STATUS_BAD_REQUEST => 'Bad request', |
|
71 | + self::STATUS_UNAUTHORIZED => 'Unauthorized', |
|
72 | + self::STATUS_PAYMENT_REQUIRED => 'Payment Required', |
|
73 | + self::STATUS_FORBIDDEN => 'Forbidden', |
|
74 | + self::STATUS_NOT_FOUND => 'Not Found', |
|
75 | + self::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed', |
|
76 | + self::STATUS_NOT_ACCEPTABLE => 'Not Acceptable', |
|
77 | + self::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required', |
|
78 | + self::STATUS_REQUEST_TIMEOUT => 'Request Timeout', |
|
79 | + self::STATUS_CONFLICT => 'Conflict', |
|
80 | + self::STATUS_GONE => 'Gone', |
|
81 | + self::STATUS_LENGTH_REQUIRED => 'Length Required', |
|
82 | + self::STATUS_PRECONDITION_FAILED => 'Precondition failed', |
|
83 | + self::STATUS_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large', |
|
84 | + self::STATUS_REQUEST_URI_TOO_LONG => 'Request-URI Too Long', |
|
85 | + self::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type', |
|
86 | + self::STATUS_REQUEST_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable', |
|
87 | + self::STATUS_EXPECTATION_FAILED => 'Expectation Failed', |
|
88 | + self::STATUS_IM_A_TEAPOT => 'I\'m a teapot', // RFC 2324 |
|
89 | + self::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', // RFC 4918 |
|
90 | + self::STATUS_LOCKED => 'Locked', // RFC 4918 |
|
91 | + self::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', // RFC 4918 |
|
92 | + self::STATUS_UPGRADE_REQUIRED => 'Upgrade required', |
|
93 | + self::STATUS_PRECONDITION_REQUIRED => 'Precondition required', // draft-nottingham-http-new-status |
|
94 | + self::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', // draft-nottingham-http-new-status |
|
95 | + self::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', // draft-nottingham-http-new-status |
|
96 | + self::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error', |
|
97 | + self::STATUS_NOT_IMPLEMENTED => 'Not Implemented', |
|
98 | + self::STATUS_BAD_GATEWAY => 'Bad Gateway', |
|
99 | + self::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable', |
|
100 | + self::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout', |
|
101 | + self::STATUS_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported', |
|
102 | + self::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates', |
|
103 | + self::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', // RFC 4918 |
|
104 | + self::STATUS_LOOP_DETECTED => 'Loop Detected', // RFC 5842 |
|
105 | + self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard |
|
106 | + self::STATUS_NOT_EXTENDED => 'Not extended', |
|
107 | + self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status |
|
108 | + ); |
|
109 | + } |
|
110 | + |
|
111 | + |
|
112 | + /** |
|
113 | + * Gets the correct header |
|
114 | + * @param Http::CONSTANT $status the constant from the Http class |
|
115 | + * @param \DateTime $lastModified formatted last modified date |
|
116 | + * @param string $ETag the etag |
|
117 | + * @return string |
|
118 | + */ |
|
119 | + public function getStatusHeader($status, \DateTime $lastModified=null, |
|
120 | + $ETag=null) { |
|
121 | + |
|
122 | + if(!is_null($lastModified)) { |
|
123 | + $lastModified = $lastModified->format(\DateTime::RFC2822); |
|
124 | + } |
|
125 | + |
|
126 | + // if etag or lastmodified have not changed, return a not modified |
|
127 | + if ((isset($this->server['HTTP_IF_NONE_MATCH']) |
|
128 | + && trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag) |
|
129 | + |
|
130 | + || |
|
131 | + |
|
132 | + (isset($this->server['HTTP_IF_MODIFIED_SINCE']) |
|
133 | + && trim($this->server['HTTP_IF_MODIFIED_SINCE']) === |
|
134 | + $lastModified)) { |
|
135 | + |
|
136 | + $status = self::STATUS_NOT_MODIFIED; |
|
137 | + } |
|
138 | + |
|
139 | + // we have one change currently for the http 1.0 header that differs |
|
140 | + // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND |
|
141 | + // if this differs any more, we want to create childclasses for this |
|
142 | + if($status === self::STATUS_TEMPORARY_REDIRECT |
|
143 | + && $this->protocolVersion === 'HTTP/1.0') { |
|
144 | + |
|
145 | + $status = self::STATUS_FOUND; |
|
146 | + } |
|
147 | + |
|
148 | + return $this->protocolVersion . ' ' . $status . ' ' . |
|
149 | + $this->headers[$status]; |
|
150 | + } |
|
151 | 151 | |
152 | 152 | |
153 | 153 | } |
@@ -41,7 +41,7 @@ discard block |
||
41 | 41 | * @param array $server $_SERVER |
42 | 42 | * @param string $protocolVersion the http version to use defaults to HTTP/1.1 |
43 | 43 | */ |
44 | - public function __construct($server, $protocolVersion='HTTP/1.1') { |
|
44 | + public function __construct($server, $protocolVersion = 'HTTP/1.1') { |
|
45 | 45 | $this->server = $server; |
46 | 46 | $this->protocolVersion = $protocolVersion; |
47 | 47 | |
@@ -116,16 +116,16 @@ discard block |
||
116 | 116 | * @param string $ETag the etag |
117 | 117 | * @return string |
118 | 118 | */ |
119 | - public function getStatusHeader($status, \DateTime $lastModified=null, |
|
120 | - $ETag=null) { |
|
119 | + public function getStatusHeader($status, \DateTime $lastModified = null, |
|
120 | + $ETag = null) { |
|
121 | 121 | |
122 | - if(!is_null($lastModified)) { |
|
122 | + if (!is_null($lastModified)) { |
|
123 | 123 | $lastModified = $lastModified->format(\DateTime::RFC2822); |
124 | 124 | } |
125 | 125 | |
126 | 126 | // if etag or lastmodified have not changed, return a not modified |
127 | 127 | if ((isset($this->server['HTTP_IF_NONE_MATCH']) |
128 | - && trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag) |
|
128 | + && trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string) $ETag) |
|
129 | 129 | |
130 | 130 | || |
131 | 131 | |
@@ -139,13 +139,13 @@ discard block |
||
139 | 139 | // we have one change currently for the http 1.0 header that differs |
140 | 140 | // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND |
141 | 141 | // if this differs any more, we want to create childclasses for this |
142 | - if($status === self::STATUS_TEMPORARY_REDIRECT |
|
142 | + if ($status === self::STATUS_TEMPORARY_REDIRECT |
|
143 | 143 | && $this->protocolVersion === 'HTTP/1.0') { |
144 | 144 | |
145 | 145 | $status = self::STATUS_FOUND; |
146 | 146 | } |
147 | 147 | |
148 | - return $this->protocolVersion . ' ' . $status . ' ' . |
|
148 | + return $this->protocolVersion.' '.$status.' '. |
|
149 | 149 | $this->headers[$status]; |
150 | 150 | } |
151 | 151 |
@@ -205,7 +205,7 @@ |
||
205 | 205 | /** |
206 | 206 | * removes an entry from the comments run time cache |
207 | 207 | * |
208 | - * @param mixed $id the comment's id |
|
208 | + * @param string $id the comment's id |
|
209 | 209 | */ |
210 | 210 | protected function uncache($id) { |
211 | 211 | $id = strval($id); |
@@ -25,7 +25,6 @@ |
||
25 | 25 | namespace OC\Comments; |
26 | 26 | |
27 | 27 | use Doctrine\DBAL\Exception\DriverException; |
28 | -use Doctrine\DBAL\Platforms\MySqlPlatform; |
|
29 | 28 | use OCP\Comments\CommentsEvent; |
30 | 29 | use OCP\Comments\IComment; |
31 | 30 | use OCP\Comments\ICommentsEventHandler; |
@@ -39,842 +39,842 @@ |
||
39 | 39 | |
40 | 40 | class Manager implements ICommentsManager { |
41 | 41 | |
42 | - /** @var IDBConnection */ |
|
43 | - protected $dbConn; |
|
44 | - |
|
45 | - /** @var ILogger */ |
|
46 | - protected $logger; |
|
47 | - |
|
48 | - /** @var IConfig */ |
|
49 | - protected $config; |
|
50 | - |
|
51 | - /** @var IComment[] */ |
|
52 | - protected $commentsCache = []; |
|
53 | - |
|
54 | - /** @var \Closure[] */ |
|
55 | - protected $eventHandlerClosures = []; |
|
56 | - |
|
57 | - /** @var ICommentsEventHandler[] */ |
|
58 | - protected $eventHandlers = []; |
|
59 | - |
|
60 | - /** @var \Closure[] */ |
|
61 | - protected $displayNameResolvers = []; |
|
62 | - |
|
63 | - /** |
|
64 | - * Manager constructor. |
|
65 | - * |
|
66 | - * @param IDBConnection $dbConn |
|
67 | - * @param ILogger $logger |
|
68 | - * @param IConfig $config |
|
69 | - */ |
|
70 | - public function __construct( |
|
71 | - IDBConnection $dbConn, |
|
72 | - ILogger $logger, |
|
73 | - IConfig $config |
|
74 | - ) { |
|
75 | - $this->dbConn = $dbConn; |
|
76 | - $this->logger = $logger; |
|
77 | - $this->config = $config; |
|
78 | - } |
|
79 | - |
|
80 | - /** |
|
81 | - * converts data base data into PHP native, proper types as defined by |
|
82 | - * IComment interface. |
|
83 | - * |
|
84 | - * @param array $data |
|
85 | - * @return array |
|
86 | - */ |
|
87 | - protected function normalizeDatabaseData(array $data) { |
|
88 | - $data['id'] = strval($data['id']); |
|
89 | - $data['parent_id'] = strval($data['parent_id']); |
|
90 | - $data['topmost_parent_id'] = strval($data['topmost_parent_id']); |
|
91 | - $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']); |
|
92 | - if (!is_null($data['latest_child_timestamp'])) { |
|
93 | - $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']); |
|
94 | - } |
|
95 | - $data['children_count'] = intval($data['children_count']); |
|
96 | - return $data; |
|
97 | - } |
|
98 | - |
|
99 | - /** |
|
100 | - * prepares a comment for an insert or update operation after making sure |
|
101 | - * all necessary fields have a value assigned. |
|
102 | - * |
|
103 | - * @param IComment $comment |
|
104 | - * @return IComment returns the same updated IComment instance as provided |
|
105 | - * by parameter for convenience |
|
106 | - * @throws \UnexpectedValueException |
|
107 | - */ |
|
108 | - protected function prepareCommentForDatabaseWrite(IComment $comment) { |
|
109 | - if (!$comment->getActorType() |
|
110 | - || !$comment->getActorId() |
|
111 | - || !$comment->getObjectType() |
|
112 | - || !$comment->getObjectId() |
|
113 | - || !$comment->getVerb() |
|
114 | - ) { |
|
115 | - throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving'); |
|
116 | - } |
|
117 | - |
|
118 | - if ($comment->getId() === '') { |
|
119 | - $comment->setChildrenCount(0); |
|
120 | - $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC'))); |
|
121 | - $comment->setLatestChildDateTime(null); |
|
122 | - } |
|
123 | - |
|
124 | - if (is_null($comment->getCreationDateTime())) { |
|
125 | - $comment->setCreationDateTime(new \DateTime()); |
|
126 | - } |
|
127 | - |
|
128 | - if ($comment->getParentId() !== '0') { |
|
129 | - $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId())); |
|
130 | - } else { |
|
131 | - $comment->setTopmostParentId('0'); |
|
132 | - } |
|
133 | - |
|
134 | - $this->cache($comment); |
|
135 | - |
|
136 | - return $comment; |
|
137 | - } |
|
138 | - |
|
139 | - /** |
|
140 | - * returns the topmost parent id of a given comment identified by ID |
|
141 | - * |
|
142 | - * @param string $id |
|
143 | - * @return string |
|
144 | - * @throws NotFoundException |
|
145 | - */ |
|
146 | - protected function determineTopmostParentId($id) { |
|
147 | - $comment = $this->get($id); |
|
148 | - if ($comment->getParentId() === '0') { |
|
149 | - return $comment->getId(); |
|
150 | - } else { |
|
151 | - return $this->determineTopmostParentId($comment->getId()); |
|
152 | - } |
|
153 | - } |
|
154 | - |
|
155 | - /** |
|
156 | - * updates child information of a comment |
|
157 | - * |
|
158 | - * @param string $id |
|
159 | - * @param \DateTime $cDateTime the date time of the most recent child |
|
160 | - * @throws NotFoundException |
|
161 | - */ |
|
162 | - protected function updateChildrenInformation($id, \DateTime $cDateTime) { |
|
163 | - $qb = $this->dbConn->getQueryBuilder(); |
|
164 | - $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
165 | - ->from('comments') |
|
166 | - ->where($qb->expr()->eq('parent_id', $qb->createParameter('id'))) |
|
167 | - ->setParameter('id', $id); |
|
168 | - |
|
169 | - $resultStatement = $query->execute(); |
|
170 | - $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
171 | - $resultStatement->closeCursor(); |
|
172 | - $children = intval($data[0]); |
|
173 | - |
|
174 | - $comment = $this->get($id); |
|
175 | - $comment->setChildrenCount($children); |
|
176 | - $comment->setLatestChildDateTime($cDateTime); |
|
177 | - $this->save($comment); |
|
178 | - } |
|
179 | - |
|
180 | - /** |
|
181 | - * Tests whether actor or object type and id parameters are acceptable. |
|
182 | - * Throws exception if not. |
|
183 | - * |
|
184 | - * @param string $role |
|
185 | - * @param string $type |
|
186 | - * @param string $id |
|
187 | - * @throws \InvalidArgumentException |
|
188 | - */ |
|
189 | - protected function checkRoleParameters($role, $type, $id) { |
|
190 | - if ( |
|
191 | - !is_string($type) || empty($type) |
|
192 | - || !is_string($id) || empty($id) |
|
193 | - ) { |
|
194 | - throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
195 | - } |
|
196 | - } |
|
197 | - |
|
198 | - /** |
|
199 | - * run-time caches a comment |
|
200 | - * |
|
201 | - * @param IComment $comment |
|
202 | - */ |
|
203 | - protected function cache(IComment $comment) { |
|
204 | - $id = $comment->getId(); |
|
205 | - if (empty($id)) { |
|
206 | - return; |
|
207 | - } |
|
208 | - $this->commentsCache[strval($id)] = $comment; |
|
209 | - } |
|
210 | - |
|
211 | - /** |
|
212 | - * removes an entry from the comments run time cache |
|
213 | - * |
|
214 | - * @param mixed $id the comment's id |
|
215 | - */ |
|
216 | - protected function uncache($id) { |
|
217 | - $id = strval($id); |
|
218 | - if (isset($this->commentsCache[$id])) { |
|
219 | - unset($this->commentsCache[$id]); |
|
220 | - } |
|
221 | - } |
|
222 | - |
|
223 | - /** |
|
224 | - * returns a comment instance |
|
225 | - * |
|
226 | - * @param string $id the ID of the comment |
|
227 | - * @return IComment |
|
228 | - * @throws NotFoundException |
|
229 | - * @throws \InvalidArgumentException |
|
230 | - * @since 9.0.0 |
|
231 | - */ |
|
232 | - public function get($id) { |
|
233 | - if (intval($id) === 0) { |
|
234 | - throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.'); |
|
235 | - } |
|
236 | - |
|
237 | - if (isset($this->commentsCache[$id])) { |
|
238 | - return $this->commentsCache[$id]; |
|
239 | - } |
|
240 | - |
|
241 | - $qb = $this->dbConn->getQueryBuilder(); |
|
242 | - $resultStatement = $qb->select('*') |
|
243 | - ->from('comments') |
|
244 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
245 | - ->setParameter('id', $id, IQueryBuilder::PARAM_INT) |
|
246 | - ->execute(); |
|
247 | - |
|
248 | - $data = $resultStatement->fetch(); |
|
249 | - $resultStatement->closeCursor(); |
|
250 | - if (!$data) { |
|
251 | - throw new NotFoundException(); |
|
252 | - } |
|
253 | - |
|
254 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
255 | - $this->cache($comment); |
|
256 | - return $comment; |
|
257 | - } |
|
258 | - |
|
259 | - /** |
|
260 | - * returns the comment specified by the id and all it's child comments. |
|
261 | - * At this point of time, we do only support one level depth. |
|
262 | - * |
|
263 | - * @param string $id |
|
264 | - * @param int $limit max number of entries to return, 0 returns all |
|
265 | - * @param int $offset the start entry |
|
266 | - * @return array |
|
267 | - * @since 9.0.0 |
|
268 | - * |
|
269 | - * The return array looks like this |
|
270 | - * [ |
|
271 | - * 'comment' => IComment, // root comment |
|
272 | - * 'replies' => |
|
273 | - * [ |
|
274 | - * 0 => |
|
275 | - * [ |
|
276 | - * 'comment' => IComment, |
|
277 | - * 'replies' => [] |
|
278 | - * ] |
|
279 | - * 1 => |
|
280 | - * [ |
|
281 | - * 'comment' => IComment, |
|
282 | - * 'replies'=> [] |
|
283 | - * ], |
|
284 | - * … |
|
285 | - * ] |
|
286 | - * ] |
|
287 | - */ |
|
288 | - public function getTree($id, $limit = 0, $offset = 0) { |
|
289 | - $tree = []; |
|
290 | - $tree['comment'] = $this->get($id); |
|
291 | - $tree['replies'] = []; |
|
292 | - |
|
293 | - $qb = $this->dbConn->getQueryBuilder(); |
|
294 | - $query = $qb->select('*') |
|
295 | - ->from('comments') |
|
296 | - ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id'))) |
|
297 | - ->orderBy('creation_timestamp', 'DESC') |
|
298 | - ->setParameter('id', $id); |
|
299 | - |
|
300 | - if ($limit > 0) { |
|
301 | - $query->setMaxResults($limit); |
|
302 | - } |
|
303 | - if ($offset > 0) { |
|
304 | - $query->setFirstResult($offset); |
|
305 | - } |
|
306 | - |
|
307 | - $resultStatement = $query->execute(); |
|
308 | - while ($data = $resultStatement->fetch()) { |
|
309 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
310 | - $this->cache($comment); |
|
311 | - $tree['replies'][] = [ |
|
312 | - 'comment' => $comment, |
|
313 | - 'replies' => [] |
|
314 | - ]; |
|
315 | - } |
|
316 | - $resultStatement->closeCursor(); |
|
317 | - |
|
318 | - return $tree; |
|
319 | - } |
|
320 | - |
|
321 | - /** |
|
322 | - * returns comments for a specific object (e.g. a file). |
|
323 | - * |
|
324 | - * The sort order is always newest to oldest. |
|
325 | - * |
|
326 | - * @param string $objectType the object type, e.g. 'files' |
|
327 | - * @param string $objectId the id of the object |
|
328 | - * @param int $limit optional, number of maximum comments to be returned. if |
|
329 | - * not specified, all comments are returned. |
|
330 | - * @param int $offset optional, starting point |
|
331 | - * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
332 | - * that may be returned |
|
333 | - * @return IComment[] |
|
334 | - * @since 9.0.0 |
|
335 | - */ |
|
336 | - public function getForObject( |
|
337 | - $objectType, |
|
338 | - $objectId, |
|
339 | - $limit = 0, |
|
340 | - $offset = 0, |
|
341 | - \DateTime $notOlderThan = null |
|
342 | - ) { |
|
343 | - $comments = []; |
|
344 | - |
|
345 | - $qb = $this->dbConn->getQueryBuilder(); |
|
346 | - $query = $qb->select('*') |
|
347 | - ->from('comments') |
|
348 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
349 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
350 | - ->orderBy('creation_timestamp', 'DESC') |
|
351 | - ->setParameter('type', $objectType) |
|
352 | - ->setParameter('id', $objectId); |
|
353 | - |
|
354 | - if ($limit > 0) { |
|
355 | - $query->setMaxResults($limit); |
|
356 | - } |
|
357 | - if ($offset > 0) { |
|
358 | - $query->setFirstResult($offset); |
|
359 | - } |
|
360 | - if (!is_null($notOlderThan)) { |
|
361 | - $query |
|
362 | - ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
363 | - ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
364 | - } |
|
365 | - |
|
366 | - $resultStatement = $query->execute(); |
|
367 | - while ($data = $resultStatement->fetch()) { |
|
368 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
369 | - $this->cache($comment); |
|
370 | - $comments[] = $comment; |
|
371 | - } |
|
372 | - $resultStatement->closeCursor(); |
|
373 | - |
|
374 | - return $comments; |
|
375 | - } |
|
376 | - |
|
377 | - /** |
|
378 | - * @param $objectType string the object type, e.g. 'files' |
|
379 | - * @param $objectId string the id of the object |
|
380 | - * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
381 | - * that may be returned |
|
382 | - * @return Int |
|
383 | - * @since 9.0.0 |
|
384 | - */ |
|
385 | - public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) { |
|
386 | - $qb = $this->dbConn->getQueryBuilder(); |
|
387 | - $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
388 | - ->from('comments') |
|
389 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
390 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
391 | - ->setParameter('type', $objectType) |
|
392 | - ->setParameter('id', $objectId); |
|
393 | - |
|
394 | - if (!is_null($notOlderThan)) { |
|
395 | - $query |
|
396 | - ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
397 | - ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
398 | - } |
|
399 | - |
|
400 | - $resultStatement = $query->execute(); |
|
401 | - $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
402 | - $resultStatement->closeCursor(); |
|
403 | - return intval($data[0]); |
|
404 | - } |
|
405 | - |
|
406 | - /** |
|
407 | - * Get the number of unread comments for all files in a folder |
|
408 | - * |
|
409 | - * @param int $folderId |
|
410 | - * @param IUser $user |
|
411 | - * @return array [$fileId => $unreadCount] |
|
412 | - */ |
|
413 | - public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) { |
|
414 | - $qb = $this->dbConn->getQueryBuilder(); |
|
415 | - $query = $qb->select('fileid', $qb->createFunction( |
|
416 | - 'COUNT(' . $qb->getColumnName('c.id') . ')') |
|
417 | - )->from('comments', 'c') |
|
418 | - ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX( |
|
419 | - $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')), |
|
420 | - $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)) |
|
421 | - )) |
|
422 | - ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX( |
|
423 | - $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')), |
|
424 | - $qb->expr()->eq('m.object_id', 'c.object_id'), |
|
425 | - $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())) |
|
426 | - )) |
|
427 | - ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId))) |
|
428 | - ->andWhere($qb->expr()->orX( |
|
429 | - $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'), |
|
430 | - $qb->expr()->isNull('marker_datetime') |
|
431 | - )) |
|
432 | - ->groupBy('f.fileid'); |
|
433 | - |
|
434 | - $resultStatement = $query->execute(); |
|
435 | - return array_map(function ($count) { |
|
436 | - return (int)$count; |
|
437 | - }, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR)); |
|
438 | - } |
|
439 | - |
|
440 | - /** |
|
441 | - * creates a new comment and returns it. At this point of time, it is not |
|
442 | - * saved in the used data storage. Use save() after setting other fields |
|
443 | - * of the comment (e.g. message or verb). |
|
444 | - * |
|
445 | - * @param string $actorType the actor type (e.g. 'users') |
|
446 | - * @param string $actorId a user id |
|
447 | - * @param string $objectType the object type the comment is attached to |
|
448 | - * @param string $objectId the object id the comment is attached to |
|
449 | - * @return IComment |
|
450 | - * @since 9.0.0 |
|
451 | - */ |
|
452 | - public function create($actorType, $actorId, $objectType, $objectId) { |
|
453 | - $comment = new Comment(); |
|
454 | - $comment |
|
455 | - ->setActor($actorType, $actorId) |
|
456 | - ->setObject($objectType, $objectId); |
|
457 | - return $comment; |
|
458 | - } |
|
459 | - |
|
460 | - /** |
|
461 | - * permanently deletes the comment specified by the ID |
|
462 | - * |
|
463 | - * When the comment has child comments, their parent ID will be changed to |
|
464 | - * the parent ID of the item that is to be deleted. |
|
465 | - * |
|
466 | - * @param string $id |
|
467 | - * @return bool |
|
468 | - * @throws \InvalidArgumentException |
|
469 | - * @since 9.0.0 |
|
470 | - */ |
|
471 | - public function delete($id) { |
|
472 | - if (!is_string($id)) { |
|
473 | - throw new \InvalidArgumentException('Parameter must be string'); |
|
474 | - } |
|
475 | - |
|
476 | - try { |
|
477 | - $comment = $this->get($id); |
|
478 | - } catch (\Exception $e) { |
|
479 | - // Ignore exceptions, we just don't fire a hook then |
|
480 | - $comment = null; |
|
481 | - } |
|
482 | - |
|
483 | - $qb = $this->dbConn->getQueryBuilder(); |
|
484 | - $query = $qb->delete('comments') |
|
485 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
486 | - ->setParameter('id', $id); |
|
487 | - |
|
488 | - try { |
|
489 | - $affectedRows = $query->execute(); |
|
490 | - $this->uncache($id); |
|
491 | - } catch (DriverException $e) { |
|
492 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
493 | - return false; |
|
494 | - } |
|
495 | - |
|
496 | - if ($affectedRows > 0 && $comment instanceof IComment) { |
|
497 | - $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment); |
|
498 | - } |
|
499 | - |
|
500 | - return ($affectedRows > 0); |
|
501 | - } |
|
502 | - |
|
503 | - /** |
|
504 | - * saves the comment permanently |
|
505 | - * |
|
506 | - * if the supplied comment has an empty ID, a new entry comment will be |
|
507 | - * saved and the instance updated with the new ID. |
|
508 | - * |
|
509 | - * Otherwise, an existing comment will be updated. |
|
510 | - * |
|
511 | - * Throws NotFoundException when a comment that is to be updated does not |
|
512 | - * exist anymore at this point of time. |
|
513 | - * |
|
514 | - * @param IComment $comment |
|
515 | - * @return bool |
|
516 | - * @throws NotFoundException |
|
517 | - * @since 9.0.0 |
|
518 | - */ |
|
519 | - public function save(IComment $comment) { |
|
520 | - if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
521 | - $result = $this->insert($comment); |
|
522 | - } else { |
|
523 | - $result = $this->update($comment); |
|
524 | - } |
|
525 | - |
|
526 | - if ($result && !!$comment->getParentId()) { |
|
527 | - $this->updateChildrenInformation( |
|
528 | - $comment->getParentId(), |
|
529 | - $comment->getCreationDateTime() |
|
530 | - ); |
|
531 | - $this->cache($comment); |
|
532 | - } |
|
533 | - |
|
534 | - return $result; |
|
535 | - } |
|
536 | - |
|
537 | - /** |
|
538 | - * inserts the provided comment in the database |
|
539 | - * |
|
540 | - * @param IComment $comment |
|
541 | - * @return bool |
|
542 | - */ |
|
543 | - protected function insert(IComment &$comment) { |
|
544 | - $qb = $this->dbConn->getQueryBuilder(); |
|
545 | - $affectedRows = $qb |
|
546 | - ->insert('comments') |
|
547 | - ->values([ |
|
548 | - 'parent_id' => $qb->createNamedParameter($comment->getParentId()), |
|
549 | - 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), |
|
550 | - 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), |
|
551 | - 'actor_type' => $qb->createNamedParameter($comment->getActorType()), |
|
552 | - 'actor_id' => $qb->createNamedParameter($comment->getActorId()), |
|
553 | - 'message' => $qb->createNamedParameter($comment->getMessage()), |
|
554 | - 'verb' => $qb->createNamedParameter($comment->getVerb()), |
|
555 | - 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), |
|
556 | - 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), |
|
557 | - 'object_type' => $qb->createNamedParameter($comment->getObjectType()), |
|
558 | - 'object_id' => $qb->createNamedParameter($comment->getObjectId()), |
|
559 | - ]) |
|
560 | - ->execute(); |
|
561 | - |
|
562 | - if ($affectedRows > 0) { |
|
563 | - $comment->setId(strval($qb->getLastInsertId())); |
|
564 | - $this->sendEvent(CommentsEvent::EVENT_ADD, $comment); |
|
565 | - } |
|
566 | - |
|
567 | - return $affectedRows > 0; |
|
568 | - } |
|
569 | - |
|
570 | - /** |
|
571 | - * updates a Comment data row |
|
572 | - * |
|
573 | - * @param IComment $comment |
|
574 | - * @return bool |
|
575 | - * @throws NotFoundException |
|
576 | - */ |
|
577 | - protected function update(IComment $comment) { |
|
578 | - // for properly working preUpdate Events we need the old comments as is |
|
579 | - // in the DB and overcome caching. Also avoid that outdated information stays. |
|
580 | - $this->uncache($comment->getId()); |
|
581 | - $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId())); |
|
582 | - $this->uncache($comment->getId()); |
|
583 | - |
|
584 | - $qb = $this->dbConn->getQueryBuilder(); |
|
585 | - $affectedRows = $qb |
|
586 | - ->update('comments') |
|
587 | - ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
588 | - ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
589 | - ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
590 | - ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
591 | - ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
592 | - ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
593 | - ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
594 | - ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
595 | - ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
596 | - ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
597 | - ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
598 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
599 | - ->setParameter('id', $comment->getId()) |
|
600 | - ->execute(); |
|
601 | - |
|
602 | - if ($affectedRows === 0) { |
|
603 | - throw new NotFoundException('Comment to update does ceased to exist'); |
|
604 | - } |
|
605 | - |
|
606 | - $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); |
|
607 | - |
|
608 | - return $affectedRows > 0; |
|
609 | - } |
|
610 | - |
|
611 | - /** |
|
612 | - * removes references to specific actor (e.g. on user delete) of a comment. |
|
613 | - * The comment itself must not get lost/deleted. |
|
614 | - * |
|
615 | - * @param string $actorType the actor type (e.g. 'users') |
|
616 | - * @param string $actorId a user id |
|
617 | - * @return boolean |
|
618 | - * @since 9.0.0 |
|
619 | - */ |
|
620 | - public function deleteReferencesOfActor($actorType, $actorId) { |
|
621 | - $this->checkRoleParameters('Actor', $actorType, $actorId); |
|
622 | - |
|
623 | - $qb = $this->dbConn->getQueryBuilder(); |
|
624 | - $affectedRows = $qb |
|
625 | - ->update('comments') |
|
626 | - ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
627 | - ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
628 | - ->where($qb->expr()->eq('actor_type', $qb->createParameter('type'))) |
|
629 | - ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id'))) |
|
630 | - ->setParameter('type', $actorType) |
|
631 | - ->setParameter('id', $actorId) |
|
632 | - ->execute(); |
|
633 | - |
|
634 | - $this->commentsCache = []; |
|
635 | - |
|
636 | - return is_int($affectedRows); |
|
637 | - } |
|
638 | - |
|
639 | - /** |
|
640 | - * deletes all comments made of a specific object (e.g. on file delete) |
|
641 | - * |
|
642 | - * @param string $objectType the object type (e.g. 'files') |
|
643 | - * @param string $objectId e.g. the file id |
|
644 | - * @return boolean |
|
645 | - * @since 9.0.0 |
|
646 | - */ |
|
647 | - public function deleteCommentsAtObject($objectType, $objectId) { |
|
648 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
649 | - |
|
650 | - $qb = $this->dbConn->getQueryBuilder(); |
|
651 | - $affectedRows = $qb |
|
652 | - ->delete('comments') |
|
653 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
654 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
655 | - ->setParameter('type', $objectType) |
|
656 | - ->setParameter('id', $objectId) |
|
657 | - ->execute(); |
|
658 | - |
|
659 | - $this->commentsCache = []; |
|
660 | - |
|
661 | - return is_int($affectedRows); |
|
662 | - } |
|
663 | - |
|
664 | - /** |
|
665 | - * deletes the read markers for the specified user |
|
666 | - * |
|
667 | - * @param \OCP\IUser $user |
|
668 | - * @return bool |
|
669 | - * @since 9.0.0 |
|
670 | - */ |
|
671 | - public function deleteReadMarksFromUser(IUser $user) { |
|
672 | - $qb = $this->dbConn->getQueryBuilder(); |
|
673 | - $query = $qb->delete('comments_read_markers') |
|
674 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
675 | - ->setParameter('user_id', $user->getUID()); |
|
676 | - |
|
677 | - try { |
|
678 | - $affectedRows = $query->execute(); |
|
679 | - } catch (DriverException $e) { |
|
680 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
681 | - return false; |
|
682 | - } |
|
683 | - return ($affectedRows > 0); |
|
684 | - } |
|
685 | - |
|
686 | - /** |
|
687 | - * sets the read marker for a given file to the specified date for the |
|
688 | - * provided user |
|
689 | - * |
|
690 | - * @param string $objectType |
|
691 | - * @param string $objectId |
|
692 | - * @param \DateTime $dateTime |
|
693 | - * @param IUser $user |
|
694 | - * @since 9.0.0 |
|
695 | - */ |
|
696 | - public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) { |
|
697 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
698 | - |
|
699 | - $qb = $this->dbConn->getQueryBuilder(); |
|
700 | - $values = [ |
|
701 | - 'user_id' => $qb->createNamedParameter($user->getUID()), |
|
702 | - 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'), |
|
703 | - 'object_type' => $qb->createNamedParameter($objectType), |
|
704 | - 'object_id' => $qb->createNamedParameter($objectId), |
|
705 | - ]; |
|
706 | - |
|
707 | - // Strategy: try to update, if this does not return affected rows, do an insert. |
|
708 | - $affectedRows = $qb |
|
709 | - ->update('comments_read_markers') |
|
710 | - ->set('user_id', $values['user_id']) |
|
711 | - ->set('marker_datetime', $values['marker_datetime']) |
|
712 | - ->set('object_type', $values['object_type']) |
|
713 | - ->set('object_id', $values['object_id']) |
|
714 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
715 | - ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
716 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
717 | - ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
718 | - ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
719 | - ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
720 | - ->execute(); |
|
721 | - |
|
722 | - if ($affectedRows > 0) { |
|
723 | - return; |
|
724 | - } |
|
725 | - |
|
726 | - $qb->insert('comments_read_markers') |
|
727 | - ->values($values) |
|
728 | - ->execute(); |
|
729 | - } |
|
730 | - |
|
731 | - /** |
|
732 | - * returns the read marker for a given file to the specified date for the |
|
733 | - * provided user. It returns null, when the marker is not present, i.e. |
|
734 | - * no comments were marked as read. |
|
735 | - * |
|
736 | - * @param string $objectType |
|
737 | - * @param string $objectId |
|
738 | - * @param IUser $user |
|
739 | - * @return \DateTime|null |
|
740 | - * @since 9.0.0 |
|
741 | - */ |
|
742 | - public function getReadMark($objectType, $objectId, IUser $user) { |
|
743 | - $qb = $this->dbConn->getQueryBuilder(); |
|
744 | - $resultStatement = $qb->select('marker_datetime') |
|
745 | - ->from('comments_read_markers') |
|
746 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
747 | - ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
748 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
749 | - ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
750 | - ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
751 | - ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
752 | - ->execute(); |
|
753 | - |
|
754 | - $data = $resultStatement->fetch(); |
|
755 | - $resultStatement->closeCursor(); |
|
756 | - if (!$data || is_null($data['marker_datetime'])) { |
|
757 | - return null; |
|
758 | - } |
|
759 | - |
|
760 | - return new \DateTime($data['marker_datetime']); |
|
761 | - } |
|
762 | - |
|
763 | - /** |
|
764 | - * deletes the read markers on the specified object |
|
765 | - * |
|
766 | - * @param string $objectType |
|
767 | - * @param string $objectId |
|
768 | - * @return bool |
|
769 | - * @since 9.0.0 |
|
770 | - */ |
|
771 | - public function deleteReadMarksOnObject($objectType, $objectId) { |
|
772 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
773 | - |
|
774 | - $qb = $this->dbConn->getQueryBuilder(); |
|
775 | - $query = $qb->delete('comments_read_markers') |
|
776 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
777 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
778 | - ->setParameter('object_type', $objectType) |
|
779 | - ->setParameter('object_id', $objectId); |
|
780 | - |
|
781 | - try { |
|
782 | - $affectedRows = $query->execute(); |
|
783 | - } catch (DriverException $e) { |
|
784 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
785 | - return false; |
|
786 | - } |
|
787 | - return ($affectedRows > 0); |
|
788 | - } |
|
789 | - |
|
790 | - /** |
|
791 | - * registers an Entity to the manager, so event notifications can be send |
|
792 | - * to consumers of the comments infrastructure |
|
793 | - * |
|
794 | - * @param \Closure $closure |
|
795 | - */ |
|
796 | - public function registerEventHandler(\Closure $closure) { |
|
797 | - $this->eventHandlerClosures[] = $closure; |
|
798 | - $this->eventHandlers = []; |
|
799 | - } |
|
800 | - |
|
801 | - /** |
|
802 | - * registers a method that resolves an ID to a display name for a given type |
|
803 | - * |
|
804 | - * @param string $type |
|
805 | - * @param \Closure $closure |
|
806 | - * @throws \OutOfBoundsException |
|
807 | - * @since 11.0.0 |
|
808 | - * |
|
809 | - * Only one resolver shall be registered per type. Otherwise a |
|
810 | - * \OutOfBoundsException has to thrown. |
|
811 | - */ |
|
812 | - public function registerDisplayNameResolver($type, \Closure $closure) { |
|
813 | - if (!is_string($type)) { |
|
814 | - throw new \InvalidArgumentException('String expected.'); |
|
815 | - } |
|
816 | - if (isset($this->displayNameResolvers[$type])) { |
|
817 | - throw new \OutOfBoundsException('Displayname resolver for this type already registered'); |
|
818 | - } |
|
819 | - $this->displayNameResolvers[$type] = $closure; |
|
820 | - } |
|
821 | - |
|
822 | - /** |
|
823 | - * resolves a given ID of a given Type to a display name. |
|
824 | - * |
|
825 | - * @param string $type |
|
826 | - * @param string $id |
|
827 | - * @return string |
|
828 | - * @throws \OutOfBoundsException |
|
829 | - * @since 11.0.0 |
|
830 | - * |
|
831 | - * If a provided type was not registered, an \OutOfBoundsException shall |
|
832 | - * be thrown. It is upon the resolver discretion what to return of the |
|
833 | - * provided ID is unknown. It must be ensured that a string is returned. |
|
834 | - */ |
|
835 | - public function resolveDisplayName($type, $id) { |
|
836 | - if (!is_string($type)) { |
|
837 | - throw new \InvalidArgumentException('String expected.'); |
|
838 | - } |
|
839 | - if (!isset($this->displayNameResolvers[$type])) { |
|
840 | - throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
|
841 | - } |
|
842 | - return (string)$this->displayNameResolvers[$type]($id); |
|
843 | - } |
|
844 | - |
|
845 | - /** |
|
846 | - * returns valid, registered entities |
|
847 | - * |
|
848 | - * @return \OCP\Comments\ICommentsEventHandler[] |
|
849 | - */ |
|
850 | - private function getEventHandlers() { |
|
851 | - if (!empty($this->eventHandlers)) { |
|
852 | - return $this->eventHandlers; |
|
853 | - } |
|
854 | - |
|
855 | - $this->eventHandlers = []; |
|
856 | - foreach ($this->eventHandlerClosures as $name => $closure) { |
|
857 | - $entity = $closure(); |
|
858 | - if (!($entity instanceof ICommentsEventHandler)) { |
|
859 | - throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface'); |
|
860 | - } |
|
861 | - $this->eventHandlers[$name] = $entity; |
|
862 | - } |
|
863 | - |
|
864 | - return $this->eventHandlers; |
|
865 | - } |
|
866 | - |
|
867 | - /** |
|
868 | - * sends notifications to the registered entities |
|
869 | - * |
|
870 | - * @param $eventType |
|
871 | - * @param IComment $comment |
|
872 | - */ |
|
873 | - private function sendEvent($eventType, IComment $comment) { |
|
874 | - $entities = $this->getEventHandlers(); |
|
875 | - $event = new CommentsEvent($eventType, $comment); |
|
876 | - foreach ($entities as $entity) { |
|
877 | - $entity->handle($event); |
|
878 | - } |
|
879 | - } |
|
42 | + /** @var IDBConnection */ |
|
43 | + protected $dbConn; |
|
44 | + |
|
45 | + /** @var ILogger */ |
|
46 | + protected $logger; |
|
47 | + |
|
48 | + /** @var IConfig */ |
|
49 | + protected $config; |
|
50 | + |
|
51 | + /** @var IComment[] */ |
|
52 | + protected $commentsCache = []; |
|
53 | + |
|
54 | + /** @var \Closure[] */ |
|
55 | + protected $eventHandlerClosures = []; |
|
56 | + |
|
57 | + /** @var ICommentsEventHandler[] */ |
|
58 | + protected $eventHandlers = []; |
|
59 | + |
|
60 | + /** @var \Closure[] */ |
|
61 | + protected $displayNameResolvers = []; |
|
62 | + |
|
63 | + /** |
|
64 | + * Manager constructor. |
|
65 | + * |
|
66 | + * @param IDBConnection $dbConn |
|
67 | + * @param ILogger $logger |
|
68 | + * @param IConfig $config |
|
69 | + */ |
|
70 | + public function __construct( |
|
71 | + IDBConnection $dbConn, |
|
72 | + ILogger $logger, |
|
73 | + IConfig $config |
|
74 | + ) { |
|
75 | + $this->dbConn = $dbConn; |
|
76 | + $this->logger = $logger; |
|
77 | + $this->config = $config; |
|
78 | + } |
|
79 | + |
|
80 | + /** |
|
81 | + * converts data base data into PHP native, proper types as defined by |
|
82 | + * IComment interface. |
|
83 | + * |
|
84 | + * @param array $data |
|
85 | + * @return array |
|
86 | + */ |
|
87 | + protected function normalizeDatabaseData(array $data) { |
|
88 | + $data['id'] = strval($data['id']); |
|
89 | + $data['parent_id'] = strval($data['parent_id']); |
|
90 | + $data['topmost_parent_id'] = strval($data['topmost_parent_id']); |
|
91 | + $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']); |
|
92 | + if (!is_null($data['latest_child_timestamp'])) { |
|
93 | + $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']); |
|
94 | + } |
|
95 | + $data['children_count'] = intval($data['children_count']); |
|
96 | + return $data; |
|
97 | + } |
|
98 | + |
|
99 | + /** |
|
100 | + * prepares a comment for an insert or update operation after making sure |
|
101 | + * all necessary fields have a value assigned. |
|
102 | + * |
|
103 | + * @param IComment $comment |
|
104 | + * @return IComment returns the same updated IComment instance as provided |
|
105 | + * by parameter for convenience |
|
106 | + * @throws \UnexpectedValueException |
|
107 | + */ |
|
108 | + protected function prepareCommentForDatabaseWrite(IComment $comment) { |
|
109 | + if (!$comment->getActorType() |
|
110 | + || !$comment->getActorId() |
|
111 | + || !$comment->getObjectType() |
|
112 | + || !$comment->getObjectId() |
|
113 | + || !$comment->getVerb() |
|
114 | + ) { |
|
115 | + throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving'); |
|
116 | + } |
|
117 | + |
|
118 | + if ($comment->getId() === '') { |
|
119 | + $comment->setChildrenCount(0); |
|
120 | + $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC'))); |
|
121 | + $comment->setLatestChildDateTime(null); |
|
122 | + } |
|
123 | + |
|
124 | + if (is_null($comment->getCreationDateTime())) { |
|
125 | + $comment->setCreationDateTime(new \DateTime()); |
|
126 | + } |
|
127 | + |
|
128 | + if ($comment->getParentId() !== '0') { |
|
129 | + $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId())); |
|
130 | + } else { |
|
131 | + $comment->setTopmostParentId('0'); |
|
132 | + } |
|
133 | + |
|
134 | + $this->cache($comment); |
|
135 | + |
|
136 | + return $comment; |
|
137 | + } |
|
138 | + |
|
139 | + /** |
|
140 | + * returns the topmost parent id of a given comment identified by ID |
|
141 | + * |
|
142 | + * @param string $id |
|
143 | + * @return string |
|
144 | + * @throws NotFoundException |
|
145 | + */ |
|
146 | + protected function determineTopmostParentId($id) { |
|
147 | + $comment = $this->get($id); |
|
148 | + if ($comment->getParentId() === '0') { |
|
149 | + return $comment->getId(); |
|
150 | + } else { |
|
151 | + return $this->determineTopmostParentId($comment->getId()); |
|
152 | + } |
|
153 | + } |
|
154 | + |
|
155 | + /** |
|
156 | + * updates child information of a comment |
|
157 | + * |
|
158 | + * @param string $id |
|
159 | + * @param \DateTime $cDateTime the date time of the most recent child |
|
160 | + * @throws NotFoundException |
|
161 | + */ |
|
162 | + protected function updateChildrenInformation($id, \DateTime $cDateTime) { |
|
163 | + $qb = $this->dbConn->getQueryBuilder(); |
|
164 | + $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
165 | + ->from('comments') |
|
166 | + ->where($qb->expr()->eq('parent_id', $qb->createParameter('id'))) |
|
167 | + ->setParameter('id', $id); |
|
168 | + |
|
169 | + $resultStatement = $query->execute(); |
|
170 | + $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
171 | + $resultStatement->closeCursor(); |
|
172 | + $children = intval($data[0]); |
|
173 | + |
|
174 | + $comment = $this->get($id); |
|
175 | + $comment->setChildrenCount($children); |
|
176 | + $comment->setLatestChildDateTime($cDateTime); |
|
177 | + $this->save($comment); |
|
178 | + } |
|
179 | + |
|
180 | + /** |
|
181 | + * Tests whether actor or object type and id parameters are acceptable. |
|
182 | + * Throws exception if not. |
|
183 | + * |
|
184 | + * @param string $role |
|
185 | + * @param string $type |
|
186 | + * @param string $id |
|
187 | + * @throws \InvalidArgumentException |
|
188 | + */ |
|
189 | + protected function checkRoleParameters($role, $type, $id) { |
|
190 | + if ( |
|
191 | + !is_string($type) || empty($type) |
|
192 | + || !is_string($id) || empty($id) |
|
193 | + ) { |
|
194 | + throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
195 | + } |
|
196 | + } |
|
197 | + |
|
198 | + /** |
|
199 | + * run-time caches a comment |
|
200 | + * |
|
201 | + * @param IComment $comment |
|
202 | + */ |
|
203 | + protected function cache(IComment $comment) { |
|
204 | + $id = $comment->getId(); |
|
205 | + if (empty($id)) { |
|
206 | + return; |
|
207 | + } |
|
208 | + $this->commentsCache[strval($id)] = $comment; |
|
209 | + } |
|
210 | + |
|
211 | + /** |
|
212 | + * removes an entry from the comments run time cache |
|
213 | + * |
|
214 | + * @param mixed $id the comment's id |
|
215 | + */ |
|
216 | + protected function uncache($id) { |
|
217 | + $id = strval($id); |
|
218 | + if (isset($this->commentsCache[$id])) { |
|
219 | + unset($this->commentsCache[$id]); |
|
220 | + } |
|
221 | + } |
|
222 | + |
|
223 | + /** |
|
224 | + * returns a comment instance |
|
225 | + * |
|
226 | + * @param string $id the ID of the comment |
|
227 | + * @return IComment |
|
228 | + * @throws NotFoundException |
|
229 | + * @throws \InvalidArgumentException |
|
230 | + * @since 9.0.0 |
|
231 | + */ |
|
232 | + public function get($id) { |
|
233 | + if (intval($id) === 0) { |
|
234 | + throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.'); |
|
235 | + } |
|
236 | + |
|
237 | + if (isset($this->commentsCache[$id])) { |
|
238 | + return $this->commentsCache[$id]; |
|
239 | + } |
|
240 | + |
|
241 | + $qb = $this->dbConn->getQueryBuilder(); |
|
242 | + $resultStatement = $qb->select('*') |
|
243 | + ->from('comments') |
|
244 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
245 | + ->setParameter('id', $id, IQueryBuilder::PARAM_INT) |
|
246 | + ->execute(); |
|
247 | + |
|
248 | + $data = $resultStatement->fetch(); |
|
249 | + $resultStatement->closeCursor(); |
|
250 | + if (!$data) { |
|
251 | + throw new NotFoundException(); |
|
252 | + } |
|
253 | + |
|
254 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
255 | + $this->cache($comment); |
|
256 | + return $comment; |
|
257 | + } |
|
258 | + |
|
259 | + /** |
|
260 | + * returns the comment specified by the id and all it's child comments. |
|
261 | + * At this point of time, we do only support one level depth. |
|
262 | + * |
|
263 | + * @param string $id |
|
264 | + * @param int $limit max number of entries to return, 0 returns all |
|
265 | + * @param int $offset the start entry |
|
266 | + * @return array |
|
267 | + * @since 9.0.0 |
|
268 | + * |
|
269 | + * The return array looks like this |
|
270 | + * [ |
|
271 | + * 'comment' => IComment, // root comment |
|
272 | + * 'replies' => |
|
273 | + * [ |
|
274 | + * 0 => |
|
275 | + * [ |
|
276 | + * 'comment' => IComment, |
|
277 | + * 'replies' => [] |
|
278 | + * ] |
|
279 | + * 1 => |
|
280 | + * [ |
|
281 | + * 'comment' => IComment, |
|
282 | + * 'replies'=> [] |
|
283 | + * ], |
|
284 | + * … |
|
285 | + * ] |
|
286 | + * ] |
|
287 | + */ |
|
288 | + public function getTree($id, $limit = 0, $offset = 0) { |
|
289 | + $tree = []; |
|
290 | + $tree['comment'] = $this->get($id); |
|
291 | + $tree['replies'] = []; |
|
292 | + |
|
293 | + $qb = $this->dbConn->getQueryBuilder(); |
|
294 | + $query = $qb->select('*') |
|
295 | + ->from('comments') |
|
296 | + ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id'))) |
|
297 | + ->orderBy('creation_timestamp', 'DESC') |
|
298 | + ->setParameter('id', $id); |
|
299 | + |
|
300 | + if ($limit > 0) { |
|
301 | + $query->setMaxResults($limit); |
|
302 | + } |
|
303 | + if ($offset > 0) { |
|
304 | + $query->setFirstResult($offset); |
|
305 | + } |
|
306 | + |
|
307 | + $resultStatement = $query->execute(); |
|
308 | + while ($data = $resultStatement->fetch()) { |
|
309 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
310 | + $this->cache($comment); |
|
311 | + $tree['replies'][] = [ |
|
312 | + 'comment' => $comment, |
|
313 | + 'replies' => [] |
|
314 | + ]; |
|
315 | + } |
|
316 | + $resultStatement->closeCursor(); |
|
317 | + |
|
318 | + return $tree; |
|
319 | + } |
|
320 | + |
|
321 | + /** |
|
322 | + * returns comments for a specific object (e.g. a file). |
|
323 | + * |
|
324 | + * The sort order is always newest to oldest. |
|
325 | + * |
|
326 | + * @param string $objectType the object type, e.g. 'files' |
|
327 | + * @param string $objectId the id of the object |
|
328 | + * @param int $limit optional, number of maximum comments to be returned. if |
|
329 | + * not specified, all comments are returned. |
|
330 | + * @param int $offset optional, starting point |
|
331 | + * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
332 | + * that may be returned |
|
333 | + * @return IComment[] |
|
334 | + * @since 9.0.0 |
|
335 | + */ |
|
336 | + public function getForObject( |
|
337 | + $objectType, |
|
338 | + $objectId, |
|
339 | + $limit = 0, |
|
340 | + $offset = 0, |
|
341 | + \DateTime $notOlderThan = null |
|
342 | + ) { |
|
343 | + $comments = []; |
|
344 | + |
|
345 | + $qb = $this->dbConn->getQueryBuilder(); |
|
346 | + $query = $qb->select('*') |
|
347 | + ->from('comments') |
|
348 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
349 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
350 | + ->orderBy('creation_timestamp', 'DESC') |
|
351 | + ->setParameter('type', $objectType) |
|
352 | + ->setParameter('id', $objectId); |
|
353 | + |
|
354 | + if ($limit > 0) { |
|
355 | + $query->setMaxResults($limit); |
|
356 | + } |
|
357 | + if ($offset > 0) { |
|
358 | + $query->setFirstResult($offset); |
|
359 | + } |
|
360 | + if (!is_null($notOlderThan)) { |
|
361 | + $query |
|
362 | + ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
363 | + ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
364 | + } |
|
365 | + |
|
366 | + $resultStatement = $query->execute(); |
|
367 | + while ($data = $resultStatement->fetch()) { |
|
368 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
369 | + $this->cache($comment); |
|
370 | + $comments[] = $comment; |
|
371 | + } |
|
372 | + $resultStatement->closeCursor(); |
|
373 | + |
|
374 | + return $comments; |
|
375 | + } |
|
376 | + |
|
377 | + /** |
|
378 | + * @param $objectType string the object type, e.g. 'files' |
|
379 | + * @param $objectId string the id of the object |
|
380 | + * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
381 | + * that may be returned |
|
382 | + * @return Int |
|
383 | + * @since 9.0.0 |
|
384 | + */ |
|
385 | + public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) { |
|
386 | + $qb = $this->dbConn->getQueryBuilder(); |
|
387 | + $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
388 | + ->from('comments') |
|
389 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
390 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
391 | + ->setParameter('type', $objectType) |
|
392 | + ->setParameter('id', $objectId); |
|
393 | + |
|
394 | + if (!is_null($notOlderThan)) { |
|
395 | + $query |
|
396 | + ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
397 | + ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
398 | + } |
|
399 | + |
|
400 | + $resultStatement = $query->execute(); |
|
401 | + $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
402 | + $resultStatement->closeCursor(); |
|
403 | + return intval($data[0]); |
|
404 | + } |
|
405 | + |
|
406 | + /** |
|
407 | + * Get the number of unread comments for all files in a folder |
|
408 | + * |
|
409 | + * @param int $folderId |
|
410 | + * @param IUser $user |
|
411 | + * @return array [$fileId => $unreadCount] |
|
412 | + */ |
|
413 | + public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) { |
|
414 | + $qb = $this->dbConn->getQueryBuilder(); |
|
415 | + $query = $qb->select('fileid', $qb->createFunction( |
|
416 | + 'COUNT(' . $qb->getColumnName('c.id') . ')') |
|
417 | + )->from('comments', 'c') |
|
418 | + ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX( |
|
419 | + $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')), |
|
420 | + $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)) |
|
421 | + )) |
|
422 | + ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX( |
|
423 | + $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')), |
|
424 | + $qb->expr()->eq('m.object_id', 'c.object_id'), |
|
425 | + $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())) |
|
426 | + )) |
|
427 | + ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId))) |
|
428 | + ->andWhere($qb->expr()->orX( |
|
429 | + $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'), |
|
430 | + $qb->expr()->isNull('marker_datetime') |
|
431 | + )) |
|
432 | + ->groupBy('f.fileid'); |
|
433 | + |
|
434 | + $resultStatement = $query->execute(); |
|
435 | + return array_map(function ($count) { |
|
436 | + return (int)$count; |
|
437 | + }, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR)); |
|
438 | + } |
|
439 | + |
|
440 | + /** |
|
441 | + * creates a new comment and returns it. At this point of time, it is not |
|
442 | + * saved in the used data storage. Use save() after setting other fields |
|
443 | + * of the comment (e.g. message or verb). |
|
444 | + * |
|
445 | + * @param string $actorType the actor type (e.g. 'users') |
|
446 | + * @param string $actorId a user id |
|
447 | + * @param string $objectType the object type the comment is attached to |
|
448 | + * @param string $objectId the object id the comment is attached to |
|
449 | + * @return IComment |
|
450 | + * @since 9.0.0 |
|
451 | + */ |
|
452 | + public function create($actorType, $actorId, $objectType, $objectId) { |
|
453 | + $comment = new Comment(); |
|
454 | + $comment |
|
455 | + ->setActor($actorType, $actorId) |
|
456 | + ->setObject($objectType, $objectId); |
|
457 | + return $comment; |
|
458 | + } |
|
459 | + |
|
460 | + /** |
|
461 | + * permanently deletes the comment specified by the ID |
|
462 | + * |
|
463 | + * When the comment has child comments, their parent ID will be changed to |
|
464 | + * the parent ID of the item that is to be deleted. |
|
465 | + * |
|
466 | + * @param string $id |
|
467 | + * @return bool |
|
468 | + * @throws \InvalidArgumentException |
|
469 | + * @since 9.0.0 |
|
470 | + */ |
|
471 | + public function delete($id) { |
|
472 | + if (!is_string($id)) { |
|
473 | + throw new \InvalidArgumentException('Parameter must be string'); |
|
474 | + } |
|
475 | + |
|
476 | + try { |
|
477 | + $comment = $this->get($id); |
|
478 | + } catch (\Exception $e) { |
|
479 | + // Ignore exceptions, we just don't fire a hook then |
|
480 | + $comment = null; |
|
481 | + } |
|
482 | + |
|
483 | + $qb = $this->dbConn->getQueryBuilder(); |
|
484 | + $query = $qb->delete('comments') |
|
485 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
486 | + ->setParameter('id', $id); |
|
487 | + |
|
488 | + try { |
|
489 | + $affectedRows = $query->execute(); |
|
490 | + $this->uncache($id); |
|
491 | + } catch (DriverException $e) { |
|
492 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
493 | + return false; |
|
494 | + } |
|
495 | + |
|
496 | + if ($affectedRows > 0 && $comment instanceof IComment) { |
|
497 | + $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment); |
|
498 | + } |
|
499 | + |
|
500 | + return ($affectedRows > 0); |
|
501 | + } |
|
502 | + |
|
503 | + /** |
|
504 | + * saves the comment permanently |
|
505 | + * |
|
506 | + * if the supplied comment has an empty ID, a new entry comment will be |
|
507 | + * saved and the instance updated with the new ID. |
|
508 | + * |
|
509 | + * Otherwise, an existing comment will be updated. |
|
510 | + * |
|
511 | + * Throws NotFoundException when a comment that is to be updated does not |
|
512 | + * exist anymore at this point of time. |
|
513 | + * |
|
514 | + * @param IComment $comment |
|
515 | + * @return bool |
|
516 | + * @throws NotFoundException |
|
517 | + * @since 9.0.0 |
|
518 | + */ |
|
519 | + public function save(IComment $comment) { |
|
520 | + if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
521 | + $result = $this->insert($comment); |
|
522 | + } else { |
|
523 | + $result = $this->update($comment); |
|
524 | + } |
|
525 | + |
|
526 | + if ($result && !!$comment->getParentId()) { |
|
527 | + $this->updateChildrenInformation( |
|
528 | + $comment->getParentId(), |
|
529 | + $comment->getCreationDateTime() |
|
530 | + ); |
|
531 | + $this->cache($comment); |
|
532 | + } |
|
533 | + |
|
534 | + return $result; |
|
535 | + } |
|
536 | + |
|
537 | + /** |
|
538 | + * inserts the provided comment in the database |
|
539 | + * |
|
540 | + * @param IComment $comment |
|
541 | + * @return bool |
|
542 | + */ |
|
543 | + protected function insert(IComment &$comment) { |
|
544 | + $qb = $this->dbConn->getQueryBuilder(); |
|
545 | + $affectedRows = $qb |
|
546 | + ->insert('comments') |
|
547 | + ->values([ |
|
548 | + 'parent_id' => $qb->createNamedParameter($comment->getParentId()), |
|
549 | + 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), |
|
550 | + 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), |
|
551 | + 'actor_type' => $qb->createNamedParameter($comment->getActorType()), |
|
552 | + 'actor_id' => $qb->createNamedParameter($comment->getActorId()), |
|
553 | + 'message' => $qb->createNamedParameter($comment->getMessage()), |
|
554 | + 'verb' => $qb->createNamedParameter($comment->getVerb()), |
|
555 | + 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), |
|
556 | + 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), |
|
557 | + 'object_type' => $qb->createNamedParameter($comment->getObjectType()), |
|
558 | + 'object_id' => $qb->createNamedParameter($comment->getObjectId()), |
|
559 | + ]) |
|
560 | + ->execute(); |
|
561 | + |
|
562 | + if ($affectedRows > 0) { |
|
563 | + $comment->setId(strval($qb->getLastInsertId())); |
|
564 | + $this->sendEvent(CommentsEvent::EVENT_ADD, $comment); |
|
565 | + } |
|
566 | + |
|
567 | + return $affectedRows > 0; |
|
568 | + } |
|
569 | + |
|
570 | + /** |
|
571 | + * updates a Comment data row |
|
572 | + * |
|
573 | + * @param IComment $comment |
|
574 | + * @return bool |
|
575 | + * @throws NotFoundException |
|
576 | + */ |
|
577 | + protected function update(IComment $comment) { |
|
578 | + // for properly working preUpdate Events we need the old comments as is |
|
579 | + // in the DB and overcome caching. Also avoid that outdated information stays. |
|
580 | + $this->uncache($comment->getId()); |
|
581 | + $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId())); |
|
582 | + $this->uncache($comment->getId()); |
|
583 | + |
|
584 | + $qb = $this->dbConn->getQueryBuilder(); |
|
585 | + $affectedRows = $qb |
|
586 | + ->update('comments') |
|
587 | + ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
588 | + ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
589 | + ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
590 | + ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
591 | + ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
592 | + ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
593 | + ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
594 | + ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
595 | + ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
596 | + ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
597 | + ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
598 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
599 | + ->setParameter('id', $comment->getId()) |
|
600 | + ->execute(); |
|
601 | + |
|
602 | + if ($affectedRows === 0) { |
|
603 | + throw new NotFoundException('Comment to update does ceased to exist'); |
|
604 | + } |
|
605 | + |
|
606 | + $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); |
|
607 | + |
|
608 | + return $affectedRows > 0; |
|
609 | + } |
|
610 | + |
|
611 | + /** |
|
612 | + * removes references to specific actor (e.g. on user delete) of a comment. |
|
613 | + * The comment itself must not get lost/deleted. |
|
614 | + * |
|
615 | + * @param string $actorType the actor type (e.g. 'users') |
|
616 | + * @param string $actorId a user id |
|
617 | + * @return boolean |
|
618 | + * @since 9.0.0 |
|
619 | + */ |
|
620 | + public function deleteReferencesOfActor($actorType, $actorId) { |
|
621 | + $this->checkRoleParameters('Actor', $actorType, $actorId); |
|
622 | + |
|
623 | + $qb = $this->dbConn->getQueryBuilder(); |
|
624 | + $affectedRows = $qb |
|
625 | + ->update('comments') |
|
626 | + ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
627 | + ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
628 | + ->where($qb->expr()->eq('actor_type', $qb->createParameter('type'))) |
|
629 | + ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id'))) |
|
630 | + ->setParameter('type', $actorType) |
|
631 | + ->setParameter('id', $actorId) |
|
632 | + ->execute(); |
|
633 | + |
|
634 | + $this->commentsCache = []; |
|
635 | + |
|
636 | + return is_int($affectedRows); |
|
637 | + } |
|
638 | + |
|
639 | + /** |
|
640 | + * deletes all comments made of a specific object (e.g. on file delete) |
|
641 | + * |
|
642 | + * @param string $objectType the object type (e.g. 'files') |
|
643 | + * @param string $objectId e.g. the file id |
|
644 | + * @return boolean |
|
645 | + * @since 9.0.0 |
|
646 | + */ |
|
647 | + public function deleteCommentsAtObject($objectType, $objectId) { |
|
648 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
649 | + |
|
650 | + $qb = $this->dbConn->getQueryBuilder(); |
|
651 | + $affectedRows = $qb |
|
652 | + ->delete('comments') |
|
653 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
654 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
655 | + ->setParameter('type', $objectType) |
|
656 | + ->setParameter('id', $objectId) |
|
657 | + ->execute(); |
|
658 | + |
|
659 | + $this->commentsCache = []; |
|
660 | + |
|
661 | + return is_int($affectedRows); |
|
662 | + } |
|
663 | + |
|
664 | + /** |
|
665 | + * deletes the read markers for the specified user |
|
666 | + * |
|
667 | + * @param \OCP\IUser $user |
|
668 | + * @return bool |
|
669 | + * @since 9.0.0 |
|
670 | + */ |
|
671 | + public function deleteReadMarksFromUser(IUser $user) { |
|
672 | + $qb = $this->dbConn->getQueryBuilder(); |
|
673 | + $query = $qb->delete('comments_read_markers') |
|
674 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
675 | + ->setParameter('user_id', $user->getUID()); |
|
676 | + |
|
677 | + try { |
|
678 | + $affectedRows = $query->execute(); |
|
679 | + } catch (DriverException $e) { |
|
680 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
681 | + return false; |
|
682 | + } |
|
683 | + return ($affectedRows > 0); |
|
684 | + } |
|
685 | + |
|
686 | + /** |
|
687 | + * sets the read marker for a given file to the specified date for the |
|
688 | + * provided user |
|
689 | + * |
|
690 | + * @param string $objectType |
|
691 | + * @param string $objectId |
|
692 | + * @param \DateTime $dateTime |
|
693 | + * @param IUser $user |
|
694 | + * @since 9.0.0 |
|
695 | + */ |
|
696 | + public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) { |
|
697 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
698 | + |
|
699 | + $qb = $this->dbConn->getQueryBuilder(); |
|
700 | + $values = [ |
|
701 | + 'user_id' => $qb->createNamedParameter($user->getUID()), |
|
702 | + 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'), |
|
703 | + 'object_type' => $qb->createNamedParameter($objectType), |
|
704 | + 'object_id' => $qb->createNamedParameter($objectId), |
|
705 | + ]; |
|
706 | + |
|
707 | + // Strategy: try to update, if this does not return affected rows, do an insert. |
|
708 | + $affectedRows = $qb |
|
709 | + ->update('comments_read_markers') |
|
710 | + ->set('user_id', $values['user_id']) |
|
711 | + ->set('marker_datetime', $values['marker_datetime']) |
|
712 | + ->set('object_type', $values['object_type']) |
|
713 | + ->set('object_id', $values['object_id']) |
|
714 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
715 | + ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
716 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
717 | + ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
718 | + ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
719 | + ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
720 | + ->execute(); |
|
721 | + |
|
722 | + if ($affectedRows > 0) { |
|
723 | + return; |
|
724 | + } |
|
725 | + |
|
726 | + $qb->insert('comments_read_markers') |
|
727 | + ->values($values) |
|
728 | + ->execute(); |
|
729 | + } |
|
730 | + |
|
731 | + /** |
|
732 | + * returns the read marker for a given file to the specified date for the |
|
733 | + * provided user. It returns null, when the marker is not present, i.e. |
|
734 | + * no comments were marked as read. |
|
735 | + * |
|
736 | + * @param string $objectType |
|
737 | + * @param string $objectId |
|
738 | + * @param IUser $user |
|
739 | + * @return \DateTime|null |
|
740 | + * @since 9.0.0 |
|
741 | + */ |
|
742 | + public function getReadMark($objectType, $objectId, IUser $user) { |
|
743 | + $qb = $this->dbConn->getQueryBuilder(); |
|
744 | + $resultStatement = $qb->select('marker_datetime') |
|
745 | + ->from('comments_read_markers') |
|
746 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
747 | + ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
748 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
749 | + ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
750 | + ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
751 | + ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
752 | + ->execute(); |
|
753 | + |
|
754 | + $data = $resultStatement->fetch(); |
|
755 | + $resultStatement->closeCursor(); |
|
756 | + if (!$data || is_null($data['marker_datetime'])) { |
|
757 | + return null; |
|
758 | + } |
|
759 | + |
|
760 | + return new \DateTime($data['marker_datetime']); |
|
761 | + } |
|
762 | + |
|
763 | + /** |
|
764 | + * deletes the read markers on the specified object |
|
765 | + * |
|
766 | + * @param string $objectType |
|
767 | + * @param string $objectId |
|
768 | + * @return bool |
|
769 | + * @since 9.0.0 |
|
770 | + */ |
|
771 | + public function deleteReadMarksOnObject($objectType, $objectId) { |
|
772 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
773 | + |
|
774 | + $qb = $this->dbConn->getQueryBuilder(); |
|
775 | + $query = $qb->delete('comments_read_markers') |
|
776 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
777 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
778 | + ->setParameter('object_type', $objectType) |
|
779 | + ->setParameter('object_id', $objectId); |
|
780 | + |
|
781 | + try { |
|
782 | + $affectedRows = $query->execute(); |
|
783 | + } catch (DriverException $e) { |
|
784 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
785 | + return false; |
|
786 | + } |
|
787 | + return ($affectedRows > 0); |
|
788 | + } |
|
789 | + |
|
790 | + /** |
|
791 | + * registers an Entity to the manager, so event notifications can be send |
|
792 | + * to consumers of the comments infrastructure |
|
793 | + * |
|
794 | + * @param \Closure $closure |
|
795 | + */ |
|
796 | + public function registerEventHandler(\Closure $closure) { |
|
797 | + $this->eventHandlerClosures[] = $closure; |
|
798 | + $this->eventHandlers = []; |
|
799 | + } |
|
800 | + |
|
801 | + /** |
|
802 | + * registers a method that resolves an ID to a display name for a given type |
|
803 | + * |
|
804 | + * @param string $type |
|
805 | + * @param \Closure $closure |
|
806 | + * @throws \OutOfBoundsException |
|
807 | + * @since 11.0.0 |
|
808 | + * |
|
809 | + * Only one resolver shall be registered per type. Otherwise a |
|
810 | + * \OutOfBoundsException has to thrown. |
|
811 | + */ |
|
812 | + public function registerDisplayNameResolver($type, \Closure $closure) { |
|
813 | + if (!is_string($type)) { |
|
814 | + throw new \InvalidArgumentException('String expected.'); |
|
815 | + } |
|
816 | + if (isset($this->displayNameResolvers[$type])) { |
|
817 | + throw new \OutOfBoundsException('Displayname resolver for this type already registered'); |
|
818 | + } |
|
819 | + $this->displayNameResolvers[$type] = $closure; |
|
820 | + } |
|
821 | + |
|
822 | + /** |
|
823 | + * resolves a given ID of a given Type to a display name. |
|
824 | + * |
|
825 | + * @param string $type |
|
826 | + * @param string $id |
|
827 | + * @return string |
|
828 | + * @throws \OutOfBoundsException |
|
829 | + * @since 11.0.0 |
|
830 | + * |
|
831 | + * If a provided type was not registered, an \OutOfBoundsException shall |
|
832 | + * be thrown. It is upon the resolver discretion what to return of the |
|
833 | + * provided ID is unknown. It must be ensured that a string is returned. |
|
834 | + */ |
|
835 | + public function resolveDisplayName($type, $id) { |
|
836 | + if (!is_string($type)) { |
|
837 | + throw new \InvalidArgumentException('String expected.'); |
|
838 | + } |
|
839 | + if (!isset($this->displayNameResolvers[$type])) { |
|
840 | + throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
|
841 | + } |
|
842 | + return (string)$this->displayNameResolvers[$type]($id); |
|
843 | + } |
|
844 | + |
|
845 | + /** |
|
846 | + * returns valid, registered entities |
|
847 | + * |
|
848 | + * @return \OCP\Comments\ICommentsEventHandler[] |
|
849 | + */ |
|
850 | + private function getEventHandlers() { |
|
851 | + if (!empty($this->eventHandlers)) { |
|
852 | + return $this->eventHandlers; |
|
853 | + } |
|
854 | + |
|
855 | + $this->eventHandlers = []; |
|
856 | + foreach ($this->eventHandlerClosures as $name => $closure) { |
|
857 | + $entity = $closure(); |
|
858 | + if (!($entity instanceof ICommentsEventHandler)) { |
|
859 | + throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface'); |
|
860 | + } |
|
861 | + $this->eventHandlers[$name] = $entity; |
|
862 | + } |
|
863 | + |
|
864 | + return $this->eventHandlers; |
|
865 | + } |
|
866 | + |
|
867 | + /** |
|
868 | + * sends notifications to the registered entities |
|
869 | + * |
|
870 | + * @param $eventType |
|
871 | + * @param IComment $comment |
|
872 | + */ |
|
873 | + private function sendEvent($eventType, IComment $comment) { |
|
874 | + $entities = $this->getEventHandlers(); |
|
875 | + $event = new CommentsEvent($eventType, $comment); |
|
876 | + foreach ($entities as $entity) { |
|
877 | + $entity->handle($event); |
|
878 | + } |
|
879 | + } |
|
880 | 880 | } |
@@ -191,7 +191,7 @@ discard block |
||
191 | 191 | !is_string($type) || empty($type) |
192 | 192 | || !is_string($id) || empty($id) |
193 | 193 | ) { |
194 | - throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
194 | + throw new \InvalidArgumentException($role.' parameters must be string and not empty'); |
|
195 | 195 | } |
196 | 196 | } |
197 | 197 | |
@@ -413,7 +413,7 @@ discard block |
||
413 | 413 | public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) { |
414 | 414 | $qb = $this->dbConn->getQueryBuilder(); |
415 | 415 | $query = $qb->select('fileid', $qb->createFunction( |
416 | - 'COUNT(' . $qb->getColumnName('c.id') . ')') |
|
416 | + 'COUNT('.$qb->getColumnName('c.id').')') |
|
417 | 417 | )->from('comments', 'c') |
418 | 418 | ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX( |
419 | 419 | $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')), |
@@ -432,8 +432,8 @@ discard block |
||
432 | 432 | ->groupBy('f.fileid'); |
433 | 433 | |
434 | 434 | $resultStatement = $query->execute(); |
435 | - return array_map(function ($count) { |
|
436 | - return (int)$count; |
|
435 | + return array_map(function($count) { |
|
436 | + return (int) $count; |
|
437 | 437 | }, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR)); |
438 | 438 | } |
439 | 439 | |
@@ -540,7 +540,7 @@ discard block |
||
540 | 540 | * @param IComment $comment |
541 | 541 | * @return bool |
542 | 542 | */ |
543 | - protected function insert(IComment &$comment) { |
|
543 | + protected function insert(IComment & $comment) { |
|
544 | 544 | $qb = $this->dbConn->getQueryBuilder(); |
545 | 545 | $affectedRows = $qb |
546 | 546 | ->insert('comments') |
@@ -839,7 +839,7 @@ discard block |
||
839 | 839 | if (!isset($this->displayNameResolvers[$type])) { |
840 | 840 | throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
841 | 841 | } |
842 | - return (string)$this->displayNameResolvers[$type]($id); |
|
842 | + return (string) $this->displayNameResolvers[$type]($id); |
|
843 | 843 | } |
844 | 844 | |
845 | 845 | /** |
@@ -173,7 +173,7 @@ discard block |
||
173 | 173 | * If an SQLLogger is configured, the execution is logged. |
174 | 174 | * |
175 | 175 | * @param string $query The SQL query to execute. |
176 | - * @param array $params The parameters to bind to the query, if any. |
|
176 | + * @param string[] $params The parameters to bind to the query, if any. |
|
177 | 177 | * @param array $types The types the previous parameters are in. |
178 | 178 | * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
179 | 179 | * |
@@ -218,7 +218,7 @@ discard block |
||
218 | 218 | * columns or sequences. |
219 | 219 | * |
220 | 220 | * @param string $seqName Name of the sequence object from which the ID should be returned. |
221 | - * @return string A string representation of the last inserted ID. |
|
221 | + * @return integer A string representation of the last inserted ID. |
|
222 | 222 | */ |
223 | 223 | public function lastInsertId($seqName = null) { |
224 | 224 | if ($seqName) { |
@@ -56,7 +56,7 @@ discard block |
||
56 | 56 | return parent::connect(); |
57 | 57 | } catch (DBALException $e) { |
58 | 58 | // throw a new exception to prevent leaking info from the stacktrace |
59 | - throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
59 | + throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode()); |
|
60 | 60 | } |
61 | 61 | } |
62 | 62 | |
@@ -104,7 +104,7 @@ discard block |
||
104 | 104 | // 0 is the method where we use `getCallerBacktrace` |
105 | 105 | // 1 is the target method which uses the method we want to log |
106 | 106 | if (isset($traces[1])) { |
107 | - return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
107 | + return $traces[1]['file'].':'.$traces[1]['line']; |
|
108 | 108 | } |
109 | 109 | |
110 | 110 | return ''; |
@@ -150,7 +150,7 @@ discard block |
||
150 | 150 | * @param int $offset |
151 | 151 | * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
152 | 152 | */ |
153 | - public function prepare( $statement, $limit=null, $offset=null ) { |
|
153 | + public function prepare($statement, $limit = null, $offset = null) { |
|
154 | 154 | if ($limit === -1) { |
155 | 155 | $limit = null; |
156 | 156 | } |
@@ -161,7 +161,7 @@ discard block |
||
161 | 161 | $statement = $this->replaceTablePrefix($statement); |
162 | 162 | $statement = $this->adapter->fixupStatement($statement); |
163 | 163 | |
164 | - if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) { |
|
164 | + if (\OC::$server->getSystemConfig()->getValue('log_query', false)) { |
|
165 | 165 | \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG); |
166 | 166 | } |
167 | 167 | return parent::prepare($statement); |
@@ -318,7 +318,7 @@ discard block |
||
318 | 318 | throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
319 | 319 | } |
320 | 320 | |
321 | - $tableName = $this->tablePrefix . $tableName; |
|
321 | + $tableName = $this->tablePrefix.$tableName; |
|
322 | 322 | $this->lockedTable = $tableName; |
323 | 323 | $this->adapter->lockTable($tableName); |
324 | 324 | } |
@@ -339,11 +339,11 @@ discard block |
||
339 | 339 | * @return string |
340 | 340 | */ |
341 | 341 | public function getError() { |
342 | - $msg = $this->errorCode() . ': '; |
|
342 | + $msg = $this->errorCode().': '; |
|
343 | 343 | $errorInfo = $this->errorInfo(); |
344 | 344 | if (is_array($errorInfo)) { |
345 | - $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
346 | - $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
345 | + $msg .= 'SQLSTATE = '.$errorInfo[0].', '; |
|
346 | + $msg .= 'Driver Code = '.$errorInfo[1].', '; |
|
347 | 347 | $msg .= 'Driver Message = '.$errorInfo[2]; |
348 | 348 | } |
349 | 349 | return $msg; |
@@ -355,9 +355,9 @@ discard block |
||
355 | 355 | * @param string $table table name without the prefix |
356 | 356 | */ |
357 | 357 | public function dropTable($table) { |
358 | - $table = $this->tablePrefix . trim($table); |
|
358 | + $table = $this->tablePrefix.trim($table); |
|
359 | 359 | $schema = $this->getSchemaManager(); |
360 | - if($schema->tablesExist(array($table))) { |
|
360 | + if ($schema->tablesExist(array($table))) { |
|
361 | 361 | $schema->dropTable($table); |
362 | 362 | } |
363 | 363 | } |
@@ -368,8 +368,8 @@ discard block |
||
368 | 368 | * @param string $table table name without the prefix |
369 | 369 | * @return bool |
370 | 370 | */ |
371 | - public function tableExists($table){ |
|
372 | - $table = $this->tablePrefix . trim($table); |
|
371 | + public function tableExists($table) { |
|
372 | + $table = $this->tablePrefix.trim($table); |
|
373 | 373 | $schema = $this->getSchemaManager(); |
374 | 374 | return $schema->tablesExist(array($table)); |
375 | 375 | } |
@@ -380,7 +380,7 @@ discard block |
||
380 | 380 | * @return string |
381 | 381 | */ |
382 | 382 | protected function replaceTablePrefix($statement) { |
383 | - return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
383 | + return str_replace('*PREFIX*', $this->tablePrefix, $statement); |
|
384 | 384 | } |
385 | 385 | |
386 | 386 | /** |
@@ -41,384 +41,384 @@ |
||
41 | 41 | use OCP\PreConditionNotMetException; |
42 | 42 | |
43 | 43 | class Connection extends \Doctrine\DBAL\Connection implements IDBConnection { |
44 | - /** |
|
45 | - * @var string $tablePrefix |
|
46 | - */ |
|
47 | - protected $tablePrefix; |
|
48 | - |
|
49 | - /** |
|
50 | - * @var \OC\DB\Adapter $adapter |
|
51 | - */ |
|
52 | - protected $adapter; |
|
53 | - |
|
54 | - protected $lockedTable = null; |
|
55 | - |
|
56 | - public function connect() { |
|
57 | - try { |
|
58 | - return parent::connect(); |
|
59 | - } catch (DBALException $e) { |
|
60 | - // throw a new exception to prevent leaking info from the stacktrace |
|
61 | - throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
62 | - } |
|
63 | - } |
|
64 | - |
|
65 | - /** |
|
66 | - * Returns a QueryBuilder for the connection. |
|
67 | - * |
|
68 | - * @return \OCP\DB\QueryBuilder\IQueryBuilder |
|
69 | - */ |
|
70 | - public function getQueryBuilder() { |
|
71 | - return new QueryBuilder( |
|
72 | - $this, |
|
73 | - \OC::$server->getSystemConfig(), |
|
74 | - \OC::$server->getLogger() |
|
75 | - ); |
|
76 | - } |
|
77 | - |
|
78 | - /** |
|
79 | - * Gets the QueryBuilder for the connection. |
|
80 | - * |
|
81 | - * @return \Doctrine\DBAL\Query\QueryBuilder |
|
82 | - * @deprecated please use $this->getQueryBuilder() instead |
|
83 | - */ |
|
84 | - public function createQueryBuilder() { |
|
85 | - $backtrace = $this->getCallerBacktrace(); |
|
86 | - \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
87 | - return parent::createQueryBuilder(); |
|
88 | - } |
|
89 | - |
|
90 | - /** |
|
91 | - * Gets the ExpressionBuilder for the connection. |
|
92 | - * |
|
93 | - * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder |
|
94 | - * @deprecated please use $this->getQueryBuilder()->expr() instead |
|
95 | - */ |
|
96 | - public function getExpressionBuilder() { |
|
97 | - $backtrace = $this->getCallerBacktrace(); |
|
98 | - \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
99 | - return parent::getExpressionBuilder(); |
|
100 | - } |
|
101 | - |
|
102 | - /** |
|
103 | - * Get the file and line that called the method where `getCallerBacktrace()` was used |
|
104 | - * |
|
105 | - * @return string |
|
106 | - */ |
|
107 | - protected function getCallerBacktrace() { |
|
108 | - $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
|
109 | - |
|
110 | - // 0 is the method where we use `getCallerBacktrace` |
|
111 | - // 1 is the target method which uses the method we want to log |
|
112 | - if (isset($traces[1])) { |
|
113 | - return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
114 | - } |
|
115 | - |
|
116 | - return ''; |
|
117 | - } |
|
118 | - |
|
119 | - /** |
|
120 | - * @return string |
|
121 | - */ |
|
122 | - public function getPrefix() { |
|
123 | - return $this->tablePrefix; |
|
124 | - } |
|
125 | - |
|
126 | - /** |
|
127 | - * Initializes a new instance of the Connection class. |
|
128 | - * |
|
129 | - * @param array $params The connection parameters. |
|
130 | - * @param \Doctrine\DBAL\Driver $driver |
|
131 | - * @param \Doctrine\DBAL\Configuration $config |
|
132 | - * @param \Doctrine\Common\EventManager $eventManager |
|
133 | - * @throws \Exception |
|
134 | - */ |
|
135 | - public function __construct(array $params, Driver $driver, Configuration $config = null, |
|
136 | - EventManager $eventManager = null) |
|
137 | - { |
|
138 | - if (!isset($params['adapter'])) { |
|
139 | - throw new \Exception('adapter not set'); |
|
140 | - } |
|
141 | - if (!isset($params['tablePrefix'])) { |
|
142 | - throw new \Exception('tablePrefix not set'); |
|
143 | - } |
|
144 | - parent::__construct($params, $driver, $config, $eventManager); |
|
145 | - $this->adapter = new $params['adapter']($this); |
|
146 | - $this->tablePrefix = $params['tablePrefix']; |
|
147 | - |
|
148 | - parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED); |
|
149 | - } |
|
150 | - |
|
151 | - /** |
|
152 | - * Prepares an SQL statement. |
|
153 | - * |
|
154 | - * @param string $statement The SQL statement to prepare. |
|
155 | - * @param int $limit |
|
156 | - * @param int $offset |
|
157 | - * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
|
158 | - */ |
|
159 | - public function prepare( $statement, $limit=null, $offset=null ) { |
|
160 | - if ($limit === -1) { |
|
161 | - $limit = null; |
|
162 | - } |
|
163 | - if (!is_null($limit)) { |
|
164 | - $platform = $this->getDatabasePlatform(); |
|
165 | - $statement = $platform->modifyLimitQuery($statement, $limit, $offset); |
|
166 | - } |
|
167 | - $statement = $this->replaceTablePrefix($statement); |
|
168 | - $statement = $this->adapter->fixupStatement($statement); |
|
169 | - |
|
170 | - if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) { |
|
171 | - \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG); |
|
172 | - } |
|
173 | - return parent::prepare($statement); |
|
174 | - } |
|
175 | - |
|
176 | - /** |
|
177 | - * Executes an, optionally parametrized, SQL query. |
|
178 | - * |
|
179 | - * If the query is parametrized, a prepared statement is used. |
|
180 | - * If an SQLLogger is configured, the execution is logged. |
|
181 | - * |
|
182 | - * @param string $query The SQL query to execute. |
|
183 | - * @param array $params The parameters to bind to the query, if any. |
|
184 | - * @param array $types The types the previous parameters are in. |
|
185 | - * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
|
186 | - * |
|
187 | - * @return \Doctrine\DBAL\Driver\Statement The executed statement. |
|
188 | - * |
|
189 | - * @throws \Doctrine\DBAL\DBALException |
|
190 | - */ |
|
191 | - public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) |
|
192 | - { |
|
193 | - $query = $this->replaceTablePrefix($query); |
|
194 | - $query = $this->adapter->fixupStatement($query); |
|
195 | - return parent::executeQuery($query, $params, $types, $qcp); |
|
196 | - } |
|
197 | - |
|
198 | - /** |
|
199 | - * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters |
|
200 | - * and returns the number of affected rows. |
|
201 | - * |
|
202 | - * This method supports PDO binding types as well as DBAL mapping types. |
|
203 | - * |
|
204 | - * @param string $query The SQL query. |
|
205 | - * @param array $params The query parameters. |
|
206 | - * @param array $types The parameter types. |
|
207 | - * |
|
208 | - * @return integer The number of affected rows. |
|
209 | - * |
|
210 | - * @throws \Doctrine\DBAL\DBALException |
|
211 | - */ |
|
212 | - public function executeUpdate($query, array $params = array(), array $types = array()) |
|
213 | - { |
|
214 | - $query = $this->replaceTablePrefix($query); |
|
215 | - $query = $this->adapter->fixupStatement($query); |
|
216 | - return parent::executeUpdate($query, $params, $types); |
|
217 | - } |
|
218 | - |
|
219 | - /** |
|
220 | - * Returns the ID of the last inserted row, or the last value from a sequence object, |
|
221 | - * depending on the underlying driver. |
|
222 | - * |
|
223 | - * Note: This method may not return a meaningful or consistent result across different drivers, |
|
224 | - * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY |
|
225 | - * columns or sequences. |
|
226 | - * |
|
227 | - * @param string $seqName Name of the sequence object from which the ID should be returned. |
|
228 | - * @return string A string representation of the last inserted ID. |
|
229 | - */ |
|
230 | - public function lastInsertId($seqName = null) { |
|
231 | - if ($seqName) { |
|
232 | - $seqName = $this->replaceTablePrefix($seqName); |
|
233 | - } |
|
234 | - return $this->adapter->lastInsertId($seqName); |
|
235 | - } |
|
236 | - |
|
237 | - // internal use |
|
238 | - public function realLastInsertId($seqName = null) { |
|
239 | - return parent::lastInsertId($seqName); |
|
240 | - } |
|
241 | - |
|
242 | - /** |
|
243 | - * Insert a row if the matching row does not exists. |
|
244 | - * |
|
245 | - * @param string $table The table name (will replace *PREFIX* with the actual prefix) |
|
246 | - * @param array $input data that should be inserted into the table (column name => value) |
|
247 | - * @param array|null $compare List of values that should be checked for "if not exists" |
|
248 | - * If this is null or an empty array, all keys of $input will be compared |
|
249 | - * Please note: text fields (clob) must not be used in the compare array |
|
250 | - * @return int number of inserted rows |
|
251 | - * @throws \Doctrine\DBAL\DBALException |
|
252 | - */ |
|
253 | - public function insertIfNotExist($table, $input, array $compare = null) { |
|
254 | - return $this->adapter->insertIfNotExist($table, $input, $compare); |
|
255 | - } |
|
256 | - |
|
257 | - private function getType($value) { |
|
258 | - if (is_bool($value)) { |
|
259 | - return IQueryBuilder::PARAM_BOOL; |
|
260 | - } else if (is_int($value)) { |
|
261 | - return IQueryBuilder::PARAM_INT; |
|
262 | - } else { |
|
263 | - return IQueryBuilder::PARAM_STR; |
|
264 | - } |
|
265 | - } |
|
266 | - |
|
267 | - /** |
|
268 | - * Insert or update a row value |
|
269 | - * |
|
270 | - * @param string $table |
|
271 | - * @param array $keys (column name => value) |
|
272 | - * @param array $values (column name => value) |
|
273 | - * @param array $updatePreconditionValues ensure values match preconditions (column name => value) |
|
274 | - * @return int number of new rows |
|
275 | - * @throws \Doctrine\DBAL\DBALException |
|
276 | - * @throws PreConditionNotMetException |
|
277 | - */ |
|
278 | - public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { |
|
279 | - try { |
|
280 | - $insertQb = $this->getQueryBuilder(); |
|
281 | - $insertQb->insert($table) |
|
282 | - ->values( |
|
283 | - array_map(function($value) use ($insertQb) { |
|
284 | - return $insertQb->createNamedParameter($value, $this->getType($value)); |
|
285 | - }, array_merge($keys, $values)) |
|
286 | - ); |
|
287 | - return $insertQb->execute(); |
|
288 | - } catch (ConstraintViolationException $e) { |
|
289 | - // value already exists, try update |
|
290 | - $updateQb = $this->getQueryBuilder(); |
|
291 | - $updateQb->update($table); |
|
292 | - foreach ($values as $name => $value) { |
|
293 | - $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value))); |
|
294 | - } |
|
295 | - $where = $updateQb->expr()->andX(); |
|
296 | - $whereValues = array_merge($keys, $updatePreconditionValues); |
|
297 | - foreach ($whereValues as $name => $value) { |
|
298 | - $where->add($updateQb->expr()->eq( |
|
299 | - $name, |
|
300 | - $updateQb->createNamedParameter($value, $this->getType($value)), |
|
301 | - $this->getType($value) |
|
302 | - )); |
|
303 | - } |
|
304 | - $updateQb->where($where); |
|
305 | - $affected = $updateQb->execute(); |
|
306 | - |
|
307 | - if ($affected === 0 && !empty($updatePreconditionValues)) { |
|
308 | - throw new PreConditionNotMetException(); |
|
309 | - } |
|
310 | - |
|
311 | - return 0; |
|
312 | - } |
|
313 | - } |
|
314 | - |
|
315 | - /** |
|
316 | - * Create an exclusive read+write lock on a table |
|
317 | - * |
|
318 | - * @param string $tableName |
|
319 | - * @throws \BadMethodCallException When trying to acquire a second lock |
|
320 | - * @since 9.1.0 |
|
321 | - */ |
|
322 | - public function lockTable($tableName) { |
|
323 | - if ($this->lockedTable !== null) { |
|
324 | - throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
|
325 | - } |
|
326 | - |
|
327 | - $tableName = $this->tablePrefix . $tableName; |
|
328 | - $this->lockedTable = $tableName; |
|
329 | - $this->adapter->lockTable($tableName); |
|
330 | - } |
|
331 | - |
|
332 | - /** |
|
333 | - * Release a previous acquired lock again |
|
334 | - * |
|
335 | - * @since 9.1.0 |
|
336 | - */ |
|
337 | - public function unlockTable() { |
|
338 | - $this->adapter->unlockTable(); |
|
339 | - $this->lockedTable = null; |
|
340 | - } |
|
341 | - |
|
342 | - /** |
|
343 | - * returns the error code and message as a string for logging |
|
344 | - * works with DoctrineException |
|
345 | - * @return string |
|
346 | - */ |
|
347 | - public function getError() { |
|
348 | - $msg = $this->errorCode() . ': '; |
|
349 | - $errorInfo = $this->errorInfo(); |
|
350 | - if (is_array($errorInfo)) { |
|
351 | - $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
352 | - $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
353 | - $msg .= 'Driver Message = '.$errorInfo[2]; |
|
354 | - } |
|
355 | - return $msg; |
|
356 | - } |
|
357 | - |
|
358 | - /** |
|
359 | - * Drop a table from the database if it exists |
|
360 | - * |
|
361 | - * @param string $table table name without the prefix |
|
362 | - */ |
|
363 | - public function dropTable($table) { |
|
364 | - $table = $this->tablePrefix . trim($table); |
|
365 | - $schema = $this->getSchemaManager(); |
|
366 | - if($schema->tablesExist(array($table))) { |
|
367 | - $schema->dropTable($table); |
|
368 | - } |
|
369 | - } |
|
370 | - |
|
371 | - /** |
|
372 | - * Check if a table exists |
|
373 | - * |
|
374 | - * @param string $table table name without the prefix |
|
375 | - * @return bool |
|
376 | - */ |
|
377 | - public function tableExists($table){ |
|
378 | - $table = $this->tablePrefix . trim($table); |
|
379 | - $schema = $this->getSchemaManager(); |
|
380 | - return $schema->tablesExist(array($table)); |
|
381 | - } |
|
382 | - |
|
383 | - // internal use |
|
384 | - /** |
|
385 | - * @param string $statement |
|
386 | - * @return string |
|
387 | - */ |
|
388 | - protected function replaceTablePrefix($statement) { |
|
389 | - return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
390 | - } |
|
391 | - |
|
392 | - /** |
|
393 | - * Check if a transaction is active |
|
394 | - * |
|
395 | - * @return bool |
|
396 | - * @since 8.2.0 |
|
397 | - */ |
|
398 | - public function inTransaction() { |
|
399 | - return $this->getTransactionNestingLevel() > 0; |
|
400 | - } |
|
401 | - |
|
402 | - /** |
|
403 | - * Espace a parameter to be used in a LIKE query |
|
404 | - * |
|
405 | - * @param string $param |
|
406 | - * @return string |
|
407 | - */ |
|
408 | - public function escapeLikeParameter($param) { |
|
409 | - return addcslashes($param, '\\_%'); |
|
410 | - } |
|
411 | - |
|
412 | - /** |
|
413 | - * Check whether or not the current database support 4byte wide unicode |
|
414 | - * |
|
415 | - * @return bool |
|
416 | - * @since 11.0.0 |
|
417 | - */ |
|
418 | - public function supports4ByteText() { |
|
419 | - if (!$this->getDatabasePlatform() instanceof MySqlPlatform) { |
|
420 | - return true; |
|
421 | - } |
|
422 | - return $this->getParams()['charset'] === 'utf8mb4'; |
|
423 | - } |
|
44 | + /** |
|
45 | + * @var string $tablePrefix |
|
46 | + */ |
|
47 | + protected $tablePrefix; |
|
48 | + |
|
49 | + /** |
|
50 | + * @var \OC\DB\Adapter $adapter |
|
51 | + */ |
|
52 | + protected $adapter; |
|
53 | + |
|
54 | + protected $lockedTable = null; |
|
55 | + |
|
56 | + public function connect() { |
|
57 | + try { |
|
58 | + return parent::connect(); |
|
59 | + } catch (DBALException $e) { |
|
60 | + // throw a new exception to prevent leaking info from the stacktrace |
|
61 | + throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
62 | + } |
|
63 | + } |
|
64 | + |
|
65 | + /** |
|
66 | + * Returns a QueryBuilder for the connection. |
|
67 | + * |
|
68 | + * @return \OCP\DB\QueryBuilder\IQueryBuilder |
|
69 | + */ |
|
70 | + public function getQueryBuilder() { |
|
71 | + return new QueryBuilder( |
|
72 | + $this, |
|
73 | + \OC::$server->getSystemConfig(), |
|
74 | + \OC::$server->getLogger() |
|
75 | + ); |
|
76 | + } |
|
77 | + |
|
78 | + /** |
|
79 | + * Gets the QueryBuilder for the connection. |
|
80 | + * |
|
81 | + * @return \Doctrine\DBAL\Query\QueryBuilder |
|
82 | + * @deprecated please use $this->getQueryBuilder() instead |
|
83 | + */ |
|
84 | + public function createQueryBuilder() { |
|
85 | + $backtrace = $this->getCallerBacktrace(); |
|
86 | + \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
87 | + return parent::createQueryBuilder(); |
|
88 | + } |
|
89 | + |
|
90 | + /** |
|
91 | + * Gets the ExpressionBuilder for the connection. |
|
92 | + * |
|
93 | + * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder |
|
94 | + * @deprecated please use $this->getQueryBuilder()->expr() instead |
|
95 | + */ |
|
96 | + public function getExpressionBuilder() { |
|
97 | + $backtrace = $this->getCallerBacktrace(); |
|
98 | + \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
99 | + return parent::getExpressionBuilder(); |
|
100 | + } |
|
101 | + |
|
102 | + /** |
|
103 | + * Get the file and line that called the method where `getCallerBacktrace()` was used |
|
104 | + * |
|
105 | + * @return string |
|
106 | + */ |
|
107 | + protected function getCallerBacktrace() { |
|
108 | + $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
|
109 | + |
|
110 | + // 0 is the method where we use `getCallerBacktrace` |
|
111 | + // 1 is the target method which uses the method we want to log |
|
112 | + if (isset($traces[1])) { |
|
113 | + return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
114 | + } |
|
115 | + |
|
116 | + return ''; |
|
117 | + } |
|
118 | + |
|
119 | + /** |
|
120 | + * @return string |
|
121 | + */ |
|
122 | + public function getPrefix() { |
|
123 | + return $this->tablePrefix; |
|
124 | + } |
|
125 | + |
|
126 | + /** |
|
127 | + * Initializes a new instance of the Connection class. |
|
128 | + * |
|
129 | + * @param array $params The connection parameters. |
|
130 | + * @param \Doctrine\DBAL\Driver $driver |
|
131 | + * @param \Doctrine\DBAL\Configuration $config |
|
132 | + * @param \Doctrine\Common\EventManager $eventManager |
|
133 | + * @throws \Exception |
|
134 | + */ |
|
135 | + public function __construct(array $params, Driver $driver, Configuration $config = null, |
|
136 | + EventManager $eventManager = null) |
|
137 | + { |
|
138 | + if (!isset($params['adapter'])) { |
|
139 | + throw new \Exception('adapter not set'); |
|
140 | + } |
|
141 | + if (!isset($params['tablePrefix'])) { |
|
142 | + throw new \Exception('tablePrefix not set'); |
|
143 | + } |
|
144 | + parent::__construct($params, $driver, $config, $eventManager); |
|
145 | + $this->adapter = new $params['adapter']($this); |
|
146 | + $this->tablePrefix = $params['tablePrefix']; |
|
147 | + |
|
148 | + parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED); |
|
149 | + } |
|
150 | + |
|
151 | + /** |
|
152 | + * Prepares an SQL statement. |
|
153 | + * |
|
154 | + * @param string $statement The SQL statement to prepare. |
|
155 | + * @param int $limit |
|
156 | + * @param int $offset |
|
157 | + * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
|
158 | + */ |
|
159 | + public function prepare( $statement, $limit=null, $offset=null ) { |
|
160 | + if ($limit === -1) { |
|
161 | + $limit = null; |
|
162 | + } |
|
163 | + if (!is_null($limit)) { |
|
164 | + $platform = $this->getDatabasePlatform(); |
|
165 | + $statement = $platform->modifyLimitQuery($statement, $limit, $offset); |
|
166 | + } |
|
167 | + $statement = $this->replaceTablePrefix($statement); |
|
168 | + $statement = $this->adapter->fixupStatement($statement); |
|
169 | + |
|
170 | + if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) { |
|
171 | + \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG); |
|
172 | + } |
|
173 | + return parent::prepare($statement); |
|
174 | + } |
|
175 | + |
|
176 | + /** |
|
177 | + * Executes an, optionally parametrized, SQL query. |
|
178 | + * |
|
179 | + * If the query is parametrized, a prepared statement is used. |
|
180 | + * If an SQLLogger is configured, the execution is logged. |
|
181 | + * |
|
182 | + * @param string $query The SQL query to execute. |
|
183 | + * @param array $params The parameters to bind to the query, if any. |
|
184 | + * @param array $types The types the previous parameters are in. |
|
185 | + * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional. |
|
186 | + * |
|
187 | + * @return \Doctrine\DBAL\Driver\Statement The executed statement. |
|
188 | + * |
|
189 | + * @throws \Doctrine\DBAL\DBALException |
|
190 | + */ |
|
191 | + public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) |
|
192 | + { |
|
193 | + $query = $this->replaceTablePrefix($query); |
|
194 | + $query = $this->adapter->fixupStatement($query); |
|
195 | + return parent::executeQuery($query, $params, $types, $qcp); |
|
196 | + } |
|
197 | + |
|
198 | + /** |
|
199 | + * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters |
|
200 | + * and returns the number of affected rows. |
|
201 | + * |
|
202 | + * This method supports PDO binding types as well as DBAL mapping types. |
|
203 | + * |
|
204 | + * @param string $query The SQL query. |
|
205 | + * @param array $params The query parameters. |
|
206 | + * @param array $types The parameter types. |
|
207 | + * |
|
208 | + * @return integer The number of affected rows. |
|
209 | + * |
|
210 | + * @throws \Doctrine\DBAL\DBALException |
|
211 | + */ |
|
212 | + public function executeUpdate($query, array $params = array(), array $types = array()) |
|
213 | + { |
|
214 | + $query = $this->replaceTablePrefix($query); |
|
215 | + $query = $this->adapter->fixupStatement($query); |
|
216 | + return parent::executeUpdate($query, $params, $types); |
|
217 | + } |
|
218 | + |
|
219 | + /** |
|
220 | + * Returns the ID of the last inserted row, or the last value from a sequence object, |
|
221 | + * depending on the underlying driver. |
|
222 | + * |
|
223 | + * Note: This method may not return a meaningful or consistent result across different drivers, |
|
224 | + * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY |
|
225 | + * columns or sequences. |
|
226 | + * |
|
227 | + * @param string $seqName Name of the sequence object from which the ID should be returned. |
|
228 | + * @return string A string representation of the last inserted ID. |
|
229 | + */ |
|
230 | + public function lastInsertId($seqName = null) { |
|
231 | + if ($seqName) { |
|
232 | + $seqName = $this->replaceTablePrefix($seqName); |
|
233 | + } |
|
234 | + return $this->adapter->lastInsertId($seqName); |
|
235 | + } |
|
236 | + |
|
237 | + // internal use |
|
238 | + public function realLastInsertId($seqName = null) { |
|
239 | + return parent::lastInsertId($seqName); |
|
240 | + } |
|
241 | + |
|
242 | + /** |
|
243 | + * Insert a row if the matching row does not exists. |
|
244 | + * |
|
245 | + * @param string $table The table name (will replace *PREFIX* with the actual prefix) |
|
246 | + * @param array $input data that should be inserted into the table (column name => value) |
|
247 | + * @param array|null $compare List of values that should be checked for "if not exists" |
|
248 | + * If this is null or an empty array, all keys of $input will be compared |
|
249 | + * Please note: text fields (clob) must not be used in the compare array |
|
250 | + * @return int number of inserted rows |
|
251 | + * @throws \Doctrine\DBAL\DBALException |
|
252 | + */ |
|
253 | + public function insertIfNotExist($table, $input, array $compare = null) { |
|
254 | + return $this->adapter->insertIfNotExist($table, $input, $compare); |
|
255 | + } |
|
256 | + |
|
257 | + private function getType($value) { |
|
258 | + if (is_bool($value)) { |
|
259 | + return IQueryBuilder::PARAM_BOOL; |
|
260 | + } else if (is_int($value)) { |
|
261 | + return IQueryBuilder::PARAM_INT; |
|
262 | + } else { |
|
263 | + return IQueryBuilder::PARAM_STR; |
|
264 | + } |
|
265 | + } |
|
266 | + |
|
267 | + /** |
|
268 | + * Insert or update a row value |
|
269 | + * |
|
270 | + * @param string $table |
|
271 | + * @param array $keys (column name => value) |
|
272 | + * @param array $values (column name => value) |
|
273 | + * @param array $updatePreconditionValues ensure values match preconditions (column name => value) |
|
274 | + * @return int number of new rows |
|
275 | + * @throws \Doctrine\DBAL\DBALException |
|
276 | + * @throws PreConditionNotMetException |
|
277 | + */ |
|
278 | + public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { |
|
279 | + try { |
|
280 | + $insertQb = $this->getQueryBuilder(); |
|
281 | + $insertQb->insert($table) |
|
282 | + ->values( |
|
283 | + array_map(function($value) use ($insertQb) { |
|
284 | + return $insertQb->createNamedParameter($value, $this->getType($value)); |
|
285 | + }, array_merge($keys, $values)) |
|
286 | + ); |
|
287 | + return $insertQb->execute(); |
|
288 | + } catch (ConstraintViolationException $e) { |
|
289 | + // value already exists, try update |
|
290 | + $updateQb = $this->getQueryBuilder(); |
|
291 | + $updateQb->update($table); |
|
292 | + foreach ($values as $name => $value) { |
|
293 | + $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value))); |
|
294 | + } |
|
295 | + $where = $updateQb->expr()->andX(); |
|
296 | + $whereValues = array_merge($keys, $updatePreconditionValues); |
|
297 | + foreach ($whereValues as $name => $value) { |
|
298 | + $where->add($updateQb->expr()->eq( |
|
299 | + $name, |
|
300 | + $updateQb->createNamedParameter($value, $this->getType($value)), |
|
301 | + $this->getType($value) |
|
302 | + )); |
|
303 | + } |
|
304 | + $updateQb->where($where); |
|
305 | + $affected = $updateQb->execute(); |
|
306 | + |
|
307 | + if ($affected === 0 && !empty($updatePreconditionValues)) { |
|
308 | + throw new PreConditionNotMetException(); |
|
309 | + } |
|
310 | + |
|
311 | + return 0; |
|
312 | + } |
|
313 | + } |
|
314 | + |
|
315 | + /** |
|
316 | + * Create an exclusive read+write lock on a table |
|
317 | + * |
|
318 | + * @param string $tableName |
|
319 | + * @throws \BadMethodCallException When trying to acquire a second lock |
|
320 | + * @since 9.1.0 |
|
321 | + */ |
|
322 | + public function lockTable($tableName) { |
|
323 | + if ($this->lockedTable !== null) { |
|
324 | + throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
|
325 | + } |
|
326 | + |
|
327 | + $tableName = $this->tablePrefix . $tableName; |
|
328 | + $this->lockedTable = $tableName; |
|
329 | + $this->adapter->lockTable($tableName); |
|
330 | + } |
|
331 | + |
|
332 | + /** |
|
333 | + * Release a previous acquired lock again |
|
334 | + * |
|
335 | + * @since 9.1.0 |
|
336 | + */ |
|
337 | + public function unlockTable() { |
|
338 | + $this->adapter->unlockTable(); |
|
339 | + $this->lockedTable = null; |
|
340 | + } |
|
341 | + |
|
342 | + /** |
|
343 | + * returns the error code and message as a string for logging |
|
344 | + * works with DoctrineException |
|
345 | + * @return string |
|
346 | + */ |
|
347 | + public function getError() { |
|
348 | + $msg = $this->errorCode() . ': '; |
|
349 | + $errorInfo = $this->errorInfo(); |
|
350 | + if (is_array($errorInfo)) { |
|
351 | + $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
352 | + $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
353 | + $msg .= 'Driver Message = '.$errorInfo[2]; |
|
354 | + } |
|
355 | + return $msg; |
|
356 | + } |
|
357 | + |
|
358 | + /** |
|
359 | + * Drop a table from the database if it exists |
|
360 | + * |
|
361 | + * @param string $table table name without the prefix |
|
362 | + */ |
|
363 | + public function dropTable($table) { |
|
364 | + $table = $this->tablePrefix . trim($table); |
|
365 | + $schema = $this->getSchemaManager(); |
|
366 | + if($schema->tablesExist(array($table))) { |
|
367 | + $schema->dropTable($table); |
|
368 | + } |
|
369 | + } |
|
370 | + |
|
371 | + /** |
|
372 | + * Check if a table exists |
|
373 | + * |
|
374 | + * @param string $table table name without the prefix |
|
375 | + * @return bool |
|
376 | + */ |
|
377 | + public function tableExists($table){ |
|
378 | + $table = $this->tablePrefix . trim($table); |
|
379 | + $schema = $this->getSchemaManager(); |
|
380 | + return $schema->tablesExist(array($table)); |
|
381 | + } |
|
382 | + |
|
383 | + // internal use |
|
384 | + /** |
|
385 | + * @param string $statement |
|
386 | + * @return string |
|
387 | + */ |
|
388 | + protected function replaceTablePrefix($statement) { |
|
389 | + return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
390 | + } |
|
391 | + |
|
392 | + /** |
|
393 | + * Check if a transaction is active |
|
394 | + * |
|
395 | + * @return bool |
|
396 | + * @since 8.2.0 |
|
397 | + */ |
|
398 | + public function inTransaction() { |
|
399 | + return $this->getTransactionNestingLevel() > 0; |
|
400 | + } |
|
401 | + |
|
402 | + /** |
|
403 | + * Espace a parameter to be used in a LIKE query |
|
404 | + * |
|
405 | + * @param string $param |
|
406 | + * @return string |
|
407 | + */ |
|
408 | + public function escapeLikeParameter($param) { |
|
409 | + return addcslashes($param, '\\_%'); |
|
410 | + } |
|
411 | + |
|
412 | + /** |
|
413 | + * Check whether or not the current database support 4byte wide unicode |
|
414 | + * |
|
415 | + * @return bool |
|
416 | + * @since 11.0.0 |
|
417 | + */ |
|
418 | + public function supports4ByteText() { |
|
419 | + if (!$this->getDatabasePlatform() instanceof MySqlPlatform) { |
|
420 | + return true; |
|
421 | + } |
|
422 | + return $this->getParams()['charset'] === 'utf8mb4'; |
|
423 | + } |
|
424 | 424 | } |
@@ -30,7 +30,6 @@ |
||
30 | 30 | use OC\Files\Filesystem; |
31 | 31 | use OC\Files\View; |
32 | 32 | use OCP\Encryption\IEncryptionModule; |
33 | -use OCP\Files\Storage; |
|
34 | 33 | use OCP\IConfig; |
35 | 34 | |
36 | 35 | class Util { |
@@ -97,7 +97,7 @@ discard block |
||
97 | 97 | $this->config = $config; |
98 | 98 | |
99 | 99 | $this->excludedPaths[] = 'files_encryption'; |
100 | - $this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null); |
|
100 | + $this->excludedPaths[] = 'appdata_'.$config->getSystemValue('instanceid', null); |
|
101 | 101 | } |
102 | 102 | |
103 | 103 | /** |
@@ -136,12 +136,12 @@ discard block |
||
136 | 136 | * @throws EncryptionHeaderKeyExistsException if header key is already in use |
137 | 137 | */ |
138 | 138 | public function createHeader(array $headerData, IEncryptionModule $encryptionModule) { |
139 | - $header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':'; |
|
139 | + $header = self::HEADER_START.':'.self::HEADER_ENCRYPTION_MODULE_KEY.':'.$encryptionModule->getId().':'; |
|
140 | 140 | foreach ($headerData as $key => $value) { |
141 | 141 | if (in_array($key, $this->ocHeaderKeys)) { |
142 | 142 | throw new EncryptionHeaderKeyExistsException($key); |
143 | 143 | } |
144 | - $header .= $key . ':' . $value . ':'; |
|
144 | + $header .= $key.':'.$value.':'; |
|
145 | 145 | } |
146 | 146 | $header .= self::HEADER_END; |
147 | 147 | |
@@ -172,7 +172,7 @@ discard block |
||
172 | 172 | if ($c->getType() === 'dir') { |
173 | 173 | $dirList[] = $c->getPath(); |
174 | 174 | } else { |
175 | - $result[] = $c->getPath(); |
|
175 | + $result[] = $c->getPath(); |
|
176 | 176 | } |
177 | 177 | } |
178 | 178 | |
@@ -249,15 +249,15 @@ discard block |
||
249 | 249 | public function stripPartialFileExtension($path) { |
250 | 250 | $extension = pathinfo($path, PATHINFO_EXTENSION); |
251 | 251 | |
252 | - if ( $extension === 'part') { |
|
252 | + if ($extension === 'part') { |
|
253 | 253 | |
254 | 254 | $newLength = strlen($path) - 5; // 5 = strlen(".part") |
255 | 255 | $fPath = substr($path, 0, $newLength); |
256 | 256 | |
257 | 257 | // if path also contains a transaction id, we remove it too |
258 | 258 | $extension = pathinfo($fPath, PATHINFO_EXTENSION); |
259 | - if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId") |
|
260 | - $newLength = strlen($fPath) - strlen($extension) -1; |
|
259 | + if (substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId") |
|
260 | + $newLength = strlen($fPath) - strlen($extension) - 1; |
|
261 | 261 | $fPath = substr($fPath, 0, $newLength); |
262 | 262 | } |
263 | 263 | return $fPath; |
@@ -291,7 +291,7 @@ discard block |
||
291 | 291 | if (\OCP\App::isEnabled("files_external")) { |
292 | 292 | $mounts = \OC_Mount_Config::getSystemMountPoints(); |
293 | 293 | foreach ($mounts as $mount) { |
294 | - if (strpos($path, '/files/' . $mount['mountpoint']) === 0) { |
|
294 | + if (strpos($path, '/files/'.$mount['mountpoint']) === 0) { |
|
295 | 295 | if ($this->isMountPointApplicableToUser($mount, $uid)) { |
296 | 296 | return true; |
297 | 297 | } |
@@ -36,370 +36,370 @@ |
||
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 | } |
@@ -386,6 +386,14 @@ discard block |
||
386 | 386 | return $size; |
387 | 387 | } |
388 | 388 | |
389 | + /** |
|
390 | + * @param string $path |
|
391 | + * @param boolean $recursive |
|
392 | + * @param integer $reuse |
|
393 | + * @param integer|null $folderId |
|
394 | + * @param boolean $lock |
|
395 | + * @param integer $size |
|
396 | + */ |
|
389 | 397 | private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) { |
390 | 398 | // we put this in it's own function so it cleans up the memory before we start recursing |
391 | 399 | $existingChildren = $this->getExistingChildren($folderId); |
@@ -485,6 +493,9 @@ discard block |
||
485 | 493 | } |
486 | 494 | } |
487 | 495 | |
496 | + /** |
|
497 | + * @param string|boolean $path |
|
498 | + */ |
|
488 | 499 | private function runBackgroundScanJob(callable $callback, $path) { |
489 | 500 | try { |
490 | 501 | $callback(); |
@@ -55,476 +55,476 @@ |
||
55 | 55 | * @package OC\Files\Cache |
56 | 56 | */ |
57 | 57 | class Scanner extends BasicEmitter implements IScanner { |
58 | - /** |
|
59 | - * @var \OC\Files\Storage\Storage $storage |
|
60 | - */ |
|
61 | - protected $storage; |
|
62 | - |
|
63 | - /** |
|
64 | - * @var string $storageId |
|
65 | - */ |
|
66 | - protected $storageId; |
|
67 | - |
|
68 | - /** |
|
69 | - * @var \OC\Files\Cache\Cache $cache |
|
70 | - */ |
|
71 | - protected $cache; |
|
72 | - |
|
73 | - /** |
|
74 | - * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache |
|
75 | - */ |
|
76 | - protected $cacheActive; |
|
77 | - |
|
78 | - /** |
|
79 | - * @var bool $useTransactions whether to use transactions |
|
80 | - */ |
|
81 | - protected $useTransactions = true; |
|
82 | - |
|
83 | - /** |
|
84 | - * @var \OCP\Lock\ILockingProvider |
|
85 | - */ |
|
86 | - protected $lockingProvider; |
|
87 | - |
|
88 | - public function __construct(\OC\Files\Storage\Storage $storage) { |
|
89 | - $this->storage = $storage; |
|
90 | - $this->storageId = $this->storage->getId(); |
|
91 | - $this->cache = $storage->getCache(); |
|
92 | - $this->cacheActive = !Config::getSystemValue('filesystem_cache_readonly', false); |
|
93 | - $this->lockingProvider = \OC::$server->getLockingProvider(); |
|
94 | - } |
|
95 | - |
|
96 | - /** |
|
97 | - * Whether to wrap the scanning of a folder in a database transaction |
|
98 | - * On default transactions are used |
|
99 | - * |
|
100 | - * @param bool $useTransactions |
|
101 | - */ |
|
102 | - public function setUseTransactions($useTransactions) { |
|
103 | - $this->useTransactions = $useTransactions; |
|
104 | - } |
|
105 | - |
|
106 | - /** |
|
107 | - * get all the metadata of a file or folder |
|
108 | - * * |
|
109 | - * |
|
110 | - * @param string $path |
|
111 | - * @return array an array of metadata of the file |
|
112 | - */ |
|
113 | - protected function getData($path) { |
|
114 | - $data = $this->storage->getMetaData($path); |
|
115 | - if (is_null($data)) { |
|
116 | - \OCP\Util::writeLog('OC\Files\Cache\Scanner', "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG); |
|
117 | - } |
|
118 | - return $data; |
|
119 | - } |
|
120 | - |
|
121 | - /** |
|
122 | - * scan a single file and store it in the cache |
|
123 | - * |
|
124 | - * @param string $file |
|
125 | - * @param int $reuseExisting |
|
126 | - * @param int $parentId |
|
127 | - * @param array | null $cacheData existing data in the cache for the file to be scanned |
|
128 | - * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
129 | - * @return array an array of metadata of the scanned file |
|
130 | - * @throws \OC\ServerNotAvailableException |
|
131 | - * @throws \OCP\Lock\LockedException |
|
132 | - */ |
|
133 | - public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) { |
|
134 | - if ($file !== '') { |
|
135 | - try { |
|
136 | - $this->storage->verifyPath(dirname($file), basename($file)); |
|
137 | - } catch (\Exception $e) { |
|
138 | - return null; |
|
139 | - } |
|
140 | - } |
|
141 | - |
|
142 | - // only proceed if $file is not a partial file nor a blacklisted file |
|
143 | - if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) { |
|
144 | - |
|
145 | - //acquire a lock |
|
146 | - if ($lock) { |
|
147 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
148 | - $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
149 | - } |
|
150 | - } |
|
151 | - |
|
152 | - try { |
|
153 | - $data = $this->getData($file); |
|
154 | - } catch (ForbiddenException $e) { |
|
155 | - return null; |
|
156 | - } |
|
157 | - |
|
158 | - if ($data) { |
|
159 | - |
|
160 | - // pre-emit only if it was a file. By that we avoid counting/treating folders as files |
|
161 | - if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
162 | - $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId)); |
|
163 | - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
164 | - } |
|
165 | - |
|
166 | - $parent = dirname($file); |
|
167 | - if ($parent === '.' or $parent === '/') { |
|
168 | - $parent = ''; |
|
169 | - } |
|
170 | - if ($parentId === -1) { |
|
171 | - $parentId = $this->cache->getParentId($file); |
|
172 | - } |
|
173 | - |
|
174 | - // scan the parent if it's not in the cache (id -1) and the current file is not the root folder |
|
175 | - if ($file and $parentId === -1) { |
|
176 | - $parentData = $this->scanFile($parent); |
|
177 | - if (!$parentData) { |
|
178 | - return null; |
|
179 | - } |
|
180 | - $parentId = $parentData['fileid']; |
|
181 | - } |
|
182 | - if ($parent) { |
|
183 | - $data['parent'] = $parentId; |
|
184 | - } |
|
185 | - if (is_null($cacheData)) { |
|
186 | - /** @var CacheEntry $cacheData */ |
|
187 | - $cacheData = $this->cache->get($file); |
|
188 | - } |
|
189 | - if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) { |
|
190 | - // prevent empty etag |
|
191 | - if (empty($cacheData['etag'])) { |
|
192 | - $etag = $data['etag']; |
|
193 | - } else { |
|
194 | - $etag = $cacheData['etag']; |
|
195 | - } |
|
196 | - $fileId = $cacheData['fileid']; |
|
197 | - $data['fileid'] = $fileId; |
|
198 | - // only reuse data if the file hasn't explicitly changed |
|
199 | - if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) { |
|
200 | - $data['mtime'] = $cacheData['mtime']; |
|
201 | - if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) { |
|
202 | - $data['size'] = $cacheData['size']; |
|
203 | - } |
|
204 | - if ($reuseExisting & self::REUSE_ETAG) { |
|
205 | - $data['etag'] = $etag; |
|
206 | - } |
|
207 | - } |
|
208 | - // Only update metadata that has changed |
|
209 | - $newData = array_diff_assoc($data, $cacheData->getData()); |
|
210 | - } else { |
|
211 | - $newData = $data; |
|
212 | - $fileId = -1; |
|
213 | - } |
|
214 | - if (!empty($newData)) { |
|
215 | - // Reset the checksum if the data has changed |
|
216 | - $newData['checksum'] = ''; |
|
217 | - $data['fileid'] = $this->addToCache($file, $newData, $fileId); |
|
218 | - } |
|
219 | - if (isset($cacheData['size'])) { |
|
220 | - $data['oldSize'] = $cacheData['size']; |
|
221 | - } else { |
|
222 | - $data['oldSize'] = 0; |
|
223 | - } |
|
224 | - |
|
225 | - if (isset($cacheData['encrypted'])) { |
|
226 | - $data['encrypted'] = $cacheData['encrypted']; |
|
227 | - } |
|
228 | - |
|
229 | - // post-emit only if it was a file. By that we avoid counting/treating folders as files |
|
230 | - if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
231 | - $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); |
|
232 | - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
233 | - } |
|
234 | - |
|
235 | - } else { |
|
236 | - $this->removeFromCache($file); |
|
237 | - } |
|
238 | - |
|
239 | - //release the acquired lock |
|
240 | - if ($lock) { |
|
241 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
242 | - $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
243 | - } |
|
244 | - } |
|
245 | - |
|
246 | - if ($data && !isset($data['encrypted'])) { |
|
247 | - $data['encrypted'] = false; |
|
248 | - } |
|
249 | - return $data; |
|
250 | - } |
|
251 | - |
|
252 | - return null; |
|
253 | - } |
|
254 | - |
|
255 | - protected function removeFromCache($path) { |
|
256 | - \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path)); |
|
257 | - $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path)); |
|
258 | - if ($this->cacheActive) { |
|
259 | - $this->cache->remove($path); |
|
260 | - } |
|
261 | - } |
|
262 | - |
|
263 | - /** |
|
264 | - * @param string $path |
|
265 | - * @param array $data |
|
266 | - * @param int $fileId |
|
267 | - * @return int the id of the added file |
|
268 | - */ |
|
269 | - protected function addToCache($path, $data, $fileId = -1) { |
|
270 | - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
271 | - $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data)); |
|
272 | - if ($this->cacheActive) { |
|
273 | - if ($fileId !== -1) { |
|
274 | - $this->cache->update($fileId, $data); |
|
275 | - return $fileId; |
|
276 | - } else { |
|
277 | - return $this->cache->put($path, $data); |
|
278 | - } |
|
279 | - } else { |
|
280 | - return -1; |
|
281 | - } |
|
282 | - } |
|
283 | - |
|
284 | - /** |
|
285 | - * @param string $path |
|
286 | - * @param array $data |
|
287 | - * @param int $fileId |
|
288 | - */ |
|
289 | - protected function updateCache($path, $data, $fileId = -1) { |
|
290 | - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
291 | - $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data)); |
|
292 | - if ($this->cacheActive) { |
|
293 | - if ($fileId !== -1) { |
|
294 | - $this->cache->update($fileId, $data); |
|
295 | - } else { |
|
296 | - $this->cache->put($path, $data); |
|
297 | - } |
|
298 | - } |
|
299 | - } |
|
300 | - |
|
301 | - /** |
|
302 | - * scan a folder and all it's children |
|
303 | - * |
|
304 | - * @param string $path |
|
305 | - * @param bool $recursive |
|
306 | - * @param int $reuse |
|
307 | - * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
308 | - * @return array an array of the meta data of the scanned file or folder |
|
309 | - */ |
|
310 | - public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) { |
|
311 | - if ($reuse === -1) { |
|
312 | - $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
313 | - } |
|
314 | - if ($lock) { |
|
315 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
316 | - $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
317 | - $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
318 | - } |
|
319 | - } |
|
320 | - $data = $this->scanFile($path, $reuse, -1, null, $lock); |
|
321 | - if ($data and $data['mimetype'] === 'httpd/unix-directory') { |
|
322 | - $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock); |
|
323 | - $data['size'] = $size; |
|
324 | - } |
|
325 | - if ($lock) { |
|
326 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
327 | - $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
328 | - $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
329 | - } |
|
330 | - } |
|
331 | - return $data; |
|
332 | - } |
|
333 | - |
|
334 | - /** |
|
335 | - * Get the children currently in the cache |
|
336 | - * |
|
337 | - * @param int $folderId |
|
338 | - * @return array[] |
|
339 | - */ |
|
340 | - protected function getExistingChildren($folderId) { |
|
341 | - $existingChildren = array(); |
|
342 | - $children = $this->cache->getFolderContentsById($folderId); |
|
343 | - foreach ($children as $child) { |
|
344 | - $existingChildren[$child['name']] = $child; |
|
345 | - } |
|
346 | - return $existingChildren; |
|
347 | - } |
|
348 | - |
|
349 | - /** |
|
350 | - * Get the children from the storage |
|
351 | - * |
|
352 | - * @param string $folder |
|
353 | - * @return string[] |
|
354 | - */ |
|
355 | - protected function getNewChildren($folder) { |
|
356 | - $children = array(); |
|
357 | - if ($dh = $this->storage->opendir($folder)) { |
|
358 | - if (is_resource($dh)) { |
|
359 | - while (($file = readdir($dh)) !== false) { |
|
360 | - if (!Filesystem::isIgnoredDir($file)) { |
|
361 | - $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/'); |
|
362 | - } |
|
363 | - } |
|
364 | - } |
|
365 | - } |
|
366 | - return $children; |
|
367 | - } |
|
368 | - |
|
369 | - /** |
|
370 | - * scan all the files and folders in a folder |
|
371 | - * |
|
372 | - * @param string $path |
|
373 | - * @param bool $recursive |
|
374 | - * @param int $reuse |
|
375 | - * @param int $folderId id for the folder to be scanned |
|
376 | - * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
377 | - * @return int the size of the scanned folder or -1 if the size is unknown at this stage |
|
378 | - */ |
|
379 | - protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) { |
|
380 | - if ($reuse === -1) { |
|
381 | - $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
382 | - } |
|
383 | - $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId)); |
|
384 | - $size = 0; |
|
385 | - if (!is_null($folderId)) { |
|
386 | - $folderId = $this->cache->getId($path); |
|
387 | - } |
|
388 | - $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size); |
|
389 | - |
|
390 | - foreach ($childQueue as $child => $childId) { |
|
391 | - $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock); |
|
392 | - if ($childSize === -1) { |
|
393 | - $size = -1; |
|
394 | - } else if ($size !== -1) { |
|
395 | - $size += $childSize; |
|
396 | - } |
|
397 | - } |
|
398 | - if ($this->cacheActive) { |
|
399 | - $this->cache->update($folderId, array('size' => $size)); |
|
400 | - } |
|
401 | - $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId)); |
|
402 | - return $size; |
|
403 | - } |
|
404 | - |
|
405 | - private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) { |
|
406 | - // we put this in it's own function so it cleans up the memory before we start recursing |
|
407 | - $existingChildren = $this->getExistingChildren($folderId); |
|
408 | - $newChildren = $this->getNewChildren($path); |
|
409 | - |
|
410 | - if ($this->useTransactions) { |
|
411 | - \OC::$server->getDatabaseConnection()->beginTransaction(); |
|
412 | - } |
|
413 | - |
|
414 | - $exceptionOccurred = false; |
|
415 | - $childQueue = []; |
|
416 | - foreach ($newChildren as $file) { |
|
417 | - $child = ($path) ? $path . '/' . $file : $file; |
|
418 | - try { |
|
419 | - $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; |
|
420 | - $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); |
|
421 | - if ($data) { |
|
422 | - if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) { |
|
423 | - $childQueue[$child] = $data['fileid']; |
|
424 | - } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) { |
|
425 | - // only recurse into folders which aren't fully scanned |
|
426 | - $childQueue[$child] = $data['fileid']; |
|
427 | - } else if ($data['size'] === -1) { |
|
428 | - $size = -1; |
|
429 | - } else if ($size !== -1) { |
|
430 | - $size += $data['size']; |
|
431 | - } |
|
432 | - } |
|
433 | - } catch (\Doctrine\DBAL\DBALException $ex) { |
|
434 | - // might happen if inserting duplicate while a scanning |
|
435 | - // process is running in parallel |
|
436 | - // log and ignore |
|
437 | - \OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG); |
|
438 | - $exceptionOccurred = true; |
|
439 | - } catch (\OCP\Lock\LockedException $e) { |
|
440 | - if ($this->useTransactions) { |
|
441 | - \OC::$server->getDatabaseConnection()->rollback(); |
|
442 | - } |
|
443 | - throw $e; |
|
444 | - } |
|
445 | - } |
|
446 | - $removedChildren = \array_diff(array_keys($existingChildren), $newChildren); |
|
447 | - foreach ($removedChildren as $childName) { |
|
448 | - $child = ($path) ? $path . '/' . $childName : $childName; |
|
449 | - $this->removeFromCache($child); |
|
450 | - } |
|
451 | - if ($this->useTransactions) { |
|
452 | - \OC::$server->getDatabaseConnection()->commit(); |
|
453 | - } |
|
454 | - if ($exceptionOccurred) { |
|
455 | - // It might happen that the parallel scan process has already |
|
456 | - // inserted mimetypes but those weren't available yet inside the transaction |
|
457 | - // To make sure to have the updated mime types in such cases, |
|
458 | - // we reload them here |
|
459 | - \OC::$server->getMimeTypeLoader()->reset(); |
|
460 | - } |
|
461 | - return $childQueue; |
|
462 | - } |
|
463 | - |
|
464 | - /** |
|
465 | - * check if the file should be ignored when scanning |
|
466 | - * NOTE: files with a '.part' extension are ignored as well! |
|
467 | - * prevents unfinished put requests to be scanned |
|
468 | - * |
|
469 | - * @param string $file |
|
470 | - * @return boolean |
|
471 | - */ |
|
472 | - public static function isPartialFile($file) { |
|
473 | - if (pathinfo($file, PATHINFO_EXTENSION) === 'part') { |
|
474 | - return true; |
|
475 | - } |
|
476 | - if (strpos($file, '.part/') !== false) { |
|
477 | - return true; |
|
478 | - } |
|
479 | - |
|
480 | - return false; |
|
481 | - } |
|
482 | - |
|
483 | - /** |
|
484 | - * walk over any folders that are not fully scanned yet and scan them |
|
485 | - */ |
|
486 | - public function backgroundScan() { |
|
487 | - if (!$this->cache->inCache('')) { |
|
488 | - $this->runBackgroundScanJob(function () { |
|
489 | - $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); |
|
490 | - }, ''); |
|
491 | - } else { |
|
492 | - $lastPath = null; |
|
493 | - while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { |
|
494 | - $this->runBackgroundScanJob(function () use ($path) { |
|
495 | - $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); |
|
496 | - }, $path); |
|
497 | - // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() |
|
498 | - // to make this possible |
|
499 | - $lastPath = $path; |
|
500 | - } |
|
501 | - } |
|
502 | - } |
|
503 | - |
|
504 | - private function runBackgroundScanJob(callable $callback, $path) { |
|
505 | - try { |
|
506 | - $callback(); |
|
507 | - \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); |
|
508 | - if ($this->cacheActive && $this->cache instanceof Cache) { |
|
509 | - $this->cache->correctFolderSize($path); |
|
510 | - } |
|
511 | - } catch (\OCP\Files\StorageInvalidException $e) { |
|
512 | - // skip unavailable storages |
|
513 | - } catch (\OCP\Files\StorageNotAvailableException $e) { |
|
514 | - // skip unavailable storages |
|
515 | - } catch (\OCP\Files\ForbiddenException $e) { |
|
516 | - // skip forbidden storages |
|
517 | - } catch (\OCP\Lock\LockedException $e) { |
|
518 | - // skip unavailable storages |
|
519 | - } |
|
520 | - } |
|
521 | - |
|
522 | - /** |
|
523 | - * Set whether the cache is affected by scan operations |
|
524 | - * |
|
525 | - * @param boolean $active The active state of the cache |
|
526 | - */ |
|
527 | - public function setCacheActive($active) { |
|
528 | - $this->cacheActive = $active; |
|
529 | - } |
|
58 | + /** |
|
59 | + * @var \OC\Files\Storage\Storage $storage |
|
60 | + */ |
|
61 | + protected $storage; |
|
62 | + |
|
63 | + /** |
|
64 | + * @var string $storageId |
|
65 | + */ |
|
66 | + protected $storageId; |
|
67 | + |
|
68 | + /** |
|
69 | + * @var \OC\Files\Cache\Cache $cache |
|
70 | + */ |
|
71 | + protected $cache; |
|
72 | + |
|
73 | + /** |
|
74 | + * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache |
|
75 | + */ |
|
76 | + protected $cacheActive; |
|
77 | + |
|
78 | + /** |
|
79 | + * @var bool $useTransactions whether to use transactions |
|
80 | + */ |
|
81 | + protected $useTransactions = true; |
|
82 | + |
|
83 | + /** |
|
84 | + * @var \OCP\Lock\ILockingProvider |
|
85 | + */ |
|
86 | + protected $lockingProvider; |
|
87 | + |
|
88 | + public function __construct(\OC\Files\Storage\Storage $storage) { |
|
89 | + $this->storage = $storage; |
|
90 | + $this->storageId = $this->storage->getId(); |
|
91 | + $this->cache = $storage->getCache(); |
|
92 | + $this->cacheActive = !Config::getSystemValue('filesystem_cache_readonly', false); |
|
93 | + $this->lockingProvider = \OC::$server->getLockingProvider(); |
|
94 | + } |
|
95 | + |
|
96 | + /** |
|
97 | + * Whether to wrap the scanning of a folder in a database transaction |
|
98 | + * On default transactions are used |
|
99 | + * |
|
100 | + * @param bool $useTransactions |
|
101 | + */ |
|
102 | + public function setUseTransactions($useTransactions) { |
|
103 | + $this->useTransactions = $useTransactions; |
|
104 | + } |
|
105 | + |
|
106 | + /** |
|
107 | + * get all the metadata of a file or folder |
|
108 | + * * |
|
109 | + * |
|
110 | + * @param string $path |
|
111 | + * @return array an array of metadata of the file |
|
112 | + */ |
|
113 | + protected function getData($path) { |
|
114 | + $data = $this->storage->getMetaData($path); |
|
115 | + if (is_null($data)) { |
|
116 | + \OCP\Util::writeLog('OC\Files\Cache\Scanner', "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG); |
|
117 | + } |
|
118 | + return $data; |
|
119 | + } |
|
120 | + |
|
121 | + /** |
|
122 | + * scan a single file and store it in the cache |
|
123 | + * |
|
124 | + * @param string $file |
|
125 | + * @param int $reuseExisting |
|
126 | + * @param int $parentId |
|
127 | + * @param array | null $cacheData existing data in the cache for the file to be scanned |
|
128 | + * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
129 | + * @return array an array of metadata of the scanned file |
|
130 | + * @throws \OC\ServerNotAvailableException |
|
131 | + * @throws \OCP\Lock\LockedException |
|
132 | + */ |
|
133 | + public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) { |
|
134 | + if ($file !== '') { |
|
135 | + try { |
|
136 | + $this->storage->verifyPath(dirname($file), basename($file)); |
|
137 | + } catch (\Exception $e) { |
|
138 | + return null; |
|
139 | + } |
|
140 | + } |
|
141 | + |
|
142 | + // only proceed if $file is not a partial file nor a blacklisted file |
|
143 | + if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) { |
|
144 | + |
|
145 | + //acquire a lock |
|
146 | + if ($lock) { |
|
147 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
148 | + $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
149 | + } |
|
150 | + } |
|
151 | + |
|
152 | + try { |
|
153 | + $data = $this->getData($file); |
|
154 | + } catch (ForbiddenException $e) { |
|
155 | + return null; |
|
156 | + } |
|
157 | + |
|
158 | + if ($data) { |
|
159 | + |
|
160 | + // pre-emit only if it was a file. By that we avoid counting/treating folders as files |
|
161 | + if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
162 | + $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId)); |
|
163 | + \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
164 | + } |
|
165 | + |
|
166 | + $parent = dirname($file); |
|
167 | + if ($parent === '.' or $parent === '/') { |
|
168 | + $parent = ''; |
|
169 | + } |
|
170 | + if ($parentId === -1) { |
|
171 | + $parentId = $this->cache->getParentId($file); |
|
172 | + } |
|
173 | + |
|
174 | + // scan the parent if it's not in the cache (id -1) and the current file is not the root folder |
|
175 | + if ($file and $parentId === -1) { |
|
176 | + $parentData = $this->scanFile($parent); |
|
177 | + if (!$parentData) { |
|
178 | + return null; |
|
179 | + } |
|
180 | + $parentId = $parentData['fileid']; |
|
181 | + } |
|
182 | + if ($parent) { |
|
183 | + $data['parent'] = $parentId; |
|
184 | + } |
|
185 | + if (is_null($cacheData)) { |
|
186 | + /** @var CacheEntry $cacheData */ |
|
187 | + $cacheData = $this->cache->get($file); |
|
188 | + } |
|
189 | + if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) { |
|
190 | + // prevent empty etag |
|
191 | + if (empty($cacheData['etag'])) { |
|
192 | + $etag = $data['etag']; |
|
193 | + } else { |
|
194 | + $etag = $cacheData['etag']; |
|
195 | + } |
|
196 | + $fileId = $cacheData['fileid']; |
|
197 | + $data['fileid'] = $fileId; |
|
198 | + // only reuse data if the file hasn't explicitly changed |
|
199 | + if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) { |
|
200 | + $data['mtime'] = $cacheData['mtime']; |
|
201 | + if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) { |
|
202 | + $data['size'] = $cacheData['size']; |
|
203 | + } |
|
204 | + if ($reuseExisting & self::REUSE_ETAG) { |
|
205 | + $data['etag'] = $etag; |
|
206 | + } |
|
207 | + } |
|
208 | + // Only update metadata that has changed |
|
209 | + $newData = array_diff_assoc($data, $cacheData->getData()); |
|
210 | + } else { |
|
211 | + $newData = $data; |
|
212 | + $fileId = -1; |
|
213 | + } |
|
214 | + if (!empty($newData)) { |
|
215 | + // Reset the checksum if the data has changed |
|
216 | + $newData['checksum'] = ''; |
|
217 | + $data['fileid'] = $this->addToCache($file, $newData, $fileId); |
|
218 | + } |
|
219 | + if (isset($cacheData['size'])) { |
|
220 | + $data['oldSize'] = $cacheData['size']; |
|
221 | + } else { |
|
222 | + $data['oldSize'] = 0; |
|
223 | + } |
|
224 | + |
|
225 | + if (isset($cacheData['encrypted'])) { |
|
226 | + $data['encrypted'] = $cacheData['encrypted']; |
|
227 | + } |
|
228 | + |
|
229 | + // post-emit only if it was a file. By that we avoid counting/treating folders as files |
|
230 | + if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
231 | + $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); |
|
232 | + \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
233 | + } |
|
234 | + |
|
235 | + } else { |
|
236 | + $this->removeFromCache($file); |
|
237 | + } |
|
238 | + |
|
239 | + //release the acquired lock |
|
240 | + if ($lock) { |
|
241 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
242 | + $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
243 | + } |
|
244 | + } |
|
245 | + |
|
246 | + if ($data && !isset($data['encrypted'])) { |
|
247 | + $data['encrypted'] = false; |
|
248 | + } |
|
249 | + return $data; |
|
250 | + } |
|
251 | + |
|
252 | + return null; |
|
253 | + } |
|
254 | + |
|
255 | + protected function removeFromCache($path) { |
|
256 | + \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path)); |
|
257 | + $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path)); |
|
258 | + if ($this->cacheActive) { |
|
259 | + $this->cache->remove($path); |
|
260 | + } |
|
261 | + } |
|
262 | + |
|
263 | + /** |
|
264 | + * @param string $path |
|
265 | + * @param array $data |
|
266 | + * @param int $fileId |
|
267 | + * @return int the id of the added file |
|
268 | + */ |
|
269 | + protected function addToCache($path, $data, $fileId = -1) { |
|
270 | + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
271 | + $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data)); |
|
272 | + if ($this->cacheActive) { |
|
273 | + if ($fileId !== -1) { |
|
274 | + $this->cache->update($fileId, $data); |
|
275 | + return $fileId; |
|
276 | + } else { |
|
277 | + return $this->cache->put($path, $data); |
|
278 | + } |
|
279 | + } else { |
|
280 | + return -1; |
|
281 | + } |
|
282 | + } |
|
283 | + |
|
284 | + /** |
|
285 | + * @param string $path |
|
286 | + * @param array $data |
|
287 | + * @param int $fileId |
|
288 | + */ |
|
289 | + protected function updateCache($path, $data, $fileId = -1) { |
|
290 | + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
291 | + $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data)); |
|
292 | + if ($this->cacheActive) { |
|
293 | + if ($fileId !== -1) { |
|
294 | + $this->cache->update($fileId, $data); |
|
295 | + } else { |
|
296 | + $this->cache->put($path, $data); |
|
297 | + } |
|
298 | + } |
|
299 | + } |
|
300 | + |
|
301 | + /** |
|
302 | + * scan a folder and all it's children |
|
303 | + * |
|
304 | + * @param string $path |
|
305 | + * @param bool $recursive |
|
306 | + * @param int $reuse |
|
307 | + * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
308 | + * @return array an array of the meta data of the scanned file or folder |
|
309 | + */ |
|
310 | + public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) { |
|
311 | + if ($reuse === -1) { |
|
312 | + $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
313 | + } |
|
314 | + if ($lock) { |
|
315 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
316 | + $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
317 | + $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
318 | + } |
|
319 | + } |
|
320 | + $data = $this->scanFile($path, $reuse, -1, null, $lock); |
|
321 | + if ($data and $data['mimetype'] === 'httpd/unix-directory') { |
|
322 | + $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock); |
|
323 | + $data['size'] = $size; |
|
324 | + } |
|
325 | + if ($lock) { |
|
326 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
327 | + $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
328 | + $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
329 | + } |
|
330 | + } |
|
331 | + return $data; |
|
332 | + } |
|
333 | + |
|
334 | + /** |
|
335 | + * Get the children currently in the cache |
|
336 | + * |
|
337 | + * @param int $folderId |
|
338 | + * @return array[] |
|
339 | + */ |
|
340 | + protected function getExistingChildren($folderId) { |
|
341 | + $existingChildren = array(); |
|
342 | + $children = $this->cache->getFolderContentsById($folderId); |
|
343 | + foreach ($children as $child) { |
|
344 | + $existingChildren[$child['name']] = $child; |
|
345 | + } |
|
346 | + return $existingChildren; |
|
347 | + } |
|
348 | + |
|
349 | + /** |
|
350 | + * Get the children from the storage |
|
351 | + * |
|
352 | + * @param string $folder |
|
353 | + * @return string[] |
|
354 | + */ |
|
355 | + protected function getNewChildren($folder) { |
|
356 | + $children = array(); |
|
357 | + if ($dh = $this->storage->opendir($folder)) { |
|
358 | + if (is_resource($dh)) { |
|
359 | + while (($file = readdir($dh)) !== false) { |
|
360 | + if (!Filesystem::isIgnoredDir($file)) { |
|
361 | + $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/'); |
|
362 | + } |
|
363 | + } |
|
364 | + } |
|
365 | + } |
|
366 | + return $children; |
|
367 | + } |
|
368 | + |
|
369 | + /** |
|
370 | + * scan all the files and folders in a folder |
|
371 | + * |
|
372 | + * @param string $path |
|
373 | + * @param bool $recursive |
|
374 | + * @param int $reuse |
|
375 | + * @param int $folderId id for the folder to be scanned |
|
376 | + * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
377 | + * @return int the size of the scanned folder or -1 if the size is unknown at this stage |
|
378 | + */ |
|
379 | + protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) { |
|
380 | + if ($reuse === -1) { |
|
381 | + $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
382 | + } |
|
383 | + $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId)); |
|
384 | + $size = 0; |
|
385 | + if (!is_null($folderId)) { |
|
386 | + $folderId = $this->cache->getId($path); |
|
387 | + } |
|
388 | + $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size); |
|
389 | + |
|
390 | + foreach ($childQueue as $child => $childId) { |
|
391 | + $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock); |
|
392 | + if ($childSize === -1) { |
|
393 | + $size = -1; |
|
394 | + } else if ($size !== -1) { |
|
395 | + $size += $childSize; |
|
396 | + } |
|
397 | + } |
|
398 | + if ($this->cacheActive) { |
|
399 | + $this->cache->update($folderId, array('size' => $size)); |
|
400 | + } |
|
401 | + $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId)); |
|
402 | + return $size; |
|
403 | + } |
|
404 | + |
|
405 | + private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) { |
|
406 | + // we put this in it's own function so it cleans up the memory before we start recursing |
|
407 | + $existingChildren = $this->getExistingChildren($folderId); |
|
408 | + $newChildren = $this->getNewChildren($path); |
|
409 | + |
|
410 | + if ($this->useTransactions) { |
|
411 | + \OC::$server->getDatabaseConnection()->beginTransaction(); |
|
412 | + } |
|
413 | + |
|
414 | + $exceptionOccurred = false; |
|
415 | + $childQueue = []; |
|
416 | + foreach ($newChildren as $file) { |
|
417 | + $child = ($path) ? $path . '/' . $file : $file; |
|
418 | + try { |
|
419 | + $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; |
|
420 | + $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); |
|
421 | + if ($data) { |
|
422 | + if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) { |
|
423 | + $childQueue[$child] = $data['fileid']; |
|
424 | + } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) { |
|
425 | + // only recurse into folders which aren't fully scanned |
|
426 | + $childQueue[$child] = $data['fileid']; |
|
427 | + } else if ($data['size'] === -1) { |
|
428 | + $size = -1; |
|
429 | + } else if ($size !== -1) { |
|
430 | + $size += $data['size']; |
|
431 | + } |
|
432 | + } |
|
433 | + } catch (\Doctrine\DBAL\DBALException $ex) { |
|
434 | + // might happen if inserting duplicate while a scanning |
|
435 | + // process is running in parallel |
|
436 | + // log and ignore |
|
437 | + \OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG); |
|
438 | + $exceptionOccurred = true; |
|
439 | + } catch (\OCP\Lock\LockedException $e) { |
|
440 | + if ($this->useTransactions) { |
|
441 | + \OC::$server->getDatabaseConnection()->rollback(); |
|
442 | + } |
|
443 | + throw $e; |
|
444 | + } |
|
445 | + } |
|
446 | + $removedChildren = \array_diff(array_keys($existingChildren), $newChildren); |
|
447 | + foreach ($removedChildren as $childName) { |
|
448 | + $child = ($path) ? $path . '/' . $childName : $childName; |
|
449 | + $this->removeFromCache($child); |
|
450 | + } |
|
451 | + if ($this->useTransactions) { |
|
452 | + \OC::$server->getDatabaseConnection()->commit(); |
|
453 | + } |
|
454 | + if ($exceptionOccurred) { |
|
455 | + // It might happen that the parallel scan process has already |
|
456 | + // inserted mimetypes but those weren't available yet inside the transaction |
|
457 | + // To make sure to have the updated mime types in such cases, |
|
458 | + // we reload them here |
|
459 | + \OC::$server->getMimeTypeLoader()->reset(); |
|
460 | + } |
|
461 | + return $childQueue; |
|
462 | + } |
|
463 | + |
|
464 | + /** |
|
465 | + * check if the file should be ignored when scanning |
|
466 | + * NOTE: files with a '.part' extension are ignored as well! |
|
467 | + * prevents unfinished put requests to be scanned |
|
468 | + * |
|
469 | + * @param string $file |
|
470 | + * @return boolean |
|
471 | + */ |
|
472 | + public static function isPartialFile($file) { |
|
473 | + if (pathinfo($file, PATHINFO_EXTENSION) === 'part') { |
|
474 | + return true; |
|
475 | + } |
|
476 | + if (strpos($file, '.part/') !== false) { |
|
477 | + return true; |
|
478 | + } |
|
479 | + |
|
480 | + return false; |
|
481 | + } |
|
482 | + |
|
483 | + /** |
|
484 | + * walk over any folders that are not fully scanned yet and scan them |
|
485 | + */ |
|
486 | + public function backgroundScan() { |
|
487 | + if (!$this->cache->inCache('')) { |
|
488 | + $this->runBackgroundScanJob(function () { |
|
489 | + $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); |
|
490 | + }, ''); |
|
491 | + } else { |
|
492 | + $lastPath = null; |
|
493 | + while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { |
|
494 | + $this->runBackgroundScanJob(function () use ($path) { |
|
495 | + $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); |
|
496 | + }, $path); |
|
497 | + // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() |
|
498 | + // to make this possible |
|
499 | + $lastPath = $path; |
|
500 | + } |
|
501 | + } |
|
502 | + } |
|
503 | + |
|
504 | + private function runBackgroundScanJob(callable $callback, $path) { |
|
505 | + try { |
|
506 | + $callback(); |
|
507 | + \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); |
|
508 | + if ($this->cacheActive && $this->cache instanceof Cache) { |
|
509 | + $this->cache->correctFolderSize($path); |
|
510 | + } |
|
511 | + } catch (\OCP\Files\StorageInvalidException $e) { |
|
512 | + // skip unavailable storages |
|
513 | + } catch (\OCP\Files\StorageNotAvailableException $e) { |
|
514 | + // skip unavailable storages |
|
515 | + } catch (\OCP\Files\ForbiddenException $e) { |
|
516 | + // skip forbidden storages |
|
517 | + } catch (\OCP\Lock\LockedException $e) { |
|
518 | + // skip unavailable storages |
|
519 | + } |
|
520 | + } |
|
521 | + |
|
522 | + /** |
|
523 | + * Set whether the cache is affected by scan operations |
|
524 | + * |
|
525 | + * @param boolean $active The active state of the cache |
|
526 | + */ |
|
527 | + public function setCacheActive($active) { |
|
528 | + $this->cacheActive = $active; |
|
529 | + } |
|
530 | 530 | } |
@@ -313,7 +313,7 @@ discard block |
||
313 | 313 | } |
314 | 314 | if ($lock) { |
315 | 315 | if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
316 | - $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
316 | + $this->storage->acquireLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
317 | 317 | $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
318 | 318 | } |
319 | 319 | } |
@@ -325,7 +325,7 @@ discard block |
||
325 | 325 | if ($lock) { |
326 | 326 | if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
327 | 327 | $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
328 | - $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
328 | + $this->storage->releaseLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
329 | 329 | } |
330 | 330 | } |
331 | 331 | return $data; |
@@ -414,7 +414,7 @@ discard block |
||
414 | 414 | $exceptionOccurred = false; |
415 | 415 | $childQueue = []; |
416 | 416 | foreach ($newChildren as $file) { |
417 | - $child = ($path) ? $path . '/' . $file : $file; |
|
417 | + $child = ($path) ? $path.'/'.$file : $file; |
|
418 | 418 | try { |
419 | 419 | $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; |
420 | 420 | $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); |
@@ -434,7 +434,7 @@ discard block |
||
434 | 434 | // might happen if inserting duplicate while a scanning |
435 | 435 | // process is running in parallel |
436 | 436 | // log and ignore |
437 | - \OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG); |
|
437 | + \OCP\Util::writeLog('core', 'Exception while scanning file "'.$child.'": '.$ex->getMessage(), \OCP\Util::DEBUG); |
|
438 | 438 | $exceptionOccurred = true; |
439 | 439 | } catch (\OCP\Lock\LockedException $e) { |
440 | 440 | if ($this->useTransactions) { |
@@ -445,7 +445,7 @@ discard block |
||
445 | 445 | } |
446 | 446 | $removedChildren = \array_diff(array_keys($existingChildren), $newChildren); |
447 | 447 | foreach ($removedChildren as $childName) { |
448 | - $child = ($path) ? $path . '/' . $childName : $childName; |
|
448 | + $child = ($path) ? $path.'/'.$childName : $childName; |
|
449 | 449 | $this->removeFromCache($child); |
450 | 450 | } |
451 | 451 | if ($this->useTransactions) { |
@@ -485,13 +485,13 @@ discard block |
||
485 | 485 | */ |
486 | 486 | public function backgroundScan() { |
487 | 487 | if (!$this->cache->inCache('')) { |
488 | - $this->runBackgroundScanJob(function () { |
|
488 | + $this->runBackgroundScanJob(function() { |
|
489 | 489 | $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); |
490 | 490 | }, ''); |
491 | 491 | } else { |
492 | 492 | $lastPath = null; |
493 | 493 | while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { |
494 | - $this->runBackgroundScanJob(function () use ($path) { |
|
494 | + $this->runBackgroundScanJob(function() use ($path) { |
|
495 | 495 | $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); |
496 | 496 | }, $path); |
497 | 497 | // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() |
@@ -206,7 +206,7 @@ |
||
206 | 206 | } |
207 | 207 | |
208 | 208 | /** |
209 | - * @param $fileId |
|
209 | + * @param integer $fileId |
|
210 | 210 | * @return array |
211 | 211 | * @throws \OCP\Files\NotFoundException |
212 | 212 | */ |
@@ -24,14 +24,11 @@ |
||
24 | 24 | |
25 | 25 | namespace OC\Files\Config; |
26 | 26 | |
27 | -use Doctrine\DBAL\Exception\UniqueConstraintViolationException; |
|
28 | -use OC\Files\Filesystem; |
|
29 | 27 | use OCA\Files_Sharing\SharedMount; |
30 | 28 | use OCP\DB\QueryBuilder\IQueryBuilder; |
31 | 29 | use OCP\Files\Config\ICachedMountInfo; |
32 | 30 | use OCP\Files\Config\IUserMountCache; |
33 | 31 | use OCP\Files\Mount\IMountPoint; |
34 | -use OCP\Files\Node; |
|
35 | 32 | use OCP\Files\NotFoundException; |
36 | 33 | use OCP\ICache; |
37 | 34 | use OCP\IDBConnection; |
@@ -44,289 +44,289 @@ |
||
44 | 44 | * Cache mounts points per user in the cache so we can easilly look them up |
45 | 45 | */ |
46 | 46 | class UserMountCache implements IUserMountCache { |
47 | - /** |
|
48 | - * @var IDBConnection |
|
49 | - */ |
|
50 | - private $connection; |
|
51 | - |
|
52 | - /** |
|
53 | - * @var IUserManager |
|
54 | - */ |
|
55 | - private $userManager; |
|
56 | - |
|
57 | - /** |
|
58 | - * Cached mount info. |
|
59 | - * Map of $userId to ICachedMountInfo. |
|
60 | - * |
|
61 | - * @var ICache |
|
62 | - **/ |
|
63 | - private $mountsForUsers; |
|
64 | - |
|
65 | - /** |
|
66 | - * @var ILogger |
|
67 | - */ |
|
68 | - private $logger; |
|
69 | - |
|
70 | - /** |
|
71 | - * @var ICache |
|
72 | - */ |
|
73 | - private $cacheInfoCache; |
|
74 | - |
|
75 | - /** |
|
76 | - * UserMountCache constructor. |
|
77 | - * |
|
78 | - * @param IDBConnection $connection |
|
79 | - * @param IUserManager $userManager |
|
80 | - * @param ILogger $logger |
|
81 | - */ |
|
82 | - public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) { |
|
83 | - $this->connection = $connection; |
|
84 | - $this->userManager = $userManager; |
|
85 | - $this->logger = $logger; |
|
86 | - $this->cacheInfoCache = new CappedMemoryCache(); |
|
87 | - $this->mountsForUsers = new CappedMemoryCache(); |
|
88 | - } |
|
89 | - |
|
90 | - public function registerMounts(IUser $user, array $mounts) { |
|
91 | - // filter out non-proper storages coming from unit tests |
|
92 | - $mounts = array_filter($mounts, function (IMountPoint $mount) { |
|
93 | - return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache(); |
|
94 | - }); |
|
95 | - /** @var ICachedMountInfo[] $newMounts */ |
|
96 | - $newMounts = array_map(function (IMountPoint $mount) use ($user) { |
|
97 | - // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet) |
|
98 | - if ($mount->getStorageRootId() === -1) { |
|
99 | - return null; |
|
100 | - } else { |
|
101 | - return new LazyStorageMountInfo($user, $mount); |
|
102 | - } |
|
103 | - }, $mounts); |
|
104 | - $newMounts = array_values(array_filter($newMounts)); |
|
105 | - |
|
106 | - $cachedMounts = $this->getMountsForUser($user); |
|
107 | - $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) { |
|
108 | - // since we are only looking for mounts for a specific user comparing on root id is enough |
|
109 | - return $mount1->getRootId() - $mount2->getRootId(); |
|
110 | - }; |
|
111 | - |
|
112 | - /** @var ICachedMountInfo[] $addedMounts */ |
|
113 | - $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff); |
|
114 | - /** @var ICachedMountInfo[] $removedMounts */ |
|
115 | - $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff); |
|
116 | - |
|
117 | - $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts); |
|
118 | - |
|
119 | - foreach ($addedMounts as $mount) { |
|
120 | - $this->addToCache($mount); |
|
121 | - $this->mountsForUsers[$user->getUID()][] = $mount; |
|
122 | - } |
|
123 | - foreach ($removedMounts as $mount) { |
|
124 | - $this->removeFromCache($mount); |
|
125 | - $index = array_search($mount, $this->mountsForUsers[$user->getUID()]); |
|
126 | - unset($this->mountsForUsers[$user->getUID()][$index]); |
|
127 | - } |
|
128 | - foreach ($changedMounts as $mount) { |
|
129 | - $this->updateCachedMount($mount); |
|
130 | - } |
|
131 | - } |
|
132 | - |
|
133 | - /** |
|
134 | - * @param ICachedMountInfo[] $newMounts |
|
135 | - * @param ICachedMountInfo[] $cachedMounts |
|
136 | - * @return ICachedMountInfo[] |
|
137 | - */ |
|
138 | - private function findChangedMounts(array $newMounts, array $cachedMounts) { |
|
139 | - $changed = []; |
|
140 | - foreach ($newMounts as $newMount) { |
|
141 | - foreach ($cachedMounts as $cachedMount) { |
|
142 | - if ( |
|
143 | - $newMount->getRootId() === $cachedMount->getRootId() && |
|
144 | - ( |
|
145 | - $newMount->getMountPoint() !== $cachedMount->getMountPoint() || |
|
146 | - $newMount->getStorageId() !== $cachedMount->getStorageId() || |
|
147 | - $newMount->getMountId() !== $cachedMount->getMountId() |
|
148 | - ) |
|
149 | - ) { |
|
150 | - $changed[] = $newMount; |
|
151 | - } |
|
152 | - } |
|
153 | - } |
|
154 | - return $changed; |
|
155 | - } |
|
156 | - |
|
157 | - private function addToCache(ICachedMountInfo $mount) { |
|
158 | - if ($mount->getStorageId() !== -1) { |
|
159 | - $this->connection->insertIfNotExist('*PREFIX*mounts', [ |
|
160 | - 'storage_id' => $mount->getStorageId(), |
|
161 | - 'root_id' => $mount->getRootId(), |
|
162 | - 'user_id' => $mount->getUser()->getUID(), |
|
163 | - 'mount_point' => $mount->getMountPoint(), |
|
164 | - 'mount_id' => $mount->getMountId() |
|
165 | - ], ['root_id', 'user_id']); |
|
166 | - } else { |
|
167 | - // in some cases this is legitimate, like orphaned shares |
|
168 | - $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint()); |
|
169 | - } |
|
170 | - } |
|
171 | - |
|
172 | - private function updateCachedMount(ICachedMountInfo $mount) { |
|
173 | - $builder = $this->connection->getQueryBuilder(); |
|
174 | - |
|
175 | - $query = $builder->update('mounts') |
|
176 | - ->set('storage_id', $builder->createNamedParameter($mount->getStorageId())) |
|
177 | - ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint())) |
|
178 | - ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT)) |
|
179 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID()))) |
|
180 | - ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT))); |
|
181 | - |
|
182 | - $query->execute(); |
|
183 | - } |
|
184 | - |
|
185 | - private function removeFromCache(ICachedMountInfo $mount) { |
|
186 | - $builder = $this->connection->getQueryBuilder(); |
|
187 | - |
|
188 | - $query = $builder->delete('mounts') |
|
189 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID()))) |
|
190 | - ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT))); |
|
191 | - $query->execute(); |
|
192 | - } |
|
193 | - |
|
194 | - private function dbRowToMountInfo(array $row) { |
|
195 | - $user = $this->userManager->get($row['user_id']); |
|
196 | - if (is_null($user)) { |
|
197 | - return null; |
|
198 | - } |
|
199 | - return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path'])? $row['path']:''); |
|
200 | - } |
|
201 | - |
|
202 | - /** |
|
203 | - * @param IUser $user |
|
204 | - * @return ICachedMountInfo[] |
|
205 | - */ |
|
206 | - public function getMountsForUser(IUser $user) { |
|
207 | - if (!isset($this->mountsForUsers[$user->getUID()])) { |
|
208 | - $builder = $this->connection->getQueryBuilder(); |
|
209 | - $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
210 | - ->from('mounts', 'm') |
|
211 | - ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
212 | - ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID()))); |
|
213 | - |
|
214 | - $rows = $query->execute()->fetchAll(); |
|
215 | - |
|
216 | - $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
217 | - } |
|
218 | - return $this->mountsForUsers[$user->getUID()]; |
|
219 | - } |
|
220 | - |
|
221 | - /** |
|
222 | - * @param int $numericStorageId |
|
223 | - * @return CachedMountInfo[] |
|
224 | - */ |
|
225 | - public function getMountsForStorageId($numericStorageId) { |
|
226 | - $builder = $this->connection->getQueryBuilder(); |
|
227 | - $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
228 | - ->from('mounts', 'm') |
|
229 | - ->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
230 | - ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT))); |
|
231 | - |
|
232 | - $rows = $query->execute()->fetchAll(); |
|
233 | - |
|
234 | - return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
235 | - } |
|
236 | - |
|
237 | - /** |
|
238 | - * @param int $rootFileId |
|
239 | - * @return CachedMountInfo[] |
|
240 | - */ |
|
241 | - public function getMountsForRootId($rootFileId) { |
|
242 | - $builder = $this->connection->getQueryBuilder(); |
|
243 | - $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
244 | - ->from('mounts', 'm') |
|
245 | - ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
246 | - ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT))); |
|
247 | - |
|
248 | - $rows = $query->execute()->fetchAll(); |
|
249 | - |
|
250 | - return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
251 | - } |
|
252 | - |
|
253 | - /** |
|
254 | - * @param $fileId |
|
255 | - * @return array |
|
256 | - * @throws \OCP\Files\NotFoundException |
|
257 | - */ |
|
258 | - private function getCacheInfoFromFileId($fileId) { |
|
259 | - if (!isset($this->cacheInfoCache[$fileId])) { |
|
260 | - $builder = $this->connection->getQueryBuilder(); |
|
261 | - $query = $builder->select('storage', 'path', 'mimetype') |
|
262 | - ->from('filecache') |
|
263 | - ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT))); |
|
264 | - |
|
265 | - $row = $query->execute()->fetch(); |
|
266 | - if (is_array($row)) { |
|
267 | - $this->cacheInfoCache[$fileId] = [ |
|
268 | - (int)$row['storage'], |
|
269 | - $row['path'], |
|
270 | - (int)$row['mimetype'] |
|
271 | - ]; |
|
272 | - } else { |
|
273 | - throw new NotFoundException('File with id "' . $fileId . '" not found'); |
|
274 | - } |
|
275 | - } |
|
276 | - return $this->cacheInfoCache[$fileId]; |
|
277 | - } |
|
278 | - |
|
279 | - /** |
|
280 | - * @param int $fileId |
|
281 | - * @return ICachedMountInfo[] |
|
282 | - * @since 9.0.0 |
|
283 | - */ |
|
284 | - public function getMountsForFileId($fileId) { |
|
285 | - try { |
|
286 | - list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId); |
|
287 | - } catch (NotFoundException $e) { |
|
288 | - return []; |
|
289 | - } |
|
290 | - $mountsForStorage = $this->getMountsForStorageId($storageId); |
|
291 | - |
|
292 | - // filter mounts that are from the same storage but a different directory |
|
293 | - return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
294 | - if ($fileId === $mount->getRootId()) { |
|
295 | - return true; |
|
296 | - } |
|
297 | - $internalMountPath = $mount->getRootInternalPath(); |
|
298 | - |
|
299 | - return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/'; |
|
300 | - }); |
|
301 | - } |
|
302 | - |
|
303 | - /** |
|
304 | - * Remove all cached mounts for a user |
|
305 | - * |
|
306 | - * @param IUser $user |
|
307 | - */ |
|
308 | - public function removeUserMounts(IUser $user) { |
|
309 | - $builder = $this->connection->getQueryBuilder(); |
|
310 | - |
|
311 | - $query = $builder->delete('mounts') |
|
312 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID()))); |
|
313 | - $query->execute(); |
|
314 | - } |
|
315 | - |
|
316 | - public function removeUserStorageMount($storageId, $userId) { |
|
317 | - $builder = $this->connection->getQueryBuilder(); |
|
318 | - |
|
319 | - $query = $builder->delete('mounts') |
|
320 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId))) |
|
321 | - ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
322 | - $query->execute(); |
|
323 | - } |
|
324 | - |
|
325 | - public function remoteStorageMounts($storageId) { |
|
326 | - $builder = $this->connection->getQueryBuilder(); |
|
327 | - |
|
328 | - $query = $builder->delete('mounts') |
|
329 | - ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
330 | - $query->execute(); |
|
331 | - } |
|
47 | + /** |
|
48 | + * @var IDBConnection |
|
49 | + */ |
|
50 | + private $connection; |
|
51 | + |
|
52 | + /** |
|
53 | + * @var IUserManager |
|
54 | + */ |
|
55 | + private $userManager; |
|
56 | + |
|
57 | + /** |
|
58 | + * Cached mount info. |
|
59 | + * Map of $userId to ICachedMountInfo. |
|
60 | + * |
|
61 | + * @var ICache |
|
62 | + **/ |
|
63 | + private $mountsForUsers; |
|
64 | + |
|
65 | + /** |
|
66 | + * @var ILogger |
|
67 | + */ |
|
68 | + private $logger; |
|
69 | + |
|
70 | + /** |
|
71 | + * @var ICache |
|
72 | + */ |
|
73 | + private $cacheInfoCache; |
|
74 | + |
|
75 | + /** |
|
76 | + * UserMountCache constructor. |
|
77 | + * |
|
78 | + * @param IDBConnection $connection |
|
79 | + * @param IUserManager $userManager |
|
80 | + * @param ILogger $logger |
|
81 | + */ |
|
82 | + public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) { |
|
83 | + $this->connection = $connection; |
|
84 | + $this->userManager = $userManager; |
|
85 | + $this->logger = $logger; |
|
86 | + $this->cacheInfoCache = new CappedMemoryCache(); |
|
87 | + $this->mountsForUsers = new CappedMemoryCache(); |
|
88 | + } |
|
89 | + |
|
90 | + public function registerMounts(IUser $user, array $mounts) { |
|
91 | + // filter out non-proper storages coming from unit tests |
|
92 | + $mounts = array_filter($mounts, function (IMountPoint $mount) { |
|
93 | + return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache(); |
|
94 | + }); |
|
95 | + /** @var ICachedMountInfo[] $newMounts */ |
|
96 | + $newMounts = array_map(function (IMountPoint $mount) use ($user) { |
|
97 | + // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet) |
|
98 | + if ($mount->getStorageRootId() === -1) { |
|
99 | + return null; |
|
100 | + } else { |
|
101 | + return new LazyStorageMountInfo($user, $mount); |
|
102 | + } |
|
103 | + }, $mounts); |
|
104 | + $newMounts = array_values(array_filter($newMounts)); |
|
105 | + |
|
106 | + $cachedMounts = $this->getMountsForUser($user); |
|
107 | + $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) { |
|
108 | + // since we are only looking for mounts for a specific user comparing on root id is enough |
|
109 | + return $mount1->getRootId() - $mount2->getRootId(); |
|
110 | + }; |
|
111 | + |
|
112 | + /** @var ICachedMountInfo[] $addedMounts */ |
|
113 | + $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff); |
|
114 | + /** @var ICachedMountInfo[] $removedMounts */ |
|
115 | + $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff); |
|
116 | + |
|
117 | + $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts); |
|
118 | + |
|
119 | + foreach ($addedMounts as $mount) { |
|
120 | + $this->addToCache($mount); |
|
121 | + $this->mountsForUsers[$user->getUID()][] = $mount; |
|
122 | + } |
|
123 | + foreach ($removedMounts as $mount) { |
|
124 | + $this->removeFromCache($mount); |
|
125 | + $index = array_search($mount, $this->mountsForUsers[$user->getUID()]); |
|
126 | + unset($this->mountsForUsers[$user->getUID()][$index]); |
|
127 | + } |
|
128 | + foreach ($changedMounts as $mount) { |
|
129 | + $this->updateCachedMount($mount); |
|
130 | + } |
|
131 | + } |
|
132 | + |
|
133 | + /** |
|
134 | + * @param ICachedMountInfo[] $newMounts |
|
135 | + * @param ICachedMountInfo[] $cachedMounts |
|
136 | + * @return ICachedMountInfo[] |
|
137 | + */ |
|
138 | + private function findChangedMounts(array $newMounts, array $cachedMounts) { |
|
139 | + $changed = []; |
|
140 | + foreach ($newMounts as $newMount) { |
|
141 | + foreach ($cachedMounts as $cachedMount) { |
|
142 | + if ( |
|
143 | + $newMount->getRootId() === $cachedMount->getRootId() && |
|
144 | + ( |
|
145 | + $newMount->getMountPoint() !== $cachedMount->getMountPoint() || |
|
146 | + $newMount->getStorageId() !== $cachedMount->getStorageId() || |
|
147 | + $newMount->getMountId() !== $cachedMount->getMountId() |
|
148 | + ) |
|
149 | + ) { |
|
150 | + $changed[] = $newMount; |
|
151 | + } |
|
152 | + } |
|
153 | + } |
|
154 | + return $changed; |
|
155 | + } |
|
156 | + |
|
157 | + private function addToCache(ICachedMountInfo $mount) { |
|
158 | + if ($mount->getStorageId() !== -1) { |
|
159 | + $this->connection->insertIfNotExist('*PREFIX*mounts', [ |
|
160 | + 'storage_id' => $mount->getStorageId(), |
|
161 | + 'root_id' => $mount->getRootId(), |
|
162 | + 'user_id' => $mount->getUser()->getUID(), |
|
163 | + 'mount_point' => $mount->getMountPoint(), |
|
164 | + 'mount_id' => $mount->getMountId() |
|
165 | + ], ['root_id', 'user_id']); |
|
166 | + } else { |
|
167 | + // in some cases this is legitimate, like orphaned shares |
|
168 | + $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint()); |
|
169 | + } |
|
170 | + } |
|
171 | + |
|
172 | + private function updateCachedMount(ICachedMountInfo $mount) { |
|
173 | + $builder = $this->connection->getQueryBuilder(); |
|
174 | + |
|
175 | + $query = $builder->update('mounts') |
|
176 | + ->set('storage_id', $builder->createNamedParameter($mount->getStorageId())) |
|
177 | + ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint())) |
|
178 | + ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT)) |
|
179 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID()))) |
|
180 | + ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT))); |
|
181 | + |
|
182 | + $query->execute(); |
|
183 | + } |
|
184 | + |
|
185 | + private function removeFromCache(ICachedMountInfo $mount) { |
|
186 | + $builder = $this->connection->getQueryBuilder(); |
|
187 | + |
|
188 | + $query = $builder->delete('mounts') |
|
189 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID()))) |
|
190 | + ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT))); |
|
191 | + $query->execute(); |
|
192 | + } |
|
193 | + |
|
194 | + private function dbRowToMountInfo(array $row) { |
|
195 | + $user = $this->userManager->get($row['user_id']); |
|
196 | + if (is_null($user)) { |
|
197 | + return null; |
|
198 | + } |
|
199 | + return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path'])? $row['path']:''); |
|
200 | + } |
|
201 | + |
|
202 | + /** |
|
203 | + * @param IUser $user |
|
204 | + * @return ICachedMountInfo[] |
|
205 | + */ |
|
206 | + public function getMountsForUser(IUser $user) { |
|
207 | + if (!isset($this->mountsForUsers[$user->getUID()])) { |
|
208 | + $builder = $this->connection->getQueryBuilder(); |
|
209 | + $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
210 | + ->from('mounts', 'm') |
|
211 | + ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
212 | + ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID()))); |
|
213 | + |
|
214 | + $rows = $query->execute()->fetchAll(); |
|
215 | + |
|
216 | + $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
217 | + } |
|
218 | + return $this->mountsForUsers[$user->getUID()]; |
|
219 | + } |
|
220 | + |
|
221 | + /** |
|
222 | + * @param int $numericStorageId |
|
223 | + * @return CachedMountInfo[] |
|
224 | + */ |
|
225 | + public function getMountsForStorageId($numericStorageId) { |
|
226 | + $builder = $this->connection->getQueryBuilder(); |
|
227 | + $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
228 | + ->from('mounts', 'm') |
|
229 | + ->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
230 | + ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT))); |
|
231 | + |
|
232 | + $rows = $query->execute()->fetchAll(); |
|
233 | + |
|
234 | + return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
235 | + } |
|
236 | + |
|
237 | + /** |
|
238 | + * @param int $rootFileId |
|
239 | + * @return CachedMountInfo[] |
|
240 | + */ |
|
241 | + public function getMountsForRootId($rootFileId) { |
|
242 | + $builder = $this->connection->getQueryBuilder(); |
|
243 | + $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
244 | + ->from('mounts', 'm') |
|
245 | + ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
246 | + ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT))); |
|
247 | + |
|
248 | + $rows = $query->execute()->fetchAll(); |
|
249 | + |
|
250 | + return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
251 | + } |
|
252 | + |
|
253 | + /** |
|
254 | + * @param $fileId |
|
255 | + * @return array |
|
256 | + * @throws \OCP\Files\NotFoundException |
|
257 | + */ |
|
258 | + private function getCacheInfoFromFileId($fileId) { |
|
259 | + if (!isset($this->cacheInfoCache[$fileId])) { |
|
260 | + $builder = $this->connection->getQueryBuilder(); |
|
261 | + $query = $builder->select('storage', 'path', 'mimetype') |
|
262 | + ->from('filecache') |
|
263 | + ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT))); |
|
264 | + |
|
265 | + $row = $query->execute()->fetch(); |
|
266 | + if (is_array($row)) { |
|
267 | + $this->cacheInfoCache[$fileId] = [ |
|
268 | + (int)$row['storage'], |
|
269 | + $row['path'], |
|
270 | + (int)$row['mimetype'] |
|
271 | + ]; |
|
272 | + } else { |
|
273 | + throw new NotFoundException('File with id "' . $fileId . '" not found'); |
|
274 | + } |
|
275 | + } |
|
276 | + return $this->cacheInfoCache[$fileId]; |
|
277 | + } |
|
278 | + |
|
279 | + /** |
|
280 | + * @param int $fileId |
|
281 | + * @return ICachedMountInfo[] |
|
282 | + * @since 9.0.0 |
|
283 | + */ |
|
284 | + public function getMountsForFileId($fileId) { |
|
285 | + try { |
|
286 | + list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId); |
|
287 | + } catch (NotFoundException $e) { |
|
288 | + return []; |
|
289 | + } |
|
290 | + $mountsForStorage = $this->getMountsForStorageId($storageId); |
|
291 | + |
|
292 | + // filter mounts that are from the same storage but a different directory |
|
293 | + return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
294 | + if ($fileId === $mount->getRootId()) { |
|
295 | + return true; |
|
296 | + } |
|
297 | + $internalMountPath = $mount->getRootInternalPath(); |
|
298 | + |
|
299 | + return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/'; |
|
300 | + }); |
|
301 | + } |
|
302 | + |
|
303 | + /** |
|
304 | + * Remove all cached mounts for a user |
|
305 | + * |
|
306 | + * @param IUser $user |
|
307 | + */ |
|
308 | + public function removeUserMounts(IUser $user) { |
|
309 | + $builder = $this->connection->getQueryBuilder(); |
|
310 | + |
|
311 | + $query = $builder->delete('mounts') |
|
312 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID()))); |
|
313 | + $query->execute(); |
|
314 | + } |
|
315 | + |
|
316 | + public function removeUserStorageMount($storageId, $userId) { |
|
317 | + $builder = $this->connection->getQueryBuilder(); |
|
318 | + |
|
319 | + $query = $builder->delete('mounts') |
|
320 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId))) |
|
321 | + ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
322 | + $query->execute(); |
|
323 | + } |
|
324 | + |
|
325 | + public function remoteStorageMounts($storageId) { |
|
326 | + $builder = $this->connection->getQueryBuilder(); |
|
327 | + |
|
328 | + $query = $builder->delete('mounts') |
|
329 | + ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
330 | + $query->execute(); |
|
331 | + } |
|
332 | 332 | } |
@@ -89,11 +89,11 @@ discard block |
||
89 | 89 | |
90 | 90 | public function registerMounts(IUser $user, array $mounts) { |
91 | 91 | // filter out non-proper storages coming from unit tests |
92 | - $mounts = array_filter($mounts, function (IMountPoint $mount) { |
|
92 | + $mounts = array_filter($mounts, function(IMountPoint $mount) { |
|
93 | 93 | return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache(); |
94 | 94 | }); |
95 | 95 | /** @var ICachedMountInfo[] $newMounts */ |
96 | - $newMounts = array_map(function (IMountPoint $mount) use ($user) { |
|
96 | + $newMounts = array_map(function(IMountPoint $mount) use ($user) { |
|
97 | 97 | // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet) |
98 | 98 | if ($mount->getStorageRootId() === -1) { |
99 | 99 | return null; |
@@ -104,7 +104,7 @@ discard block |
||
104 | 104 | $newMounts = array_values(array_filter($newMounts)); |
105 | 105 | |
106 | 106 | $cachedMounts = $this->getMountsForUser($user); |
107 | - $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) { |
|
107 | + $mountDiff = function(ICachedMountInfo $mount1, ICachedMountInfo $mount2) { |
|
108 | 108 | // since we are only looking for mounts for a specific user comparing on root id is enough |
109 | 109 | return $mount1->getRootId() - $mount2->getRootId(); |
110 | 110 | }; |
@@ -165,7 +165,7 @@ discard block |
||
165 | 165 | ], ['root_id', 'user_id']); |
166 | 166 | } else { |
167 | 167 | // in some cases this is legitimate, like orphaned shares |
168 | - $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint()); |
|
168 | + $this->logger->debug('Could not get storage info for mount at '.$mount->getMountPoint()); |
|
169 | 169 | } |
170 | 170 | } |
171 | 171 | |
@@ -196,7 +196,7 @@ discard block |
||
196 | 196 | if (is_null($user)) { |
197 | 197 | return null; |
198 | 198 | } |
199 | - return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path'])? $row['path']:''); |
|
199 | + return new CachedMountInfo($user, (int) $row['storage_id'], (int) $row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : ''); |
|
200 | 200 | } |
201 | 201 | |
202 | 202 | /** |
@@ -226,7 +226,7 @@ discard block |
||
226 | 226 | $builder = $this->connection->getQueryBuilder(); |
227 | 227 | $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
228 | 228 | ->from('mounts', 'm') |
229 | - ->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
229 | + ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
230 | 230 | ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT))); |
231 | 231 | |
232 | 232 | $rows = $query->execute()->fetchAll(); |
@@ -265,12 +265,12 @@ discard block |
||
265 | 265 | $row = $query->execute()->fetch(); |
266 | 266 | if (is_array($row)) { |
267 | 267 | $this->cacheInfoCache[$fileId] = [ |
268 | - (int)$row['storage'], |
|
268 | + (int) $row['storage'], |
|
269 | 269 | $row['path'], |
270 | - (int)$row['mimetype'] |
|
270 | + (int) $row['mimetype'] |
|
271 | 271 | ]; |
272 | 272 | } else { |
273 | - throw new NotFoundException('File with id "' . $fileId . '" not found'); |
|
273 | + throw new NotFoundException('File with id "'.$fileId.'" not found'); |
|
274 | 274 | } |
275 | 275 | } |
276 | 276 | return $this->cacheInfoCache[$fileId]; |
@@ -290,13 +290,13 @@ discard block |
||
290 | 290 | $mountsForStorage = $this->getMountsForStorageId($storageId); |
291 | 291 | |
292 | 292 | // filter mounts that are from the same storage but a different directory |
293 | - return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
293 | + return array_filter($mountsForStorage, function(ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
294 | 294 | if ($fileId === $mount->getRootId()) { |
295 | 295 | return true; |
296 | 296 | } |
297 | 297 | $internalMountPath = $mount->getRootInternalPath(); |
298 | 298 | |
299 | - return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/'; |
|
299 | + return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath.'/'; |
|
300 | 300 | }); |
301 | 301 | } |
302 | 302 |