@@ -671,7 +671,7 @@ discard block |
||
671 | 671 | * if the size limit for the trash bin is reached, we delete the oldest |
672 | 672 | * files in the trash bin until we meet the limit again |
673 | 673 | * |
674 | - * @param array $files |
|
674 | + * @param \OCP\Files\FileInfo[] $files |
|
675 | 675 | * @param string $user |
676 | 676 | * @param int $availableSpace available disc space |
677 | 677 | * @return int size of deleted files |
@@ -699,7 +699,7 @@ discard block |
||
699 | 699 | /** |
700 | 700 | * delete files older then max storage time |
701 | 701 | * |
702 | - * @param array $files list of files sorted by mtime |
|
702 | + * @param \OCP\Files\FileInfo[] $files list of files sorted by mtime |
|
703 | 703 | * @param string $user |
704 | 704 | * @return integer[] size of deleted files and number of deleted files |
705 | 705 | */ |
@@ -52,958 +52,958 @@ |
||
52 | 52 | |
53 | 53 | class Trashbin { |
54 | 54 | |
55 | - // unit: percentage; 50% of available disk space/quota |
|
56 | - const DEFAULTMAXSIZE = 50; |
|
57 | - |
|
58 | - /** |
|
59 | - * Whether versions have already be rescanned during this PHP request |
|
60 | - * |
|
61 | - * @var bool |
|
62 | - */ |
|
63 | - private static $scannedVersions = false; |
|
64 | - |
|
65 | - /** |
|
66 | - * Ensure we don't need to scan the file during the move to trash |
|
67 | - * by triggering the scan in the pre-hook |
|
68 | - * |
|
69 | - * @param array $params |
|
70 | - */ |
|
71 | - public static function ensureFileScannedHook($params) { |
|
72 | - try { |
|
73 | - self::getUidAndFilename($params['path']); |
|
74 | - } catch (NotFoundException $e) { |
|
75 | - // nothing to scan for non existing files |
|
76 | - } |
|
77 | - } |
|
78 | - |
|
79 | - /** |
|
80 | - * get the UID of the owner of the file and the path to the file relative to |
|
81 | - * owners files folder |
|
82 | - * |
|
83 | - * @param string $filename |
|
84 | - * @return array |
|
85 | - * @throws \OC\User\NoUserException |
|
86 | - */ |
|
87 | - public static function getUidAndFilename($filename) { |
|
88 | - $uid = Filesystem::getOwner($filename); |
|
89 | - $userManager = \OC::$server->getUserManager(); |
|
90 | - // if the user with the UID doesn't exists, e.g. because the UID points |
|
91 | - // to a remote user with a federated cloud ID we use the current logged-in |
|
92 | - // user. We need a valid local user to move the file to the right trash bin |
|
93 | - if (!$userManager->userExists($uid)) { |
|
94 | - $uid = User::getUser(); |
|
95 | - } |
|
96 | - if (!$uid) { |
|
97 | - // no owner, usually because of share link from ext storage |
|
98 | - return [null, null]; |
|
99 | - } |
|
100 | - Filesystem::initMountPoints($uid); |
|
101 | - if ($uid !== User::getUser()) { |
|
102 | - $info = Filesystem::getFileInfo($filename); |
|
103 | - $ownerView = new View('/' . $uid . '/files'); |
|
104 | - try { |
|
105 | - $filename = $ownerView->getPath($info['fileid']); |
|
106 | - } catch (NotFoundException $e) { |
|
107 | - $filename = null; |
|
108 | - } |
|
109 | - } |
|
110 | - return [$uid, $filename]; |
|
111 | - } |
|
112 | - |
|
113 | - /** |
|
114 | - * get original location of files for user |
|
115 | - * |
|
116 | - * @param string $user |
|
117 | - * @return array (filename => array (timestamp => original location)) |
|
118 | - */ |
|
119 | - public static function getLocations($user) { |
|
120 | - $query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`' |
|
121 | - . ' FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
122 | - $result = $query->execute(array($user)); |
|
123 | - $array = array(); |
|
124 | - while ($row = $result->fetchRow()) { |
|
125 | - if (isset($array[$row['id']])) { |
|
126 | - $array[$row['id']][$row['timestamp']] = $row['location']; |
|
127 | - } else { |
|
128 | - $array[$row['id']] = array($row['timestamp'] => $row['location']); |
|
129 | - } |
|
130 | - } |
|
131 | - return $array; |
|
132 | - } |
|
133 | - |
|
134 | - /** |
|
135 | - * get original location of file |
|
136 | - * |
|
137 | - * @param string $user |
|
138 | - * @param string $filename |
|
139 | - * @param string $timestamp |
|
140 | - * @return string original location |
|
141 | - */ |
|
142 | - public static function getLocation($user, $filename, $timestamp) { |
|
143 | - $query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`' |
|
144 | - . ' WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
145 | - $result = $query->execute(array($user, $filename, $timestamp))->fetchAll(); |
|
146 | - if (isset($result[0]['location'])) { |
|
147 | - return $result[0]['location']; |
|
148 | - } else { |
|
149 | - return false; |
|
150 | - } |
|
151 | - } |
|
152 | - |
|
153 | - private static function setUpTrash($user) { |
|
154 | - $view = new View('/' . $user); |
|
155 | - if (!$view->is_dir('files_trashbin')) { |
|
156 | - $view->mkdir('files_trashbin'); |
|
157 | - } |
|
158 | - if (!$view->is_dir('files_trashbin/files')) { |
|
159 | - $view->mkdir('files_trashbin/files'); |
|
160 | - } |
|
161 | - if (!$view->is_dir('files_trashbin/versions')) { |
|
162 | - $view->mkdir('files_trashbin/versions'); |
|
163 | - } |
|
164 | - if (!$view->is_dir('files_trashbin/keys')) { |
|
165 | - $view->mkdir('files_trashbin/keys'); |
|
166 | - } |
|
167 | - } |
|
168 | - |
|
169 | - |
|
170 | - /** |
|
171 | - * copy file to owners trash |
|
172 | - * |
|
173 | - * @param string $sourcePath |
|
174 | - * @param string $owner |
|
175 | - * @param string $targetPath |
|
176 | - * @param $user |
|
177 | - * @param integer $timestamp |
|
178 | - */ |
|
179 | - private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) { |
|
180 | - self::setUpTrash($owner); |
|
181 | - |
|
182 | - $targetFilename = basename($targetPath); |
|
183 | - $targetLocation = dirname($targetPath); |
|
184 | - |
|
185 | - $sourceFilename = basename($sourcePath); |
|
186 | - |
|
187 | - $view = new View('/'); |
|
188 | - |
|
189 | - $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp; |
|
190 | - $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp; |
|
191 | - self::copy_recursive($source, $target, $view); |
|
192 | - |
|
193 | - |
|
194 | - if ($view->file_exists($target)) { |
|
195 | - $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)"); |
|
196 | - $result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user)); |
|
197 | - if (!$result) { |
|
198 | - \OC::$server->getLogger()->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']); |
|
199 | - } |
|
200 | - } |
|
201 | - } |
|
202 | - |
|
203 | - |
|
204 | - /** |
|
205 | - * move file to the trash bin |
|
206 | - * |
|
207 | - * @param string $file_path path to the deleted file/directory relative to the files root directory |
|
208 | - * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder) |
|
209 | - * |
|
210 | - * @return bool |
|
211 | - */ |
|
212 | - public static function move2trash($file_path, $ownerOnly = false) { |
|
213 | - // get the user for which the filesystem is setup |
|
214 | - $root = Filesystem::getRoot(); |
|
215 | - list(, $user) = explode('/', $root); |
|
216 | - list($owner, $ownerPath) = self::getUidAndFilename($file_path); |
|
217 | - |
|
218 | - // if no owner found (ex: ext storage + share link), will use the current user's trashbin then |
|
219 | - if (is_null($owner)) { |
|
220 | - $owner = $user; |
|
221 | - $ownerPath = $file_path; |
|
222 | - } |
|
223 | - |
|
224 | - $ownerView = new View('/' . $owner); |
|
225 | - // file has been deleted in between |
|
226 | - if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) { |
|
227 | - return true; |
|
228 | - } |
|
229 | - |
|
230 | - self::setUpTrash($user); |
|
231 | - if ($owner !== $user) { |
|
232 | - // also setup for owner |
|
233 | - self::setUpTrash($owner); |
|
234 | - } |
|
235 | - |
|
236 | - $path_parts = pathinfo($ownerPath); |
|
237 | - |
|
238 | - $filename = $path_parts['basename']; |
|
239 | - $location = $path_parts['dirname']; |
|
240 | - $timestamp = time(); |
|
241 | - |
|
242 | - // disable proxy to prevent recursive calls |
|
243 | - $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp; |
|
244 | - |
|
245 | - /** @var \OC\Files\Storage\Storage $trashStorage */ |
|
246 | - list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath); |
|
247 | - /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
248 | - list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath); |
|
249 | - try { |
|
250 | - $moveSuccessful = true; |
|
251 | - if ($trashStorage->file_exists($trashInternalPath)) { |
|
252 | - $trashStorage->unlink($trashInternalPath); |
|
253 | - } |
|
254 | - $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath); |
|
255 | - } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) { |
|
256 | - $moveSuccessful = false; |
|
257 | - if ($trashStorage->file_exists($trashInternalPath)) { |
|
258 | - $trashStorage->unlink($trashInternalPath); |
|
259 | - } |
|
260 | - \OC::$server->getLogger()->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']); |
|
261 | - } |
|
262 | - |
|
263 | - if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort |
|
264 | - if ($sourceStorage->is_dir($sourceInternalPath)) { |
|
265 | - $sourceStorage->rmdir($sourceInternalPath); |
|
266 | - } else { |
|
267 | - $sourceStorage->unlink($sourceInternalPath); |
|
268 | - } |
|
269 | - return false; |
|
270 | - } |
|
271 | - |
|
272 | - $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath); |
|
273 | - |
|
274 | - if ($moveSuccessful) { |
|
275 | - $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)"); |
|
276 | - $result = $query->execute(array($filename, $timestamp, $location, $owner)); |
|
277 | - if (!$result) { |
|
278 | - \OC::$server->getLogger()->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']); |
|
279 | - } |
|
280 | - \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path), |
|
281 | - 'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp))); |
|
282 | - |
|
283 | - self::retainVersions($filename, $owner, $ownerPath, $timestamp); |
|
284 | - |
|
285 | - // if owner !== user we need to also add a copy to the users trash |
|
286 | - if ($user !== $owner && $ownerOnly === false) { |
|
287 | - self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp); |
|
288 | - } |
|
289 | - } |
|
290 | - |
|
291 | - self::scheduleExpire($user); |
|
292 | - |
|
293 | - // if owner !== user we also need to update the owners trash size |
|
294 | - if ($owner !== $user) { |
|
295 | - self::scheduleExpire($owner); |
|
296 | - } |
|
297 | - |
|
298 | - return $moveSuccessful; |
|
299 | - } |
|
300 | - |
|
301 | - /** |
|
302 | - * Move file versions to trash so that they can be restored later |
|
303 | - * |
|
304 | - * @param string $filename of deleted file |
|
305 | - * @param string $owner owner user id |
|
306 | - * @param string $ownerPath path relative to the owner's home storage |
|
307 | - * @param integer $timestamp when the file was deleted |
|
308 | - */ |
|
309 | - private static function retainVersions($filename, $owner, $ownerPath, $timestamp) { |
|
310 | - if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) { |
|
311 | - |
|
312 | - $user = User::getUser(); |
|
313 | - $rootView = new View('/'); |
|
314 | - |
|
315 | - if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) { |
|
316 | - if ($owner !== $user) { |
|
317 | - self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView); |
|
318 | - } |
|
319 | - self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp); |
|
320 | - } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) { |
|
321 | - |
|
322 | - foreach ($versions as $v) { |
|
323 | - if ($owner !== $user) { |
|
324 | - self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp); |
|
325 | - } |
|
326 | - self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp); |
|
327 | - } |
|
328 | - } |
|
329 | - } |
|
330 | - } |
|
331 | - |
|
332 | - /** |
|
333 | - * Move a file or folder on storage level |
|
334 | - * |
|
335 | - * @param View $view |
|
336 | - * @param string $source |
|
337 | - * @param string $target |
|
338 | - * @return bool |
|
339 | - */ |
|
340 | - private static function move(View $view, $source, $target) { |
|
341 | - /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
342 | - list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); |
|
343 | - /** @var \OC\Files\Storage\Storage $targetStorage */ |
|
344 | - list($targetStorage, $targetInternalPath) = $view->resolvePath($target); |
|
345 | - /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ |
|
346 | - |
|
347 | - $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
348 | - if ($result) { |
|
349 | - $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
350 | - } |
|
351 | - return $result; |
|
352 | - } |
|
353 | - |
|
354 | - /** |
|
355 | - * Copy a file or folder on storage level |
|
356 | - * |
|
357 | - * @param View $view |
|
358 | - * @param string $source |
|
359 | - * @param string $target |
|
360 | - * @return bool |
|
361 | - */ |
|
362 | - private static function copy(View $view, $source, $target) { |
|
363 | - /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
364 | - list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); |
|
365 | - /** @var \OC\Files\Storage\Storage $targetStorage */ |
|
366 | - list($targetStorage, $targetInternalPath) = $view->resolvePath($target); |
|
367 | - /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ |
|
368 | - |
|
369 | - $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
370 | - if ($result) { |
|
371 | - $targetStorage->getUpdater()->update($targetInternalPath); |
|
372 | - } |
|
373 | - return $result; |
|
374 | - } |
|
375 | - |
|
376 | - /** |
|
377 | - * Restore a file or folder from trash bin |
|
378 | - * |
|
379 | - * @param string $file path to the deleted file/folder relative to "files_trashbin/files/", |
|
380 | - * including the timestamp suffix ".d12345678" |
|
381 | - * @param string $filename name of the file/folder |
|
382 | - * @param int $timestamp time when the file/folder was deleted |
|
383 | - * |
|
384 | - * @return bool true on success, false otherwise |
|
385 | - */ |
|
386 | - public static function restore($file, $filename, $timestamp) { |
|
387 | - $user = User::getUser(); |
|
388 | - $view = new View('/' . $user); |
|
389 | - |
|
390 | - $location = ''; |
|
391 | - if ($timestamp) { |
|
392 | - $location = self::getLocation($user, $filename, $timestamp); |
|
393 | - if ($location === false) { |
|
394 | - \OC::$server->getLogger()->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']); |
|
395 | - } else { |
|
396 | - // if location no longer exists, restore file in the root directory |
|
397 | - if ($location !== '/' && |
|
398 | - (!$view->is_dir('files/' . $location) || |
|
399 | - !$view->isCreatable('files/' . $location)) |
|
400 | - ) { |
|
401 | - $location = ''; |
|
402 | - } |
|
403 | - } |
|
404 | - } |
|
405 | - |
|
406 | - // we need a extension in case a file/dir with the same name already exists |
|
407 | - $uniqueFilename = self::getUniqueFilename($location, $filename, $view); |
|
408 | - |
|
409 | - $source = Filesystem::normalizePath('files_trashbin/files/' . $file); |
|
410 | - $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename); |
|
411 | - if (!$view->file_exists($source)) { |
|
412 | - return false; |
|
413 | - } |
|
414 | - $mtime = $view->filemtime($source); |
|
415 | - |
|
416 | - // restore file |
|
417 | - $restoreResult = $view->rename($source, $target); |
|
418 | - |
|
419 | - // handle the restore result |
|
420 | - if ($restoreResult) { |
|
421 | - $fakeRoot = $view->getRoot(); |
|
422 | - $view->chroot('/' . $user . '/files'); |
|
423 | - $view->touch('/' . $location . '/' . $uniqueFilename, $mtime); |
|
424 | - $view->chroot($fakeRoot); |
|
425 | - \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename), |
|
426 | - 'trashPath' => Filesystem::normalizePath($file))); |
|
427 | - |
|
428 | - self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp); |
|
429 | - |
|
430 | - if ($timestamp) { |
|
431 | - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
432 | - $query->execute(array($user, $filename, $timestamp)); |
|
433 | - } |
|
434 | - |
|
435 | - return true; |
|
436 | - } |
|
437 | - |
|
438 | - return false; |
|
439 | - } |
|
440 | - |
|
441 | - /** |
|
442 | - * restore versions from trash bin |
|
443 | - * |
|
444 | - * @param View $view file view |
|
445 | - * @param string $file complete path to file |
|
446 | - * @param string $filename name of file once it was deleted |
|
447 | - * @param string $uniqueFilename new file name to restore the file without overwriting existing files |
|
448 | - * @param string $location location if file |
|
449 | - * @param int $timestamp deletion time |
|
450 | - * @return false|null |
|
451 | - */ |
|
452 | - private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) { |
|
453 | - |
|
454 | - if (\OCP\App::isEnabled('files_versions')) { |
|
455 | - |
|
456 | - $user = User::getUser(); |
|
457 | - $rootView = new View('/'); |
|
458 | - |
|
459 | - $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename); |
|
460 | - |
|
461 | - list($owner, $ownerPath) = self::getUidAndFilename($target); |
|
462 | - |
|
463 | - // file has been deleted in between |
|
464 | - if (empty($ownerPath)) { |
|
465 | - return false; |
|
466 | - } |
|
467 | - |
|
468 | - if ($timestamp) { |
|
469 | - $versionedFile = $filename; |
|
470 | - } else { |
|
471 | - $versionedFile = $file; |
|
472 | - } |
|
473 | - |
|
474 | - if ($view->is_dir('/files_trashbin/versions/' . $file)) { |
|
475 | - $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath)); |
|
476 | - } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) { |
|
477 | - foreach ($versions as $v) { |
|
478 | - if ($timestamp) { |
|
479 | - $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
480 | - } else { |
|
481 | - $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
482 | - } |
|
483 | - } |
|
484 | - } |
|
485 | - } |
|
486 | - } |
|
487 | - |
|
488 | - /** |
|
489 | - * delete all files from the trash |
|
490 | - */ |
|
491 | - public static function deleteAll() { |
|
492 | - $user = User::getUser(); |
|
493 | - $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
|
494 | - $view = new View('/' . $user); |
|
495 | - $fileInfos = $view->getDirectoryContent('files_trashbin/files'); |
|
496 | - |
|
497 | - try { |
|
498 | - $trash = $userRoot->get('files_trashbin'); |
|
499 | - } catch (NotFoundException $e) { |
|
500 | - return false; |
|
501 | - } |
|
502 | - |
|
503 | - // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore) |
|
504 | - $filePaths = array(); |
|
505 | - foreach($fileInfos as $fileInfo){ |
|
506 | - $filePaths[] = $view->getRelativePath($fileInfo->getPath()); |
|
507 | - } |
|
508 | - unset($fileInfos); // save memory |
|
509 | - |
|
510 | - // Bulk PreDelete-Hook |
|
511 | - \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths)); |
|
512 | - |
|
513 | - // Single-File Hooks |
|
514 | - foreach($filePaths as $path){ |
|
515 | - self::emitTrashbinPreDelete($path); |
|
516 | - } |
|
517 | - |
|
518 | - // actual file deletion |
|
519 | - $trash->delete(); |
|
520 | - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
521 | - $query->execute(array($user)); |
|
522 | - |
|
523 | - // Bulk PostDelete-Hook |
|
524 | - \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths)); |
|
525 | - |
|
526 | - // Single-File Hooks |
|
527 | - foreach($filePaths as $path){ |
|
528 | - self::emitTrashbinPostDelete($path); |
|
529 | - } |
|
530 | - |
|
531 | - $trash = $userRoot->newFolder('files_trashbin'); |
|
532 | - $trash->newFolder('files'); |
|
533 | - |
|
534 | - return true; |
|
535 | - } |
|
536 | - |
|
537 | - /** |
|
538 | - * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted |
|
539 | - * @param string $path |
|
540 | - */ |
|
541 | - protected static function emitTrashbinPreDelete($path){ |
|
542 | - \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path)); |
|
543 | - } |
|
544 | - |
|
545 | - /** |
|
546 | - * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted |
|
547 | - * @param string $path |
|
548 | - */ |
|
549 | - protected static function emitTrashbinPostDelete($path){ |
|
550 | - \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path)); |
|
551 | - } |
|
552 | - |
|
553 | - /** |
|
554 | - * delete file from trash bin permanently |
|
555 | - * |
|
556 | - * @param string $filename path to the file |
|
557 | - * @param string $user |
|
558 | - * @param int $timestamp of deletion time |
|
559 | - * |
|
560 | - * @return int size of deleted files |
|
561 | - */ |
|
562 | - public static function delete($filename, $user, $timestamp = null) { |
|
563 | - $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
|
564 | - $view = new View('/' . $user); |
|
565 | - $size = 0; |
|
566 | - |
|
567 | - if ($timestamp) { |
|
568 | - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
569 | - $query->execute(array($user, $filename, $timestamp)); |
|
570 | - $file = $filename . '.d' . $timestamp; |
|
571 | - } else { |
|
572 | - $file = $filename; |
|
573 | - } |
|
574 | - |
|
575 | - $size += self::deleteVersions($view, $file, $filename, $timestamp, $user); |
|
576 | - |
|
577 | - try { |
|
578 | - $node = $userRoot->get('/files_trashbin/files/' . $file); |
|
579 | - } catch (NotFoundException $e) { |
|
580 | - return $size; |
|
581 | - } |
|
582 | - |
|
583 | - if ($node instanceof Folder) { |
|
584 | - $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file)); |
|
585 | - } else if ($node instanceof File) { |
|
586 | - $size += $view->filesize('/files_trashbin/files/' . $file); |
|
587 | - } |
|
588 | - |
|
589 | - self::emitTrashbinPreDelete('/files_trashbin/files/' . $file); |
|
590 | - $node->delete(); |
|
591 | - self::emitTrashbinPostDelete('/files_trashbin/files/' . $file); |
|
592 | - |
|
593 | - return $size; |
|
594 | - } |
|
595 | - |
|
596 | - /** |
|
597 | - * @param View $view |
|
598 | - * @param string $file |
|
599 | - * @param string $filename |
|
600 | - * @param integer|null $timestamp |
|
601 | - * @param string $user |
|
602 | - * @return int |
|
603 | - */ |
|
604 | - private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) { |
|
605 | - $size = 0; |
|
606 | - if (\OCP\App::isEnabled('files_versions')) { |
|
607 | - if ($view->is_dir('files_trashbin/versions/' . $file)) { |
|
608 | - $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file)); |
|
609 | - $view->unlink('files_trashbin/versions/' . $file); |
|
610 | - } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) { |
|
611 | - foreach ($versions as $v) { |
|
612 | - if ($timestamp) { |
|
613 | - $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
614 | - $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
615 | - } else { |
|
616 | - $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
617 | - $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
618 | - } |
|
619 | - } |
|
620 | - } |
|
621 | - } |
|
622 | - return $size; |
|
623 | - } |
|
624 | - |
|
625 | - /** |
|
626 | - * check to see whether a file exists in trashbin |
|
627 | - * |
|
628 | - * @param string $filename path to the file |
|
629 | - * @param int $timestamp of deletion time |
|
630 | - * @return bool true if file exists, otherwise false |
|
631 | - */ |
|
632 | - public static function file_exists($filename, $timestamp = null) { |
|
633 | - $user = User::getUser(); |
|
634 | - $view = new View('/' . $user); |
|
635 | - |
|
636 | - if ($timestamp) { |
|
637 | - $filename = $filename . '.d' . $timestamp; |
|
638 | - } |
|
639 | - |
|
640 | - $target = Filesystem::normalizePath('files_trashbin/files/' . $filename); |
|
641 | - return $view->file_exists($target); |
|
642 | - } |
|
643 | - |
|
644 | - /** |
|
645 | - * deletes used space for trash bin in db if user was deleted |
|
646 | - * |
|
647 | - * @param string $uid id of deleted user |
|
648 | - * @return bool result of db delete operation |
|
649 | - */ |
|
650 | - public static function deleteUser($uid) { |
|
651 | - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
652 | - return $query->execute(array($uid)); |
|
653 | - } |
|
654 | - |
|
655 | - /** |
|
656 | - * calculate remaining free space for trash bin |
|
657 | - * |
|
658 | - * @param integer $trashbinSize current size of the trash bin |
|
659 | - * @param string $user |
|
660 | - * @return int available free space for trash bin |
|
661 | - */ |
|
662 | - private static function calculateFreeSpace($trashbinSize, $user) { |
|
663 | - $softQuota = true; |
|
664 | - $userObject = \OC::$server->getUserManager()->get($user); |
|
665 | - if(is_null($userObject)) { |
|
666 | - return 0; |
|
667 | - } |
|
668 | - $quota = $userObject->getQuota(); |
|
669 | - if ($quota === null || $quota === 'none') { |
|
670 | - $quota = Filesystem::free_space('/'); |
|
671 | - $softQuota = false; |
|
672 | - // inf or unknown free space |
|
673 | - if ($quota < 0) { |
|
674 | - $quota = PHP_INT_MAX; |
|
675 | - } |
|
676 | - } else { |
|
677 | - $quota = \OCP\Util::computerFileSize($quota); |
|
678 | - } |
|
679 | - |
|
680 | - // calculate available space for trash bin |
|
681 | - // subtract size of files and current trash bin size from quota |
|
682 | - if ($softQuota) { |
|
683 | - $userFolder = \OC::$server->getUserFolder($user); |
|
684 | - if(is_null($userFolder)) { |
|
685 | - return 0; |
|
686 | - } |
|
687 | - $free = $quota - $userFolder->getSize(); // remaining free space for user |
|
688 | - if ($free > 0) { |
|
689 | - $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions |
|
690 | - } else { |
|
691 | - $availableSpace = $free - $trashbinSize; |
|
692 | - } |
|
693 | - } else { |
|
694 | - $availableSpace = $quota; |
|
695 | - } |
|
696 | - |
|
697 | - return $availableSpace; |
|
698 | - } |
|
699 | - |
|
700 | - /** |
|
701 | - * resize trash bin if necessary after a new file was added to Nextcloud |
|
702 | - * |
|
703 | - * @param string $user user id |
|
704 | - */ |
|
705 | - public static function resizeTrash($user) { |
|
706 | - |
|
707 | - $size = self::getTrashbinSize($user); |
|
708 | - |
|
709 | - $freeSpace = self::calculateFreeSpace($size, $user); |
|
710 | - |
|
711 | - if ($freeSpace < 0) { |
|
712 | - self::scheduleExpire($user); |
|
713 | - } |
|
714 | - } |
|
715 | - |
|
716 | - /** |
|
717 | - * clean up the trash bin |
|
718 | - * |
|
719 | - * @param string $user |
|
720 | - */ |
|
721 | - public static function expire($user) { |
|
722 | - $trashBinSize = self::getTrashbinSize($user); |
|
723 | - $availableSpace = self::calculateFreeSpace($trashBinSize, $user); |
|
724 | - |
|
725 | - $dirContent = Helper::getTrashFiles('/', $user, 'mtime'); |
|
726 | - |
|
727 | - // delete all files older then $retention_obligation |
|
728 | - list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user); |
|
729 | - |
|
730 | - $availableSpace += $delSize; |
|
731 | - |
|
732 | - // delete files from trash until we meet the trash bin size limit again |
|
733 | - self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace); |
|
734 | - } |
|
735 | - |
|
736 | - /** |
|
737 | - * @param string $user |
|
738 | - */ |
|
739 | - private static function scheduleExpire($user) { |
|
740 | - // let the admin disable auto expire |
|
741 | - $application = new Application(); |
|
742 | - $expiration = $application->getContainer()->query('Expiration'); |
|
743 | - if ($expiration->isEnabled()) { |
|
744 | - \OC::$server->getCommandBus()->push(new Expire($user)); |
|
745 | - } |
|
746 | - } |
|
747 | - |
|
748 | - /** |
|
749 | - * if the size limit for the trash bin is reached, we delete the oldest |
|
750 | - * files in the trash bin until we meet the limit again |
|
751 | - * |
|
752 | - * @param array $files |
|
753 | - * @param string $user |
|
754 | - * @param int $availableSpace available disc space |
|
755 | - * @return int size of deleted files |
|
756 | - */ |
|
757 | - protected static function deleteFiles($files, $user, $availableSpace) { |
|
758 | - $application = new Application(); |
|
759 | - $expiration = $application->getContainer()->query('Expiration'); |
|
760 | - $size = 0; |
|
761 | - |
|
762 | - if ($availableSpace < 0) { |
|
763 | - foreach ($files as $file) { |
|
764 | - if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) { |
|
765 | - $tmp = self::delete($file['name'], $user, $file['mtime']); |
|
766 | - \OC::$server->getLogger()->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']); |
|
767 | - $availableSpace += $tmp; |
|
768 | - $size += $tmp; |
|
769 | - } else { |
|
770 | - break; |
|
771 | - } |
|
772 | - } |
|
773 | - } |
|
774 | - return $size; |
|
775 | - } |
|
776 | - |
|
777 | - /** |
|
778 | - * delete files older then max storage time |
|
779 | - * |
|
780 | - * @param array $files list of files sorted by mtime |
|
781 | - * @param string $user |
|
782 | - * @return integer[] size of deleted files and number of deleted files |
|
783 | - */ |
|
784 | - public static function deleteExpiredFiles($files, $user) { |
|
785 | - $application = new Application(); |
|
786 | - $expiration = $application->getContainer()->query('Expiration'); |
|
787 | - $size = 0; |
|
788 | - $count = 0; |
|
789 | - foreach ($files as $file) { |
|
790 | - $timestamp = $file['mtime']; |
|
791 | - $filename = $file['name']; |
|
792 | - if ($expiration->isExpired($timestamp)) { |
|
793 | - try { |
|
794 | - $size += self::delete($filename, $user, $timestamp); |
|
795 | - $count++; |
|
796 | - } catch (\OCP\Files\NotPermittedException $e) { |
|
797 | - \OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']); |
|
798 | - } |
|
799 | - \OC::$server->getLogger()->info( |
|
800 | - 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.', |
|
801 | - ['app' => 'files_trashbin'] |
|
802 | - ); |
|
803 | - } else { |
|
804 | - break; |
|
805 | - } |
|
806 | - } |
|
807 | - |
|
808 | - return array($size, $count); |
|
809 | - } |
|
810 | - |
|
811 | - /** |
|
812 | - * recursive copy to copy a whole directory |
|
813 | - * |
|
814 | - * @param string $source source path, relative to the users files directory |
|
815 | - * @param string $destination destination path relative to the users root directoy |
|
816 | - * @param View $view file view for the users root directory |
|
817 | - * @return int |
|
818 | - * @throws Exceptions\CopyRecursiveException |
|
819 | - */ |
|
820 | - private static function copy_recursive($source, $destination, View $view) { |
|
821 | - $size = 0; |
|
822 | - if ($view->is_dir($source)) { |
|
823 | - $view->mkdir($destination); |
|
824 | - $view->touch($destination, $view->filemtime($source)); |
|
825 | - foreach ($view->getDirectoryContent($source) as $i) { |
|
826 | - $pathDir = $source . '/' . $i['name']; |
|
827 | - if ($view->is_dir($pathDir)) { |
|
828 | - $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view); |
|
829 | - } else { |
|
830 | - $size += $view->filesize($pathDir); |
|
831 | - $result = $view->copy($pathDir, $destination . '/' . $i['name']); |
|
832 | - if (!$result) { |
|
833 | - throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
|
834 | - } |
|
835 | - $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir)); |
|
836 | - } |
|
837 | - } |
|
838 | - } else { |
|
839 | - $size += $view->filesize($source); |
|
840 | - $result = $view->copy($source, $destination); |
|
841 | - if (!$result) { |
|
842 | - throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
|
843 | - } |
|
844 | - $view->touch($destination, $view->filemtime($source)); |
|
845 | - } |
|
846 | - return $size; |
|
847 | - } |
|
848 | - |
|
849 | - /** |
|
850 | - * find all versions which belong to the file we want to restore |
|
851 | - * |
|
852 | - * @param string $filename name of the file which should be restored |
|
853 | - * @param int $timestamp timestamp when the file was deleted |
|
854 | - * @return array |
|
855 | - */ |
|
856 | - private static function getVersionsFromTrash($filename, $timestamp, $user) { |
|
857 | - $view = new View('/' . $user . '/files_trashbin/versions'); |
|
858 | - $versions = array(); |
|
859 | - |
|
860 | - //force rescan of versions, local storage may not have updated the cache |
|
861 | - if (!self::$scannedVersions) { |
|
862 | - /** @var \OC\Files\Storage\Storage $storage */ |
|
863 | - list($storage,) = $view->resolvePath('/'); |
|
864 | - $storage->getScanner()->scan('files_trashbin/versions'); |
|
865 | - self::$scannedVersions = true; |
|
866 | - } |
|
867 | - |
|
868 | - if ($timestamp) { |
|
869 | - // fetch for old versions |
|
870 | - $matches = $view->searchRaw($filename . '.v%.d' . $timestamp); |
|
871 | - $offset = -strlen($timestamp) - 2; |
|
872 | - } else { |
|
873 | - $matches = $view->searchRaw($filename . '.v%'); |
|
874 | - } |
|
875 | - |
|
876 | - if (is_array($matches)) { |
|
877 | - foreach ($matches as $ma) { |
|
878 | - if ($timestamp) { |
|
879 | - $parts = explode('.v', substr($ma['path'], 0, $offset)); |
|
880 | - $versions[] = end($parts); |
|
881 | - } else { |
|
882 | - $parts = explode('.v', $ma); |
|
883 | - $versions[] = end($parts); |
|
884 | - } |
|
885 | - } |
|
886 | - } |
|
887 | - return $versions; |
|
888 | - } |
|
889 | - |
|
890 | - /** |
|
891 | - * find unique extension for restored file if a file with the same name already exists |
|
892 | - * |
|
893 | - * @param string $location where the file should be restored |
|
894 | - * @param string $filename name of the file |
|
895 | - * @param View $view filesystem view relative to users root directory |
|
896 | - * @return string with unique extension |
|
897 | - */ |
|
898 | - private static function getUniqueFilename($location, $filename, View $view) { |
|
899 | - $ext = pathinfo($filename, PATHINFO_EXTENSION); |
|
900 | - $name = pathinfo($filename, PATHINFO_FILENAME); |
|
901 | - $l = \OC::$server->getL10N('files_trashbin'); |
|
902 | - |
|
903 | - $location = '/' . trim($location, '/'); |
|
904 | - |
|
905 | - // if extension is not empty we set a dot in front of it |
|
906 | - if ($ext !== '') { |
|
907 | - $ext = '.' . $ext; |
|
908 | - } |
|
909 | - |
|
910 | - if ($view->file_exists('files' . $location . '/' . $filename)) { |
|
911 | - $i = 2; |
|
912 | - $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext; |
|
913 | - while ($view->file_exists('files' . $location . '/' . $uniqueName)) { |
|
914 | - $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext; |
|
915 | - $i++; |
|
916 | - } |
|
917 | - |
|
918 | - return $uniqueName; |
|
919 | - } |
|
920 | - |
|
921 | - return $filename; |
|
922 | - } |
|
923 | - |
|
924 | - /** |
|
925 | - * get the size from a given root folder |
|
926 | - * |
|
927 | - * @param View $view file view on the root folder |
|
928 | - * @return integer size of the folder |
|
929 | - */ |
|
930 | - private static function calculateSize($view) { |
|
931 | - $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath(''); |
|
932 | - if (!file_exists($root)) { |
|
933 | - return 0; |
|
934 | - } |
|
935 | - $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST); |
|
936 | - $size = 0; |
|
937 | - |
|
938 | - /** |
|
939 | - * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach |
|
940 | - * This bug is fixed in PHP 5.5.9 or before |
|
941 | - * See #8376 |
|
942 | - */ |
|
943 | - $iterator->rewind(); |
|
944 | - while ($iterator->valid()) { |
|
945 | - $path = $iterator->current(); |
|
946 | - $relpath = substr($path, strlen($root) - 1); |
|
947 | - if (!$view->is_dir($relpath)) { |
|
948 | - $size += $view->filesize($relpath); |
|
949 | - } |
|
950 | - $iterator->next(); |
|
951 | - } |
|
952 | - return $size; |
|
953 | - } |
|
954 | - |
|
955 | - /** |
|
956 | - * get current size of trash bin from a given user |
|
957 | - * |
|
958 | - * @param string $user user who owns the trash bin |
|
959 | - * @return integer trash bin size |
|
960 | - */ |
|
961 | - private static function getTrashbinSize($user) { |
|
962 | - $view = new View('/' . $user); |
|
963 | - $fileInfo = $view->getFileInfo('/files_trashbin'); |
|
964 | - return isset($fileInfo['size']) ? $fileInfo['size'] : 0; |
|
965 | - } |
|
966 | - |
|
967 | - /** |
|
968 | - * register hooks |
|
969 | - */ |
|
970 | - public static function registerHooks() { |
|
971 | - // create storage wrapper on setup |
|
972 | - \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage'); |
|
973 | - //Listen to delete user signal |
|
974 | - \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook'); |
|
975 | - //Listen to post write hook |
|
976 | - \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook'); |
|
977 | - // pre and post-rename, disable trash logic for the copy+unlink case |
|
978 | - \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook'); |
|
979 | - \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook'); |
|
980 | - \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook'); |
|
981 | - } |
|
982 | - |
|
983 | - /** |
|
984 | - * check if trash bin is empty for a given user |
|
985 | - * |
|
986 | - * @param string $user |
|
987 | - * @return bool |
|
988 | - */ |
|
989 | - public static function isEmpty($user) { |
|
990 | - |
|
991 | - $view = new View('/' . $user . '/files_trashbin'); |
|
992 | - if ($view->is_dir('/files') && $dh = $view->opendir('/files')) { |
|
993 | - while ($file = readdir($dh)) { |
|
994 | - if (!Filesystem::isIgnoredDir($file)) { |
|
995 | - return false; |
|
996 | - } |
|
997 | - } |
|
998 | - } |
|
999 | - return true; |
|
1000 | - } |
|
1001 | - |
|
1002 | - /** |
|
1003 | - * @param $path |
|
1004 | - * @return string |
|
1005 | - */ |
|
1006 | - public static function preview_icon($path) { |
|
1007 | - return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path)); |
|
1008 | - } |
|
55 | + // unit: percentage; 50% of available disk space/quota |
|
56 | + const DEFAULTMAXSIZE = 50; |
|
57 | + |
|
58 | + /** |
|
59 | + * Whether versions have already be rescanned during this PHP request |
|
60 | + * |
|
61 | + * @var bool |
|
62 | + */ |
|
63 | + private static $scannedVersions = false; |
|
64 | + |
|
65 | + /** |
|
66 | + * Ensure we don't need to scan the file during the move to trash |
|
67 | + * by triggering the scan in the pre-hook |
|
68 | + * |
|
69 | + * @param array $params |
|
70 | + */ |
|
71 | + public static function ensureFileScannedHook($params) { |
|
72 | + try { |
|
73 | + self::getUidAndFilename($params['path']); |
|
74 | + } catch (NotFoundException $e) { |
|
75 | + // nothing to scan for non existing files |
|
76 | + } |
|
77 | + } |
|
78 | + |
|
79 | + /** |
|
80 | + * get the UID of the owner of the file and the path to the file relative to |
|
81 | + * owners files folder |
|
82 | + * |
|
83 | + * @param string $filename |
|
84 | + * @return array |
|
85 | + * @throws \OC\User\NoUserException |
|
86 | + */ |
|
87 | + public static function getUidAndFilename($filename) { |
|
88 | + $uid = Filesystem::getOwner($filename); |
|
89 | + $userManager = \OC::$server->getUserManager(); |
|
90 | + // if the user with the UID doesn't exists, e.g. because the UID points |
|
91 | + // to a remote user with a federated cloud ID we use the current logged-in |
|
92 | + // user. We need a valid local user to move the file to the right trash bin |
|
93 | + if (!$userManager->userExists($uid)) { |
|
94 | + $uid = User::getUser(); |
|
95 | + } |
|
96 | + if (!$uid) { |
|
97 | + // no owner, usually because of share link from ext storage |
|
98 | + return [null, null]; |
|
99 | + } |
|
100 | + Filesystem::initMountPoints($uid); |
|
101 | + if ($uid !== User::getUser()) { |
|
102 | + $info = Filesystem::getFileInfo($filename); |
|
103 | + $ownerView = new View('/' . $uid . '/files'); |
|
104 | + try { |
|
105 | + $filename = $ownerView->getPath($info['fileid']); |
|
106 | + } catch (NotFoundException $e) { |
|
107 | + $filename = null; |
|
108 | + } |
|
109 | + } |
|
110 | + return [$uid, $filename]; |
|
111 | + } |
|
112 | + |
|
113 | + /** |
|
114 | + * get original location of files for user |
|
115 | + * |
|
116 | + * @param string $user |
|
117 | + * @return array (filename => array (timestamp => original location)) |
|
118 | + */ |
|
119 | + public static function getLocations($user) { |
|
120 | + $query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`' |
|
121 | + . ' FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
122 | + $result = $query->execute(array($user)); |
|
123 | + $array = array(); |
|
124 | + while ($row = $result->fetchRow()) { |
|
125 | + if (isset($array[$row['id']])) { |
|
126 | + $array[$row['id']][$row['timestamp']] = $row['location']; |
|
127 | + } else { |
|
128 | + $array[$row['id']] = array($row['timestamp'] => $row['location']); |
|
129 | + } |
|
130 | + } |
|
131 | + return $array; |
|
132 | + } |
|
133 | + |
|
134 | + /** |
|
135 | + * get original location of file |
|
136 | + * |
|
137 | + * @param string $user |
|
138 | + * @param string $filename |
|
139 | + * @param string $timestamp |
|
140 | + * @return string original location |
|
141 | + */ |
|
142 | + public static function getLocation($user, $filename, $timestamp) { |
|
143 | + $query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`' |
|
144 | + . ' WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
145 | + $result = $query->execute(array($user, $filename, $timestamp))->fetchAll(); |
|
146 | + if (isset($result[0]['location'])) { |
|
147 | + return $result[0]['location']; |
|
148 | + } else { |
|
149 | + return false; |
|
150 | + } |
|
151 | + } |
|
152 | + |
|
153 | + private static function setUpTrash($user) { |
|
154 | + $view = new View('/' . $user); |
|
155 | + if (!$view->is_dir('files_trashbin')) { |
|
156 | + $view->mkdir('files_trashbin'); |
|
157 | + } |
|
158 | + if (!$view->is_dir('files_trashbin/files')) { |
|
159 | + $view->mkdir('files_trashbin/files'); |
|
160 | + } |
|
161 | + if (!$view->is_dir('files_trashbin/versions')) { |
|
162 | + $view->mkdir('files_trashbin/versions'); |
|
163 | + } |
|
164 | + if (!$view->is_dir('files_trashbin/keys')) { |
|
165 | + $view->mkdir('files_trashbin/keys'); |
|
166 | + } |
|
167 | + } |
|
168 | + |
|
169 | + |
|
170 | + /** |
|
171 | + * copy file to owners trash |
|
172 | + * |
|
173 | + * @param string $sourcePath |
|
174 | + * @param string $owner |
|
175 | + * @param string $targetPath |
|
176 | + * @param $user |
|
177 | + * @param integer $timestamp |
|
178 | + */ |
|
179 | + private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) { |
|
180 | + self::setUpTrash($owner); |
|
181 | + |
|
182 | + $targetFilename = basename($targetPath); |
|
183 | + $targetLocation = dirname($targetPath); |
|
184 | + |
|
185 | + $sourceFilename = basename($sourcePath); |
|
186 | + |
|
187 | + $view = new View('/'); |
|
188 | + |
|
189 | + $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp; |
|
190 | + $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp; |
|
191 | + self::copy_recursive($source, $target, $view); |
|
192 | + |
|
193 | + |
|
194 | + if ($view->file_exists($target)) { |
|
195 | + $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)"); |
|
196 | + $result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user)); |
|
197 | + if (!$result) { |
|
198 | + \OC::$server->getLogger()->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']); |
|
199 | + } |
|
200 | + } |
|
201 | + } |
|
202 | + |
|
203 | + |
|
204 | + /** |
|
205 | + * move file to the trash bin |
|
206 | + * |
|
207 | + * @param string $file_path path to the deleted file/directory relative to the files root directory |
|
208 | + * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder) |
|
209 | + * |
|
210 | + * @return bool |
|
211 | + */ |
|
212 | + public static function move2trash($file_path, $ownerOnly = false) { |
|
213 | + // get the user for which the filesystem is setup |
|
214 | + $root = Filesystem::getRoot(); |
|
215 | + list(, $user) = explode('/', $root); |
|
216 | + list($owner, $ownerPath) = self::getUidAndFilename($file_path); |
|
217 | + |
|
218 | + // if no owner found (ex: ext storage + share link), will use the current user's trashbin then |
|
219 | + if (is_null($owner)) { |
|
220 | + $owner = $user; |
|
221 | + $ownerPath = $file_path; |
|
222 | + } |
|
223 | + |
|
224 | + $ownerView = new View('/' . $owner); |
|
225 | + // file has been deleted in between |
|
226 | + if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) { |
|
227 | + return true; |
|
228 | + } |
|
229 | + |
|
230 | + self::setUpTrash($user); |
|
231 | + if ($owner !== $user) { |
|
232 | + // also setup for owner |
|
233 | + self::setUpTrash($owner); |
|
234 | + } |
|
235 | + |
|
236 | + $path_parts = pathinfo($ownerPath); |
|
237 | + |
|
238 | + $filename = $path_parts['basename']; |
|
239 | + $location = $path_parts['dirname']; |
|
240 | + $timestamp = time(); |
|
241 | + |
|
242 | + // disable proxy to prevent recursive calls |
|
243 | + $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp; |
|
244 | + |
|
245 | + /** @var \OC\Files\Storage\Storage $trashStorage */ |
|
246 | + list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath); |
|
247 | + /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
248 | + list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath); |
|
249 | + try { |
|
250 | + $moveSuccessful = true; |
|
251 | + if ($trashStorage->file_exists($trashInternalPath)) { |
|
252 | + $trashStorage->unlink($trashInternalPath); |
|
253 | + } |
|
254 | + $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath); |
|
255 | + } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) { |
|
256 | + $moveSuccessful = false; |
|
257 | + if ($trashStorage->file_exists($trashInternalPath)) { |
|
258 | + $trashStorage->unlink($trashInternalPath); |
|
259 | + } |
|
260 | + \OC::$server->getLogger()->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']); |
|
261 | + } |
|
262 | + |
|
263 | + if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort |
|
264 | + if ($sourceStorage->is_dir($sourceInternalPath)) { |
|
265 | + $sourceStorage->rmdir($sourceInternalPath); |
|
266 | + } else { |
|
267 | + $sourceStorage->unlink($sourceInternalPath); |
|
268 | + } |
|
269 | + return false; |
|
270 | + } |
|
271 | + |
|
272 | + $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath); |
|
273 | + |
|
274 | + if ($moveSuccessful) { |
|
275 | + $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)"); |
|
276 | + $result = $query->execute(array($filename, $timestamp, $location, $owner)); |
|
277 | + if (!$result) { |
|
278 | + \OC::$server->getLogger()->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']); |
|
279 | + } |
|
280 | + \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path), |
|
281 | + 'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp))); |
|
282 | + |
|
283 | + self::retainVersions($filename, $owner, $ownerPath, $timestamp); |
|
284 | + |
|
285 | + // if owner !== user we need to also add a copy to the users trash |
|
286 | + if ($user !== $owner && $ownerOnly === false) { |
|
287 | + self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp); |
|
288 | + } |
|
289 | + } |
|
290 | + |
|
291 | + self::scheduleExpire($user); |
|
292 | + |
|
293 | + // if owner !== user we also need to update the owners trash size |
|
294 | + if ($owner !== $user) { |
|
295 | + self::scheduleExpire($owner); |
|
296 | + } |
|
297 | + |
|
298 | + return $moveSuccessful; |
|
299 | + } |
|
300 | + |
|
301 | + /** |
|
302 | + * Move file versions to trash so that they can be restored later |
|
303 | + * |
|
304 | + * @param string $filename of deleted file |
|
305 | + * @param string $owner owner user id |
|
306 | + * @param string $ownerPath path relative to the owner's home storage |
|
307 | + * @param integer $timestamp when the file was deleted |
|
308 | + */ |
|
309 | + private static function retainVersions($filename, $owner, $ownerPath, $timestamp) { |
|
310 | + if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) { |
|
311 | + |
|
312 | + $user = User::getUser(); |
|
313 | + $rootView = new View('/'); |
|
314 | + |
|
315 | + if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) { |
|
316 | + if ($owner !== $user) { |
|
317 | + self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView); |
|
318 | + } |
|
319 | + self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp); |
|
320 | + } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) { |
|
321 | + |
|
322 | + foreach ($versions as $v) { |
|
323 | + if ($owner !== $user) { |
|
324 | + self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp); |
|
325 | + } |
|
326 | + self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp); |
|
327 | + } |
|
328 | + } |
|
329 | + } |
|
330 | + } |
|
331 | + |
|
332 | + /** |
|
333 | + * Move a file or folder on storage level |
|
334 | + * |
|
335 | + * @param View $view |
|
336 | + * @param string $source |
|
337 | + * @param string $target |
|
338 | + * @return bool |
|
339 | + */ |
|
340 | + private static function move(View $view, $source, $target) { |
|
341 | + /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
342 | + list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); |
|
343 | + /** @var \OC\Files\Storage\Storage $targetStorage */ |
|
344 | + list($targetStorage, $targetInternalPath) = $view->resolvePath($target); |
|
345 | + /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ |
|
346 | + |
|
347 | + $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
348 | + if ($result) { |
|
349 | + $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
350 | + } |
|
351 | + return $result; |
|
352 | + } |
|
353 | + |
|
354 | + /** |
|
355 | + * Copy a file or folder on storage level |
|
356 | + * |
|
357 | + * @param View $view |
|
358 | + * @param string $source |
|
359 | + * @param string $target |
|
360 | + * @return bool |
|
361 | + */ |
|
362 | + private static function copy(View $view, $source, $target) { |
|
363 | + /** @var \OC\Files\Storage\Storage $sourceStorage */ |
|
364 | + list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); |
|
365 | + /** @var \OC\Files\Storage\Storage $targetStorage */ |
|
366 | + list($targetStorage, $targetInternalPath) = $view->resolvePath($target); |
|
367 | + /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ |
|
368 | + |
|
369 | + $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); |
|
370 | + if ($result) { |
|
371 | + $targetStorage->getUpdater()->update($targetInternalPath); |
|
372 | + } |
|
373 | + return $result; |
|
374 | + } |
|
375 | + |
|
376 | + /** |
|
377 | + * Restore a file or folder from trash bin |
|
378 | + * |
|
379 | + * @param string $file path to the deleted file/folder relative to "files_trashbin/files/", |
|
380 | + * including the timestamp suffix ".d12345678" |
|
381 | + * @param string $filename name of the file/folder |
|
382 | + * @param int $timestamp time when the file/folder was deleted |
|
383 | + * |
|
384 | + * @return bool true on success, false otherwise |
|
385 | + */ |
|
386 | + public static function restore($file, $filename, $timestamp) { |
|
387 | + $user = User::getUser(); |
|
388 | + $view = new View('/' . $user); |
|
389 | + |
|
390 | + $location = ''; |
|
391 | + if ($timestamp) { |
|
392 | + $location = self::getLocation($user, $filename, $timestamp); |
|
393 | + if ($location === false) { |
|
394 | + \OC::$server->getLogger()->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']); |
|
395 | + } else { |
|
396 | + // if location no longer exists, restore file in the root directory |
|
397 | + if ($location !== '/' && |
|
398 | + (!$view->is_dir('files/' . $location) || |
|
399 | + !$view->isCreatable('files/' . $location)) |
|
400 | + ) { |
|
401 | + $location = ''; |
|
402 | + } |
|
403 | + } |
|
404 | + } |
|
405 | + |
|
406 | + // we need a extension in case a file/dir with the same name already exists |
|
407 | + $uniqueFilename = self::getUniqueFilename($location, $filename, $view); |
|
408 | + |
|
409 | + $source = Filesystem::normalizePath('files_trashbin/files/' . $file); |
|
410 | + $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename); |
|
411 | + if (!$view->file_exists($source)) { |
|
412 | + return false; |
|
413 | + } |
|
414 | + $mtime = $view->filemtime($source); |
|
415 | + |
|
416 | + // restore file |
|
417 | + $restoreResult = $view->rename($source, $target); |
|
418 | + |
|
419 | + // handle the restore result |
|
420 | + if ($restoreResult) { |
|
421 | + $fakeRoot = $view->getRoot(); |
|
422 | + $view->chroot('/' . $user . '/files'); |
|
423 | + $view->touch('/' . $location . '/' . $uniqueFilename, $mtime); |
|
424 | + $view->chroot($fakeRoot); |
|
425 | + \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename), |
|
426 | + 'trashPath' => Filesystem::normalizePath($file))); |
|
427 | + |
|
428 | + self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp); |
|
429 | + |
|
430 | + if ($timestamp) { |
|
431 | + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
432 | + $query->execute(array($user, $filename, $timestamp)); |
|
433 | + } |
|
434 | + |
|
435 | + return true; |
|
436 | + } |
|
437 | + |
|
438 | + return false; |
|
439 | + } |
|
440 | + |
|
441 | + /** |
|
442 | + * restore versions from trash bin |
|
443 | + * |
|
444 | + * @param View $view file view |
|
445 | + * @param string $file complete path to file |
|
446 | + * @param string $filename name of file once it was deleted |
|
447 | + * @param string $uniqueFilename new file name to restore the file without overwriting existing files |
|
448 | + * @param string $location location if file |
|
449 | + * @param int $timestamp deletion time |
|
450 | + * @return false|null |
|
451 | + */ |
|
452 | + private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) { |
|
453 | + |
|
454 | + if (\OCP\App::isEnabled('files_versions')) { |
|
455 | + |
|
456 | + $user = User::getUser(); |
|
457 | + $rootView = new View('/'); |
|
458 | + |
|
459 | + $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename); |
|
460 | + |
|
461 | + list($owner, $ownerPath) = self::getUidAndFilename($target); |
|
462 | + |
|
463 | + // file has been deleted in between |
|
464 | + if (empty($ownerPath)) { |
|
465 | + return false; |
|
466 | + } |
|
467 | + |
|
468 | + if ($timestamp) { |
|
469 | + $versionedFile = $filename; |
|
470 | + } else { |
|
471 | + $versionedFile = $file; |
|
472 | + } |
|
473 | + |
|
474 | + if ($view->is_dir('/files_trashbin/versions/' . $file)) { |
|
475 | + $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath)); |
|
476 | + } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) { |
|
477 | + foreach ($versions as $v) { |
|
478 | + if ($timestamp) { |
|
479 | + $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
480 | + } else { |
|
481 | + $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
482 | + } |
|
483 | + } |
|
484 | + } |
|
485 | + } |
|
486 | + } |
|
487 | + |
|
488 | + /** |
|
489 | + * delete all files from the trash |
|
490 | + */ |
|
491 | + public static function deleteAll() { |
|
492 | + $user = User::getUser(); |
|
493 | + $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
|
494 | + $view = new View('/' . $user); |
|
495 | + $fileInfos = $view->getDirectoryContent('files_trashbin/files'); |
|
496 | + |
|
497 | + try { |
|
498 | + $trash = $userRoot->get('files_trashbin'); |
|
499 | + } catch (NotFoundException $e) { |
|
500 | + return false; |
|
501 | + } |
|
502 | + |
|
503 | + // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore) |
|
504 | + $filePaths = array(); |
|
505 | + foreach($fileInfos as $fileInfo){ |
|
506 | + $filePaths[] = $view->getRelativePath($fileInfo->getPath()); |
|
507 | + } |
|
508 | + unset($fileInfos); // save memory |
|
509 | + |
|
510 | + // Bulk PreDelete-Hook |
|
511 | + \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths)); |
|
512 | + |
|
513 | + // Single-File Hooks |
|
514 | + foreach($filePaths as $path){ |
|
515 | + self::emitTrashbinPreDelete($path); |
|
516 | + } |
|
517 | + |
|
518 | + // actual file deletion |
|
519 | + $trash->delete(); |
|
520 | + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
521 | + $query->execute(array($user)); |
|
522 | + |
|
523 | + // Bulk PostDelete-Hook |
|
524 | + \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths)); |
|
525 | + |
|
526 | + // Single-File Hooks |
|
527 | + foreach($filePaths as $path){ |
|
528 | + self::emitTrashbinPostDelete($path); |
|
529 | + } |
|
530 | + |
|
531 | + $trash = $userRoot->newFolder('files_trashbin'); |
|
532 | + $trash->newFolder('files'); |
|
533 | + |
|
534 | + return true; |
|
535 | + } |
|
536 | + |
|
537 | + /** |
|
538 | + * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted |
|
539 | + * @param string $path |
|
540 | + */ |
|
541 | + protected static function emitTrashbinPreDelete($path){ |
|
542 | + \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path)); |
|
543 | + } |
|
544 | + |
|
545 | + /** |
|
546 | + * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted |
|
547 | + * @param string $path |
|
548 | + */ |
|
549 | + protected static function emitTrashbinPostDelete($path){ |
|
550 | + \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path)); |
|
551 | + } |
|
552 | + |
|
553 | + /** |
|
554 | + * delete file from trash bin permanently |
|
555 | + * |
|
556 | + * @param string $filename path to the file |
|
557 | + * @param string $user |
|
558 | + * @param int $timestamp of deletion time |
|
559 | + * |
|
560 | + * @return int size of deleted files |
|
561 | + */ |
|
562 | + public static function delete($filename, $user, $timestamp = null) { |
|
563 | + $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
|
564 | + $view = new View('/' . $user); |
|
565 | + $size = 0; |
|
566 | + |
|
567 | + if ($timestamp) { |
|
568 | + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
|
569 | + $query->execute(array($user, $filename, $timestamp)); |
|
570 | + $file = $filename . '.d' . $timestamp; |
|
571 | + } else { |
|
572 | + $file = $filename; |
|
573 | + } |
|
574 | + |
|
575 | + $size += self::deleteVersions($view, $file, $filename, $timestamp, $user); |
|
576 | + |
|
577 | + try { |
|
578 | + $node = $userRoot->get('/files_trashbin/files/' . $file); |
|
579 | + } catch (NotFoundException $e) { |
|
580 | + return $size; |
|
581 | + } |
|
582 | + |
|
583 | + if ($node instanceof Folder) { |
|
584 | + $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file)); |
|
585 | + } else if ($node instanceof File) { |
|
586 | + $size += $view->filesize('/files_trashbin/files/' . $file); |
|
587 | + } |
|
588 | + |
|
589 | + self::emitTrashbinPreDelete('/files_trashbin/files/' . $file); |
|
590 | + $node->delete(); |
|
591 | + self::emitTrashbinPostDelete('/files_trashbin/files/' . $file); |
|
592 | + |
|
593 | + return $size; |
|
594 | + } |
|
595 | + |
|
596 | + /** |
|
597 | + * @param View $view |
|
598 | + * @param string $file |
|
599 | + * @param string $filename |
|
600 | + * @param integer|null $timestamp |
|
601 | + * @param string $user |
|
602 | + * @return int |
|
603 | + */ |
|
604 | + private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) { |
|
605 | + $size = 0; |
|
606 | + if (\OCP\App::isEnabled('files_versions')) { |
|
607 | + if ($view->is_dir('files_trashbin/versions/' . $file)) { |
|
608 | + $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file)); |
|
609 | + $view->unlink('files_trashbin/versions/' . $file); |
|
610 | + } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) { |
|
611 | + foreach ($versions as $v) { |
|
612 | + if ($timestamp) { |
|
613 | + $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
614 | + $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
615 | + } else { |
|
616 | + $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
617 | + $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
618 | + } |
|
619 | + } |
|
620 | + } |
|
621 | + } |
|
622 | + return $size; |
|
623 | + } |
|
624 | + |
|
625 | + /** |
|
626 | + * check to see whether a file exists in trashbin |
|
627 | + * |
|
628 | + * @param string $filename path to the file |
|
629 | + * @param int $timestamp of deletion time |
|
630 | + * @return bool true if file exists, otherwise false |
|
631 | + */ |
|
632 | + public static function file_exists($filename, $timestamp = null) { |
|
633 | + $user = User::getUser(); |
|
634 | + $view = new View('/' . $user); |
|
635 | + |
|
636 | + if ($timestamp) { |
|
637 | + $filename = $filename . '.d' . $timestamp; |
|
638 | + } |
|
639 | + |
|
640 | + $target = Filesystem::normalizePath('files_trashbin/files/' . $filename); |
|
641 | + return $view->file_exists($target); |
|
642 | + } |
|
643 | + |
|
644 | + /** |
|
645 | + * deletes used space for trash bin in db if user was deleted |
|
646 | + * |
|
647 | + * @param string $uid id of deleted user |
|
648 | + * @return bool result of db delete operation |
|
649 | + */ |
|
650 | + public static function deleteUser($uid) { |
|
651 | + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?'); |
|
652 | + return $query->execute(array($uid)); |
|
653 | + } |
|
654 | + |
|
655 | + /** |
|
656 | + * calculate remaining free space for trash bin |
|
657 | + * |
|
658 | + * @param integer $trashbinSize current size of the trash bin |
|
659 | + * @param string $user |
|
660 | + * @return int available free space for trash bin |
|
661 | + */ |
|
662 | + private static function calculateFreeSpace($trashbinSize, $user) { |
|
663 | + $softQuota = true; |
|
664 | + $userObject = \OC::$server->getUserManager()->get($user); |
|
665 | + if(is_null($userObject)) { |
|
666 | + return 0; |
|
667 | + } |
|
668 | + $quota = $userObject->getQuota(); |
|
669 | + if ($quota === null || $quota === 'none') { |
|
670 | + $quota = Filesystem::free_space('/'); |
|
671 | + $softQuota = false; |
|
672 | + // inf or unknown free space |
|
673 | + if ($quota < 0) { |
|
674 | + $quota = PHP_INT_MAX; |
|
675 | + } |
|
676 | + } else { |
|
677 | + $quota = \OCP\Util::computerFileSize($quota); |
|
678 | + } |
|
679 | + |
|
680 | + // calculate available space for trash bin |
|
681 | + // subtract size of files and current trash bin size from quota |
|
682 | + if ($softQuota) { |
|
683 | + $userFolder = \OC::$server->getUserFolder($user); |
|
684 | + if(is_null($userFolder)) { |
|
685 | + return 0; |
|
686 | + } |
|
687 | + $free = $quota - $userFolder->getSize(); // remaining free space for user |
|
688 | + if ($free > 0) { |
|
689 | + $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions |
|
690 | + } else { |
|
691 | + $availableSpace = $free - $trashbinSize; |
|
692 | + } |
|
693 | + } else { |
|
694 | + $availableSpace = $quota; |
|
695 | + } |
|
696 | + |
|
697 | + return $availableSpace; |
|
698 | + } |
|
699 | + |
|
700 | + /** |
|
701 | + * resize trash bin if necessary after a new file was added to Nextcloud |
|
702 | + * |
|
703 | + * @param string $user user id |
|
704 | + */ |
|
705 | + public static function resizeTrash($user) { |
|
706 | + |
|
707 | + $size = self::getTrashbinSize($user); |
|
708 | + |
|
709 | + $freeSpace = self::calculateFreeSpace($size, $user); |
|
710 | + |
|
711 | + if ($freeSpace < 0) { |
|
712 | + self::scheduleExpire($user); |
|
713 | + } |
|
714 | + } |
|
715 | + |
|
716 | + /** |
|
717 | + * clean up the trash bin |
|
718 | + * |
|
719 | + * @param string $user |
|
720 | + */ |
|
721 | + public static function expire($user) { |
|
722 | + $trashBinSize = self::getTrashbinSize($user); |
|
723 | + $availableSpace = self::calculateFreeSpace($trashBinSize, $user); |
|
724 | + |
|
725 | + $dirContent = Helper::getTrashFiles('/', $user, 'mtime'); |
|
726 | + |
|
727 | + // delete all files older then $retention_obligation |
|
728 | + list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user); |
|
729 | + |
|
730 | + $availableSpace += $delSize; |
|
731 | + |
|
732 | + // delete files from trash until we meet the trash bin size limit again |
|
733 | + self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace); |
|
734 | + } |
|
735 | + |
|
736 | + /** |
|
737 | + * @param string $user |
|
738 | + */ |
|
739 | + private static function scheduleExpire($user) { |
|
740 | + // let the admin disable auto expire |
|
741 | + $application = new Application(); |
|
742 | + $expiration = $application->getContainer()->query('Expiration'); |
|
743 | + if ($expiration->isEnabled()) { |
|
744 | + \OC::$server->getCommandBus()->push(new Expire($user)); |
|
745 | + } |
|
746 | + } |
|
747 | + |
|
748 | + /** |
|
749 | + * if the size limit for the trash bin is reached, we delete the oldest |
|
750 | + * files in the trash bin until we meet the limit again |
|
751 | + * |
|
752 | + * @param array $files |
|
753 | + * @param string $user |
|
754 | + * @param int $availableSpace available disc space |
|
755 | + * @return int size of deleted files |
|
756 | + */ |
|
757 | + protected static function deleteFiles($files, $user, $availableSpace) { |
|
758 | + $application = new Application(); |
|
759 | + $expiration = $application->getContainer()->query('Expiration'); |
|
760 | + $size = 0; |
|
761 | + |
|
762 | + if ($availableSpace < 0) { |
|
763 | + foreach ($files as $file) { |
|
764 | + if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) { |
|
765 | + $tmp = self::delete($file['name'], $user, $file['mtime']); |
|
766 | + \OC::$server->getLogger()->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']); |
|
767 | + $availableSpace += $tmp; |
|
768 | + $size += $tmp; |
|
769 | + } else { |
|
770 | + break; |
|
771 | + } |
|
772 | + } |
|
773 | + } |
|
774 | + return $size; |
|
775 | + } |
|
776 | + |
|
777 | + /** |
|
778 | + * delete files older then max storage time |
|
779 | + * |
|
780 | + * @param array $files list of files sorted by mtime |
|
781 | + * @param string $user |
|
782 | + * @return integer[] size of deleted files and number of deleted files |
|
783 | + */ |
|
784 | + public static function deleteExpiredFiles($files, $user) { |
|
785 | + $application = new Application(); |
|
786 | + $expiration = $application->getContainer()->query('Expiration'); |
|
787 | + $size = 0; |
|
788 | + $count = 0; |
|
789 | + foreach ($files as $file) { |
|
790 | + $timestamp = $file['mtime']; |
|
791 | + $filename = $file['name']; |
|
792 | + if ($expiration->isExpired($timestamp)) { |
|
793 | + try { |
|
794 | + $size += self::delete($filename, $user, $timestamp); |
|
795 | + $count++; |
|
796 | + } catch (\OCP\Files\NotPermittedException $e) { |
|
797 | + \OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']); |
|
798 | + } |
|
799 | + \OC::$server->getLogger()->info( |
|
800 | + 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.', |
|
801 | + ['app' => 'files_trashbin'] |
|
802 | + ); |
|
803 | + } else { |
|
804 | + break; |
|
805 | + } |
|
806 | + } |
|
807 | + |
|
808 | + return array($size, $count); |
|
809 | + } |
|
810 | + |
|
811 | + /** |
|
812 | + * recursive copy to copy a whole directory |
|
813 | + * |
|
814 | + * @param string $source source path, relative to the users files directory |
|
815 | + * @param string $destination destination path relative to the users root directoy |
|
816 | + * @param View $view file view for the users root directory |
|
817 | + * @return int |
|
818 | + * @throws Exceptions\CopyRecursiveException |
|
819 | + */ |
|
820 | + private static function copy_recursive($source, $destination, View $view) { |
|
821 | + $size = 0; |
|
822 | + if ($view->is_dir($source)) { |
|
823 | + $view->mkdir($destination); |
|
824 | + $view->touch($destination, $view->filemtime($source)); |
|
825 | + foreach ($view->getDirectoryContent($source) as $i) { |
|
826 | + $pathDir = $source . '/' . $i['name']; |
|
827 | + if ($view->is_dir($pathDir)) { |
|
828 | + $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view); |
|
829 | + } else { |
|
830 | + $size += $view->filesize($pathDir); |
|
831 | + $result = $view->copy($pathDir, $destination . '/' . $i['name']); |
|
832 | + if (!$result) { |
|
833 | + throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
|
834 | + } |
|
835 | + $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir)); |
|
836 | + } |
|
837 | + } |
|
838 | + } else { |
|
839 | + $size += $view->filesize($source); |
|
840 | + $result = $view->copy($source, $destination); |
|
841 | + if (!$result) { |
|
842 | + throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
|
843 | + } |
|
844 | + $view->touch($destination, $view->filemtime($source)); |
|
845 | + } |
|
846 | + return $size; |
|
847 | + } |
|
848 | + |
|
849 | + /** |
|
850 | + * find all versions which belong to the file we want to restore |
|
851 | + * |
|
852 | + * @param string $filename name of the file which should be restored |
|
853 | + * @param int $timestamp timestamp when the file was deleted |
|
854 | + * @return array |
|
855 | + */ |
|
856 | + private static function getVersionsFromTrash($filename, $timestamp, $user) { |
|
857 | + $view = new View('/' . $user . '/files_trashbin/versions'); |
|
858 | + $versions = array(); |
|
859 | + |
|
860 | + //force rescan of versions, local storage may not have updated the cache |
|
861 | + if (!self::$scannedVersions) { |
|
862 | + /** @var \OC\Files\Storage\Storage $storage */ |
|
863 | + list($storage,) = $view->resolvePath('/'); |
|
864 | + $storage->getScanner()->scan('files_trashbin/versions'); |
|
865 | + self::$scannedVersions = true; |
|
866 | + } |
|
867 | + |
|
868 | + if ($timestamp) { |
|
869 | + // fetch for old versions |
|
870 | + $matches = $view->searchRaw($filename . '.v%.d' . $timestamp); |
|
871 | + $offset = -strlen($timestamp) - 2; |
|
872 | + } else { |
|
873 | + $matches = $view->searchRaw($filename . '.v%'); |
|
874 | + } |
|
875 | + |
|
876 | + if (is_array($matches)) { |
|
877 | + foreach ($matches as $ma) { |
|
878 | + if ($timestamp) { |
|
879 | + $parts = explode('.v', substr($ma['path'], 0, $offset)); |
|
880 | + $versions[] = end($parts); |
|
881 | + } else { |
|
882 | + $parts = explode('.v', $ma); |
|
883 | + $versions[] = end($parts); |
|
884 | + } |
|
885 | + } |
|
886 | + } |
|
887 | + return $versions; |
|
888 | + } |
|
889 | + |
|
890 | + /** |
|
891 | + * find unique extension for restored file if a file with the same name already exists |
|
892 | + * |
|
893 | + * @param string $location where the file should be restored |
|
894 | + * @param string $filename name of the file |
|
895 | + * @param View $view filesystem view relative to users root directory |
|
896 | + * @return string with unique extension |
|
897 | + */ |
|
898 | + private static function getUniqueFilename($location, $filename, View $view) { |
|
899 | + $ext = pathinfo($filename, PATHINFO_EXTENSION); |
|
900 | + $name = pathinfo($filename, PATHINFO_FILENAME); |
|
901 | + $l = \OC::$server->getL10N('files_trashbin'); |
|
902 | + |
|
903 | + $location = '/' . trim($location, '/'); |
|
904 | + |
|
905 | + // if extension is not empty we set a dot in front of it |
|
906 | + if ($ext !== '') { |
|
907 | + $ext = '.' . $ext; |
|
908 | + } |
|
909 | + |
|
910 | + if ($view->file_exists('files' . $location . '/' . $filename)) { |
|
911 | + $i = 2; |
|
912 | + $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext; |
|
913 | + while ($view->file_exists('files' . $location . '/' . $uniqueName)) { |
|
914 | + $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext; |
|
915 | + $i++; |
|
916 | + } |
|
917 | + |
|
918 | + return $uniqueName; |
|
919 | + } |
|
920 | + |
|
921 | + return $filename; |
|
922 | + } |
|
923 | + |
|
924 | + /** |
|
925 | + * get the size from a given root folder |
|
926 | + * |
|
927 | + * @param View $view file view on the root folder |
|
928 | + * @return integer size of the folder |
|
929 | + */ |
|
930 | + private static function calculateSize($view) { |
|
931 | + $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath(''); |
|
932 | + if (!file_exists($root)) { |
|
933 | + return 0; |
|
934 | + } |
|
935 | + $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST); |
|
936 | + $size = 0; |
|
937 | + |
|
938 | + /** |
|
939 | + * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach |
|
940 | + * This bug is fixed in PHP 5.5.9 or before |
|
941 | + * See #8376 |
|
942 | + */ |
|
943 | + $iterator->rewind(); |
|
944 | + while ($iterator->valid()) { |
|
945 | + $path = $iterator->current(); |
|
946 | + $relpath = substr($path, strlen($root) - 1); |
|
947 | + if (!$view->is_dir($relpath)) { |
|
948 | + $size += $view->filesize($relpath); |
|
949 | + } |
|
950 | + $iterator->next(); |
|
951 | + } |
|
952 | + return $size; |
|
953 | + } |
|
954 | + |
|
955 | + /** |
|
956 | + * get current size of trash bin from a given user |
|
957 | + * |
|
958 | + * @param string $user user who owns the trash bin |
|
959 | + * @return integer trash bin size |
|
960 | + */ |
|
961 | + private static function getTrashbinSize($user) { |
|
962 | + $view = new View('/' . $user); |
|
963 | + $fileInfo = $view->getFileInfo('/files_trashbin'); |
|
964 | + return isset($fileInfo['size']) ? $fileInfo['size'] : 0; |
|
965 | + } |
|
966 | + |
|
967 | + /** |
|
968 | + * register hooks |
|
969 | + */ |
|
970 | + public static function registerHooks() { |
|
971 | + // create storage wrapper on setup |
|
972 | + \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage'); |
|
973 | + //Listen to delete user signal |
|
974 | + \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook'); |
|
975 | + //Listen to post write hook |
|
976 | + \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook'); |
|
977 | + // pre and post-rename, disable trash logic for the copy+unlink case |
|
978 | + \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook'); |
|
979 | + \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook'); |
|
980 | + \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook'); |
|
981 | + } |
|
982 | + |
|
983 | + /** |
|
984 | + * check if trash bin is empty for a given user |
|
985 | + * |
|
986 | + * @param string $user |
|
987 | + * @return bool |
|
988 | + */ |
|
989 | + public static function isEmpty($user) { |
|
990 | + |
|
991 | + $view = new View('/' . $user . '/files_trashbin'); |
|
992 | + if ($view->is_dir('/files') && $dh = $view->opendir('/files')) { |
|
993 | + while ($file = readdir($dh)) { |
|
994 | + if (!Filesystem::isIgnoredDir($file)) { |
|
995 | + return false; |
|
996 | + } |
|
997 | + } |
|
998 | + } |
|
999 | + return true; |
|
1000 | + } |
|
1001 | + |
|
1002 | + /** |
|
1003 | + * @param $path |
|
1004 | + * @return string |
|
1005 | + */ |
|
1006 | + public static function preview_icon($path) { |
|
1007 | + return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path)); |
|
1008 | + } |
|
1009 | 1009 | } |
@@ -100,7 +100,7 @@ discard block |
||
100 | 100 | Filesystem::initMountPoints($uid); |
101 | 101 | if ($uid !== User::getUser()) { |
102 | 102 | $info = Filesystem::getFileInfo($filename); |
103 | - $ownerView = new View('/' . $uid . '/files'); |
|
103 | + $ownerView = new View('/'.$uid.'/files'); |
|
104 | 104 | try { |
105 | 105 | $filename = $ownerView->getPath($info['fileid']); |
106 | 106 | } catch (NotFoundException $e) { |
@@ -151,7 +151,7 @@ discard block |
||
151 | 151 | } |
152 | 152 | |
153 | 153 | private static function setUpTrash($user) { |
154 | - $view = new View('/' . $user); |
|
154 | + $view = new View('/'.$user); |
|
155 | 155 | if (!$view->is_dir('files_trashbin')) { |
156 | 156 | $view->mkdir('files_trashbin'); |
157 | 157 | } |
@@ -186,8 +186,8 @@ discard block |
||
186 | 186 | |
187 | 187 | $view = new View('/'); |
188 | 188 | |
189 | - $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp; |
|
190 | - $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp; |
|
189 | + $target = $user.'/files_trashbin/files/'.$targetFilename.'.d'.$timestamp; |
|
190 | + $source = $owner.'/files_trashbin/files/'.$sourceFilename.'.d'.$timestamp; |
|
191 | 191 | self::copy_recursive($source, $target, $view); |
192 | 192 | |
193 | 193 | |
@@ -221,9 +221,9 @@ discard block |
||
221 | 221 | $ownerPath = $file_path; |
222 | 222 | } |
223 | 223 | |
224 | - $ownerView = new View('/' . $owner); |
|
224 | + $ownerView = new View('/'.$owner); |
|
225 | 225 | // file has been deleted in between |
226 | - if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) { |
|
226 | + if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/'.$ownerPath)) { |
|
227 | 227 | return true; |
228 | 228 | } |
229 | 229 | |
@@ -240,12 +240,12 @@ discard block |
||
240 | 240 | $timestamp = time(); |
241 | 241 | |
242 | 242 | // disable proxy to prevent recursive calls |
243 | - $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp; |
|
243 | + $trashPath = '/files_trashbin/files/'.$filename.'.d'.$timestamp; |
|
244 | 244 | |
245 | 245 | /** @var \OC\Files\Storage\Storage $trashStorage */ |
246 | 246 | list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath); |
247 | 247 | /** @var \OC\Files\Storage\Storage $sourceStorage */ |
248 | - list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath); |
|
248 | + list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/'.$ownerPath); |
|
249 | 249 | try { |
250 | 250 | $moveSuccessful = true; |
251 | 251 | if ($trashStorage->file_exists($trashInternalPath)) { |
@@ -257,7 +257,7 @@ discard block |
||
257 | 257 | if ($trashStorage->file_exists($trashInternalPath)) { |
258 | 258 | $trashStorage->unlink($trashInternalPath); |
259 | 259 | } |
260 | - \OC::$server->getLogger()->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']); |
|
260 | + \OC::$server->getLogger()->error('Couldn\'t move '.$file_path.' to the trash bin', ['app' => 'files_trashbin']); |
|
261 | 261 | } |
262 | 262 | |
263 | 263 | if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort |
@@ -278,7 +278,7 @@ discard block |
||
278 | 278 | \OC::$server->getLogger()->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']); |
279 | 279 | } |
280 | 280 | \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path), |
281 | - 'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp))); |
|
281 | + 'trashPath' => Filesystem::normalizePath($filename.'.d'.$timestamp))); |
|
282 | 282 | |
283 | 283 | self::retainVersions($filename, $owner, $ownerPath, $timestamp); |
284 | 284 | |
@@ -312,18 +312,18 @@ discard block |
||
312 | 312 | $user = User::getUser(); |
313 | 313 | $rootView = new View('/'); |
314 | 314 | |
315 | - if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) { |
|
315 | + if ($rootView->is_dir($owner.'/files_versions/'.$ownerPath)) { |
|
316 | 316 | if ($owner !== $user) { |
317 | - self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView); |
|
317 | + self::copy_recursive($owner.'/files_versions/'.$ownerPath, $owner.'/files_trashbin/versions/'.basename($ownerPath).'.d'.$timestamp, $rootView); |
|
318 | 318 | } |
319 | - self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp); |
|
319 | + self::move($rootView, $owner.'/files_versions/'.$ownerPath, $user.'/files_trashbin/versions/'.$filename.'.d'.$timestamp); |
|
320 | 320 | } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) { |
321 | 321 | |
322 | 322 | foreach ($versions as $v) { |
323 | 323 | if ($owner !== $user) { |
324 | - self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp); |
|
324 | + self::copy($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $owner.'/files_trashbin/versions/'.$v['name'].'.v'.$v['version'].'.d'.$timestamp); |
|
325 | 325 | } |
326 | - self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp); |
|
326 | + self::move($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $user.'/files_trashbin/versions/'.$filename.'.v'.$v['version'].'.d'.$timestamp); |
|
327 | 327 | } |
328 | 328 | } |
329 | 329 | } |
@@ -385,18 +385,18 @@ discard block |
||
385 | 385 | */ |
386 | 386 | public static function restore($file, $filename, $timestamp) { |
387 | 387 | $user = User::getUser(); |
388 | - $view = new View('/' . $user); |
|
388 | + $view = new View('/'.$user); |
|
389 | 389 | |
390 | 390 | $location = ''; |
391 | 391 | if ($timestamp) { |
392 | 392 | $location = self::getLocation($user, $filename, $timestamp); |
393 | 393 | if ($location === false) { |
394 | - \OC::$server->getLogger()->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']); |
|
394 | + \OC::$server->getLogger()->error('trash bin database inconsistent! ($user: '.$user.' $filename: '.$filename.', $timestamp: '.$timestamp.')', ['app' => 'files_trashbin']); |
|
395 | 395 | } else { |
396 | 396 | // if location no longer exists, restore file in the root directory |
397 | 397 | if ($location !== '/' && |
398 | - (!$view->is_dir('files/' . $location) || |
|
399 | - !$view->isCreatable('files/' . $location)) |
|
398 | + (!$view->is_dir('files/'.$location) || |
|
399 | + !$view->isCreatable('files/'.$location)) |
|
400 | 400 | ) { |
401 | 401 | $location = ''; |
402 | 402 | } |
@@ -406,8 +406,8 @@ discard block |
||
406 | 406 | // we need a extension in case a file/dir with the same name already exists |
407 | 407 | $uniqueFilename = self::getUniqueFilename($location, $filename, $view); |
408 | 408 | |
409 | - $source = Filesystem::normalizePath('files_trashbin/files/' . $file); |
|
410 | - $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename); |
|
409 | + $source = Filesystem::normalizePath('files_trashbin/files/'.$file); |
|
410 | + $target = Filesystem::normalizePath('files/'.$location.'/'.$uniqueFilename); |
|
411 | 411 | if (!$view->file_exists($source)) { |
412 | 412 | return false; |
413 | 413 | } |
@@ -419,10 +419,10 @@ discard block |
||
419 | 419 | // handle the restore result |
420 | 420 | if ($restoreResult) { |
421 | 421 | $fakeRoot = $view->getRoot(); |
422 | - $view->chroot('/' . $user . '/files'); |
|
423 | - $view->touch('/' . $location . '/' . $uniqueFilename, $mtime); |
|
422 | + $view->chroot('/'.$user.'/files'); |
|
423 | + $view->touch('/'.$location.'/'.$uniqueFilename, $mtime); |
|
424 | 424 | $view->chroot($fakeRoot); |
425 | - \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename), |
|
425 | + \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename), |
|
426 | 426 | 'trashPath' => Filesystem::normalizePath($file))); |
427 | 427 | |
428 | 428 | self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp); |
@@ -456,7 +456,7 @@ discard block |
||
456 | 456 | $user = User::getUser(); |
457 | 457 | $rootView = new View('/'); |
458 | 458 | |
459 | - $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename); |
|
459 | + $target = Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename); |
|
460 | 460 | |
461 | 461 | list($owner, $ownerPath) = self::getUidAndFilename($target); |
462 | 462 | |
@@ -471,14 +471,14 @@ discard block |
||
471 | 471 | $versionedFile = $file; |
472 | 472 | } |
473 | 473 | |
474 | - if ($view->is_dir('/files_trashbin/versions/' . $file)) { |
|
475 | - $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath)); |
|
474 | + if ($view->is_dir('/files_trashbin/versions/'.$file)) { |
|
475 | + $rootView->rename(Filesystem::normalizePath($user.'/files_trashbin/versions/'.$file), Filesystem::normalizePath($owner.'/files_versions/'.$ownerPath)); |
|
476 | 476 | } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) { |
477 | 477 | foreach ($versions as $v) { |
478 | 478 | if ($timestamp) { |
479 | - $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
479 | + $rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v.'.d'.$timestamp, $owner.'/files_versions/'.$ownerPath.'.v'.$v); |
|
480 | 480 | } else { |
481 | - $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v); |
|
481 | + $rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v, $owner.'/files_versions/'.$ownerPath.'.v'.$v); |
|
482 | 482 | } |
483 | 483 | } |
484 | 484 | } |
@@ -491,7 +491,7 @@ discard block |
||
491 | 491 | public static function deleteAll() { |
492 | 492 | $user = User::getUser(); |
493 | 493 | $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
494 | - $view = new View('/' . $user); |
|
494 | + $view = new View('/'.$user); |
|
495 | 495 | $fileInfos = $view->getDirectoryContent('files_trashbin/files'); |
496 | 496 | |
497 | 497 | try { |
@@ -502,7 +502,7 @@ discard block |
||
502 | 502 | |
503 | 503 | // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore) |
504 | 504 | $filePaths = array(); |
505 | - foreach($fileInfos as $fileInfo){ |
|
505 | + foreach ($fileInfos as $fileInfo) { |
|
506 | 506 | $filePaths[] = $view->getRelativePath($fileInfo->getPath()); |
507 | 507 | } |
508 | 508 | unset($fileInfos); // save memory |
@@ -511,7 +511,7 @@ discard block |
||
511 | 511 | \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths)); |
512 | 512 | |
513 | 513 | // Single-File Hooks |
514 | - foreach($filePaths as $path){ |
|
514 | + foreach ($filePaths as $path) { |
|
515 | 515 | self::emitTrashbinPreDelete($path); |
516 | 516 | } |
517 | 517 | |
@@ -524,7 +524,7 @@ discard block |
||
524 | 524 | \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths)); |
525 | 525 | |
526 | 526 | // Single-File Hooks |
527 | - foreach($filePaths as $path){ |
|
527 | + foreach ($filePaths as $path) { |
|
528 | 528 | self::emitTrashbinPostDelete($path); |
529 | 529 | } |
530 | 530 | |
@@ -538,7 +538,7 @@ discard block |
||
538 | 538 | * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted |
539 | 539 | * @param string $path |
540 | 540 | */ |
541 | - protected static function emitTrashbinPreDelete($path){ |
|
541 | + protected static function emitTrashbinPreDelete($path) { |
|
542 | 542 | \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path)); |
543 | 543 | } |
544 | 544 | |
@@ -546,7 +546,7 @@ discard block |
||
546 | 546 | * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted |
547 | 547 | * @param string $path |
548 | 548 | */ |
549 | - protected static function emitTrashbinPostDelete($path){ |
|
549 | + protected static function emitTrashbinPostDelete($path) { |
|
550 | 550 | \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path)); |
551 | 551 | } |
552 | 552 | |
@@ -561,13 +561,13 @@ discard block |
||
561 | 561 | */ |
562 | 562 | public static function delete($filename, $user, $timestamp = null) { |
563 | 563 | $userRoot = \OC::$server->getUserFolder($user)->getParent(); |
564 | - $view = new View('/' . $user); |
|
564 | + $view = new View('/'.$user); |
|
565 | 565 | $size = 0; |
566 | 566 | |
567 | 567 | if ($timestamp) { |
568 | 568 | $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); |
569 | 569 | $query->execute(array($user, $filename, $timestamp)); |
570 | - $file = $filename . '.d' . $timestamp; |
|
570 | + $file = $filename.'.d'.$timestamp; |
|
571 | 571 | } else { |
572 | 572 | $file = $filename; |
573 | 573 | } |
@@ -575,20 +575,20 @@ discard block |
||
575 | 575 | $size += self::deleteVersions($view, $file, $filename, $timestamp, $user); |
576 | 576 | |
577 | 577 | try { |
578 | - $node = $userRoot->get('/files_trashbin/files/' . $file); |
|
578 | + $node = $userRoot->get('/files_trashbin/files/'.$file); |
|
579 | 579 | } catch (NotFoundException $e) { |
580 | 580 | return $size; |
581 | 581 | } |
582 | 582 | |
583 | 583 | if ($node instanceof Folder) { |
584 | - $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file)); |
|
584 | + $size += self::calculateSize(new View('/'.$user.'/files_trashbin/files/'.$file)); |
|
585 | 585 | } else if ($node instanceof File) { |
586 | - $size += $view->filesize('/files_trashbin/files/' . $file); |
|
586 | + $size += $view->filesize('/files_trashbin/files/'.$file); |
|
587 | 587 | } |
588 | 588 | |
589 | - self::emitTrashbinPreDelete('/files_trashbin/files/' . $file); |
|
589 | + self::emitTrashbinPreDelete('/files_trashbin/files/'.$file); |
|
590 | 590 | $node->delete(); |
591 | - self::emitTrashbinPostDelete('/files_trashbin/files/' . $file); |
|
591 | + self::emitTrashbinPostDelete('/files_trashbin/files/'.$file); |
|
592 | 592 | |
593 | 593 | return $size; |
594 | 594 | } |
@@ -604,17 +604,17 @@ discard block |
||
604 | 604 | private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) { |
605 | 605 | $size = 0; |
606 | 606 | if (\OCP\App::isEnabled('files_versions')) { |
607 | - if ($view->is_dir('files_trashbin/versions/' . $file)) { |
|
608 | - $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file)); |
|
609 | - $view->unlink('files_trashbin/versions/' . $file); |
|
607 | + if ($view->is_dir('files_trashbin/versions/'.$file)) { |
|
608 | + $size += self::calculateSize(new View('/'.$user.'/files_trashbin/versions/'.$file)); |
|
609 | + $view->unlink('files_trashbin/versions/'.$file); |
|
610 | 610 | } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) { |
611 | 611 | foreach ($versions as $v) { |
612 | 612 | if ($timestamp) { |
613 | - $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
614 | - $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp); |
|
613 | + $size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp); |
|
614 | + $view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp); |
|
615 | 615 | } else { |
616 | - $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
617 | - $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v); |
|
616 | + $size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v); |
|
617 | + $view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v); |
|
618 | 618 | } |
619 | 619 | } |
620 | 620 | } |
@@ -631,13 +631,13 @@ discard block |
||
631 | 631 | */ |
632 | 632 | public static function file_exists($filename, $timestamp = null) { |
633 | 633 | $user = User::getUser(); |
634 | - $view = new View('/' . $user); |
|
634 | + $view = new View('/'.$user); |
|
635 | 635 | |
636 | 636 | if ($timestamp) { |
637 | - $filename = $filename . '.d' . $timestamp; |
|
637 | + $filename = $filename.'.d'.$timestamp; |
|
638 | 638 | } |
639 | 639 | |
640 | - $target = Filesystem::normalizePath('files_trashbin/files/' . $filename); |
|
640 | + $target = Filesystem::normalizePath('files_trashbin/files/'.$filename); |
|
641 | 641 | return $view->file_exists($target); |
642 | 642 | } |
643 | 643 | |
@@ -662,7 +662,7 @@ discard block |
||
662 | 662 | private static function calculateFreeSpace($trashbinSize, $user) { |
663 | 663 | $softQuota = true; |
664 | 664 | $userObject = \OC::$server->getUserManager()->get($user); |
665 | - if(is_null($userObject)) { |
|
665 | + if (is_null($userObject)) { |
|
666 | 666 | return 0; |
667 | 667 | } |
668 | 668 | $quota = $userObject->getQuota(); |
@@ -681,7 +681,7 @@ discard block |
||
681 | 681 | // subtract size of files and current trash bin size from quota |
682 | 682 | if ($softQuota) { |
683 | 683 | $userFolder = \OC::$server->getUserFolder($user); |
684 | - if(is_null($userFolder)) { |
|
684 | + if (is_null($userFolder)) { |
|
685 | 685 | return 0; |
686 | 686 | } |
687 | 687 | $free = $quota - $userFolder->getSize(); // remaining free space for user |
@@ -763,7 +763,7 @@ discard block |
||
763 | 763 | foreach ($files as $file) { |
764 | 764 | if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) { |
765 | 765 | $tmp = self::delete($file['name'], $user, $file['mtime']); |
766 | - \OC::$server->getLogger()->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']); |
|
766 | + \OC::$server->getLogger()->info('remove "'.$file['name'].'" ('.$tmp.'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']); |
|
767 | 767 | $availableSpace += $tmp; |
768 | 768 | $size += $tmp; |
769 | 769 | } else { |
@@ -794,10 +794,10 @@ discard block |
||
794 | 794 | $size += self::delete($filename, $user, $timestamp); |
795 | 795 | $count++; |
796 | 796 | } catch (\OCP\Files\NotPermittedException $e) { |
797 | - \OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']); |
|
797 | + \OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "'.$filename.'" from trashbin failed.']); |
|
798 | 798 | } |
799 | 799 | \OC::$server->getLogger()->info( |
800 | - 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.', |
|
800 | + 'Remove "'.$filename.'" from trashbin because it exceeds max retention obligation term.', |
|
801 | 801 | ['app' => 'files_trashbin'] |
802 | 802 | ); |
803 | 803 | } else { |
@@ -823,16 +823,16 @@ discard block |
||
823 | 823 | $view->mkdir($destination); |
824 | 824 | $view->touch($destination, $view->filemtime($source)); |
825 | 825 | foreach ($view->getDirectoryContent($source) as $i) { |
826 | - $pathDir = $source . '/' . $i['name']; |
|
826 | + $pathDir = $source.'/'.$i['name']; |
|
827 | 827 | if ($view->is_dir($pathDir)) { |
828 | - $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view); |
|
828 | + $size += self::copy_recursive($pathDir, $destination.'/'.$i['name'], $view); |
|
829 | 829 | } else { |
830 | 830 | $size += $view->filesize($pathDir); |
831 | - $result = $view->copy($pathDir, $destination . '/' . $i['name']); |
|
831 | + $result = $view->copy($pathDir, $destination.'/'.$i['name']); |
|
832 | 832 | if (!$result) { |
833 | 833 | throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException(); |
834 | 834 | } |
835 | - $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir)); |
|
835 | + $view->touch($destination.'/'.$i['name'], $view->filemtime($pathDir)); |
|
836 | 836 | } |
837 | 837 | } |
838 | 838 | } else { |
@@ -854,7 +854,7 @@ discard block |
||
854 | 854 | * @return array |
855 | 855 | */ |
856 | 856 | private static function getVersionsFromTrash($filename, $timestamp, $user) { |
857 | - $view = new View('/' . $user . '/files_trashbin/versions'); |
|
857 | + $view = new View('/'.$user.'/files_trashbin/versions'); |
|
858 | 858 | $versions = array(); |
859 | 859 | |
860 | 860 | //force rescan of versions, local storage may not have updated the cache |
@@ -867,10 +867,10 @@ discard block |
||
867 | 867 | |
868 | 868 | if ($timestamp) { |
869 | 869 | // fetch for old versions |
870 | - $matches = $view->searchRaw($filename . '.v%.d' . $timestamp); |
|
870 | + $matches = $view->searchRaw($filename.'.v%.d'.$timestamp); |
|
871 | 871 | $offset = -strlen($timestamp) - 2; |
872 | 872 | } else { |
873 | - $matches = $view->searchRaw($filename . '.v%'); |
|
873 | + $matches = $view->searchRaw($filename.'.v%'); |
|
874 | 874 | } |
875 | 875 | |
876 | 876 | if (is_array($matches)) { |
@@ -900,18 +900,18 @@ discard block |
||
900 | 900 | $name = pathinfo($filename, PATHINFO_FILENAME); |
901 | 901 | $l = \OC::$server->getL10N('files_trashbin'); |
902 | 902 | |
903 | - $location = '/' . trim($location, '/'); |
|
903 | + $location = '/'.trim($location, '/'); |
|
904 | 904 | |
905 | 905 | // if extension is not empty we set a dot in front of it |
906 | 906 | if ($ext !== '') { |
907 | - $ext = '.' . $ext; |
|
907 | + $ext = '.'.$ext; |
|
908 | 908 | } |
909 | 909 | |
910 | - if ($view->file_exists('files' . $location . '/' . $filename)) { |
|
910 | + if ($view->file_exists('files'.$location.'/'.$filename)) { |
|
911 | 911 | $i = 2; |
912 | - $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext; |
|
913 | - while ($view->file_exists('files' . $location . '/' . $uniqueName)) { |
|
914 | - $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext; |
|
912 | + $uniqueName = $name." (".$l->t("restored").")".$ext; |
|
913 | + while ($view->file_exists('files'.$location.'/'.$uniqueName)) { |
|
914 | + $uniqueName = $name." (".$l->t("restored")." ".$i.")".$ext; |
|
915 | 915 | $i++; |
916 | 916 | } |
917 | 917 | |
@@ -928,7 +928,7 @@ discard block |
||
928 | 928 | * @return integer size of the folder |
929 | 929 | */ |
930 | 930 | private static function calculateSize($view) { |
931 | - $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath(''); |
|
931 | + $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').$view->getAbsolutePath(''); |
|
932 | 932 | if (!file_exists($root)) { |
933 | 933 | return 0; |
934 | 934 | } |
@@ -959,7 +959,7 @@ discard block |
||
959 | 959 | * @return integer trash bin size |
960 | 960 | */ |
961 | 961 | private static function getTrashbinSize($user) { |
962 | - $view = new View('/' . $user); |
|
962 | + $view = new View('/'.$user); |
|
963 | 963 | $fileInfo = $view->getFileInfo('/files_trashbin'); |
964 | 964 | return isset($fileInfo['size']) ? $fileInfo['size'] : 0; |
965 | 965 | } |
@@ -988,7 +988,7 @@ discard block |
||
988 | 988 | */ |
989 | 989 | public static function isEmpty($user) { |
990 | 990 | |
991 | - $view = new View('/' . $user . '/files_trashbin'); |
|
991 | + $view = new View('/'.$user.'/files_trashbin'); |
|
992 | 992 | if ($view->is_dir('/files') && $dh = $view->opendir('/files')) { |
993 | 993 | while ($file = readdir($dh)) { |
994 | 994 | if (!Filesystem::isIgnoredDir($file)) { |
@@ -102,6 +102,9 @@ |
||
102 | 102 | return \OC_App::getAppVersions(); |
103 | 103 | } |
104 | 104 | |
105 | + /** |
|
106 | + * @param string $appId |
|
107 | + */ |
|
105 | 108 | protected function getAppInfo($appId) { |
106 | 109 | return \OC_App::getAppInfo($appId); |
107 | 110 | } |
@@ -106,7 +106,7 @@ discard block |
||
106 | 106 | $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']])); |
107 | 107 | |
108 | 108 | if ($this->isAdmin()) { |
109 | - $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater'); |
|
109 | + $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index').'#updater'); |
|
110 | 110 | } |
111 | 111 | } else { |
112 | 112 | $appInfo = $this->getAppInfo($notification->getObjectType()); |
@@ -126,7 +126,7 @@ discard block |
||
126 | 126 | ]); |
127 | 127 | |
128 | 128 | if ($this->isAdmin()) { |
129 | - $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps', ['category' => 'updates']) . '#app-' . $notification->getObjectType()); |
|
129 | + $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps', ['category' => 'updates']).'#app-'.$notification->getObjectType()); |
|
130 | 130 | } |
131 | 131 | } |
132 | 132 |
@@ -38,141 +38,141 @@ |
||
38 | 38 | |
39 | 39 | class Notifier implements INotifier { |
40 | 40 | |
41 | - /** @var IURLGenerator */ |
|
42 | - protected $url; |
|
43 | - |
|
44 | - /** @var IConfig */ |
|
45 | - protected $config; |
|
46 | - |
|
47 | - /** @var IManager */ |
|
48 | - protected $notificationManager; |
|
49 | - |
|
50 | - /** @var IFactory */ |
|
51 | - protected $l10NFactory; |
|
52 | - |
|
53 | - /** @var IUserSession */ |
|
54 | - protected $userSession; |
|
55 | - |
|
56 | - /** @var IGroupManager */ |
|
57 | - protected $groupManager; |
|
58 | - |
|
59 | - /** @var string[] */ |
|
60 | - protected $appVersions; |
|
61 | - |
|
62 | - /** |
|
63 | - * Notifier constructor. |
|
64 | - * |
|
65 | - * @param IURLGenerator $url |
|
66 | - * @param IConfig $config |
|
67 | - * @param IManager $notificationManager |
|
68 | - * @param IFactory $l10NFactory |
|
69 | - * @param IUserSession $userSession |
|
70 | - * @param IGroupManager $groupManager |
|
71 | - */ |
|
72 | - public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) { |
|
73 | - $this->url = $url; |
|
74 | - $this->notificationManager = $notificationManager; |
|
75 | - $this->config = $config; |
|
76 | - $this->l10NFactory = $l10NFactory; |
|
77 | - $this->userSession = $userSession; |
|
78 | - $this->groupManager = $groupManager; |
|
79 | - $this->appVersions = $this->getAppVersions(); |
|
80 | - } |
|
81 | - |
|
82 | - /** |
|
83 | - * @param INotification $notification |
|
84 | - * @param string $languageCode The code of the language that should be used to prepare the notification |
|
85 | - * @return INotification |
|
86 | - * @throws \InvalidArgumentException When the notification was not prepared by a notifier |
|
87 | - * @since 9.0.0 |
|
88 | - */ |
|
89 | - public function prepare(INotification $notification, $languageCode): INotification { |
|
90 | - if ($notification->getApp() !== 'updatenotification') { |
|
91 | - throw new \InvalidArgumentException('Unknown app id'); |
|
92 | - } |
|
93 | - |
|
94 | - $l = $this->l10NFactory->get('updatenotification', $languageCode); |
|
95 | - if ($notification->getSubject() === 'connection_error') { |
|
96 | - $errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0); |
|
97 | - if ($errors === 0) { |
|
98 | - $this->notificationManager->markProcessed($notification); |
|
99 | - throw new \InvalidArgumentException('Update checked worked again'); |
|
100 | - } |
|
101 | - |
|
102 | - $notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors])) |
|
103 | - ->setParsedMessage($l->t('Please check the Nextcloud and server log files for errors.')); |
|
104 | - } elseif ($notification->getObjectType() === 'core') { |
|
105 | - $this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions()); |
|
106 | - |
|
107 | - $parameters = $notification->getSubjectParameters(); |
|
108 | - $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']])); |
|
109 | - |
|
110 | - if ($this->isAdmin()) { |
|
111 | - $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater'); |
|
112 | - } |
|
113 | - } else { |
|
114 | - $appInfo = $this->getAppInfo($notification->getObjectType()); |
|
115 | - $appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name']; |
|
116 | - |
|
117 | - if (isset($this->appVersions[$notification->getObjectType()])) { |
|
118 | - $this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]); |
|
119 | - } |
|
120 | - |
|
121 | - $notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()])) |
|
122 | - ->setRichSubject($l->t('Update for {app} to version %s is available.', [$notification->getObjectId()]), [ |
|
123 | - 'app' => [ |
|
124 | - 'type' => 'app', |
|
125 | - 'id' => $notification->getObjectType(), |
|
126 | - 'name' => $appName, |
|
127 | - ] |
|
128 | - ]); |
|
129 | - |
|
130 | - if ($this->isAdmin()) { |
|
131 | - $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps', ['category' => 'updates']) . '#app-' . $notification->getObjectType()); |
|
132 | - } |
|
133 | - } |
|
134 | - |
|
135 | - $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg'))); |
|
136 | - |
|
137 | - return $notification; |
|
138 | - } |
|
139 | - |
|
140 | - /** |
|
141 | - * Remove the notification and prevent rendering, when the update is installed |
|
142 | - * |
|
143 | - * @param INotification $notification |
|
144 | - * @param string $installedVersion |
|
145 | - * @throws \InvalidArgumentException When the update is already installed |
|
146 | - */ |
|
147 | - protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) { |
|
148 | - if (version_compare($notification->getObjectId(), $installedVersion, '<=')) { |
|
149 | - $this->notificationManager->markProcessed($notification); |
|
150 | - throw new \InvalidArgumentException('Update already installed'); |
|
151 | - } |
|
152 | - } |
|
153 | - |
|
154 | - /** |
|
155 | - * @return bool |
|
156 | - */ |
|
157 | - protected function isAdmin(): bool { |
|
158 | - $user = $this->userSession->getUser(); |
|
159 | - |
|
160 | - if ($user instanceof IUser) { |
|
161 | - return $this->groupManager->isAdmin($user->getUID()); |
|
162 | - } |
|
163 | - |
|
164 | - return false; |
|
165 | - } |
|
166 | - |
|
167 | - protected function getCoreVersions(): string { |
|
168 | - return implode('.', Util::getVersion()); |
|
169 | - } |
|
170 | - |
|
171 | - protected function getAppVersions(): array { |
|
172 | - return \OC_App::getAppVersions(); |
|
173 | - } |
|
174 | - |
|
175 | - protected function getAppInfo($appId) { |
|
176 | - return \OC_App::getAppInfo($appId); |
|
177 | - } |
|
41 | + /** @var IURLGenerator */ |
|
42 | + protected $url; |
|
43 | + |
|
44 | + /** @var IConfig */ |
|
45 | + protected $config; |
|
46 | + |
|
47 | + /** @var IManager */ |
|
48 | + protected $notificationManager; |
|
49 | + |
|
50 | + /** @var IFactory */ |
|
51 | + protected $l10NFactory; |
|
52 | + |
|
53 | + /** @var IUserSession */ |
|
54 | + protected $userSession; |
|
55 | + |
|
56 | + /** @var IGroupManager */ |
|
57 | + protected $groupManager; |
|
58 | + |
|
59 | + /** @var string[] */ |
|
60 | + protected $appVersions; |
|
61 | + |
|
62 | + /** |
|
63 | + * Notifier constructor. |
|
64 | + * |
|
65 | + * @param IURLGenerator $url |
|
66 | + * @param IConfig $config |
|
67 | + * @param IManager $notificationManager |
|
68 | + * @param IFactory $l10NFactory |
|
69 | + * @param IUserSession $userSession |
|
70 | + * @param IGroupManager $groupManager |
|
71 | + */ |
|
72 | + public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) { |
|
73 | + $this->url = $url; |
|
74 | + $this->notificationManager = $notificationManager; |
|
75 | + $this->config = $config; |
|
76 | + $this->l10NFactory = $l10NFactory; |
|
77 | + $this->userSession = $userSession; |
|
78 | + $this->groupManager = $groupManager; |
|
79 | + $this->appVersions = $this->getAppVersions(); |
|
80 | + } |
|
81 | + |
|
82 | + /** |
|
83 | + * @param INotification $notification |
|
84 | + * @param string $languageCode The code of the language that should be used to prepare the notification |
|
85 | + * @return INotification |
|
86 | + * @throws \InvalidArgumentException When the notification was not prepared by a notifier |
|
87 | + * @since 9.0.0 |
|
88 | + */ |
|
89 | + public function prepare(INotification $notification, $languageCode): INotification { |
|
90 | + if ($notification->getApp() !== 'updatenotification') { |
|
91 | + throw new \InvalidArgumentException('Unknown app id'); |
|
92 | + } |
|
93 | + |
|
94 | + $l = $this->l10NFactory->get('updatenotification', $languageCode); |
|
95 | + if ($notification->getSubject() === 'connection_error') { |
|
96 | + $errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0); |
|
97 | + if ($errors === 0) { |
|
98 | + $this->notificationManager->markProcessed($notification); |
|
99 | + throw new \InvalidArgumentException('Update checked worked again'); |
|
100 | + } |
|
101 | + |
|
102 | + $notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors])) |
|
103 | + ->setParsedMessage($l->t('Please check the Nextcloud and server log files for errors.')); |
|
104 | + } elseif ($notification->getObjectType() === 'core') { |
|
105 | + $this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions()); |
|
106 | + |
|
107 | + $parameters = $notification->getSubjectParameters(); |
|
108 | + $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']])); |
|
109 | + |
|
110 | + if ($this->isAdmin()) { |
|
111 | + $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater'); |
|
112 | + } |
|
113 | + } else { |
|
114 | + $appInfo = $this->getAppInfo($notification->getObjectType()); |
|
115 | + $appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name']; |
|
116 | + |
|
117 | + if (isset($this->appVersions[$notification->getObjectType()])) { |
|
118 | + $this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]); |
|
119 | + } |
|
120 | + |
|
121 | + $notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()])) |
|
122 | + ->setRichSubject($l->t('Update for {app} to version %s is available.', [$notification->getObjectId()]), [ |
|
123 | + 'app' => [ |
|
124 | + 'type' => 'app', |
|
125 | + 'id' => $notification->getObjectType(), |
|
126 | + 'name' => $appName, |
|
127 | + ] |
|
128 | + ]); |
|
129 | + |
|
130 | + if ($this->isAdmin()) { |
|
131 | + $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps', ['category' => 'updates']) . '#app-' . $notification->getObjectType()); |
|
132 | + } |
|
133 | + } |
|
134 | + |
|
135 | + $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg'))); |
|
136 | + |
|
137 | + return $notification; |
|
138 | + } |
|
139 | + |
|
140 | + /** |
|
141 | + * Remove the notification and prevent rendering, when the update is installed |
|
142 | + * |
|
143 | + * @param INotification $notification |
|
144 | + * @param string $installedVersion |
|
145 | + * @throws \InvalidArgumentException When the update is already installed |
|
146 | + */ |
|
147 | + protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) { |
|
148 | + if (version_compare($notification->getObjectId(), $installedVersion, '<=')) { |
|
149 | + $this->notificationManager->markProcessed($notification); |
|
150 | + throw new \InvalidArgumentException('Update already installed'); |
|
151 | + } |
|
152 | + } |
|
153 | + |
|
154 | + /** |
|
155 | + * @return bool |
|
156 | + */ |
|
157 | + protected function isAdmin(): bool { |
|
158 | + $user = $this->userSession->getUser(); |
|
159 | + |
|
160 | + if ($user instanceof IUser) { |
|
161 | + return $this->groupManager->isAdmin($user->getUID()); |
|
162 | + } |
|
163 | + |
|
164 | + return false; |
|
165 | + } |
|
166 | + |
|
167 | + protected function getCoreVersions(): string { |
|
168 | + return implode('.', Util::getVersion()); |
|
169 | + } |
|
170 | + |
|
171 | + protected function getAppVersions(): array { |
|
172 | + return \OC_App::getAppVersions(); |
|
173 | + } |
|
174 | + |
|
175 | + protected function getAppInfo($appId) { |
|
176 | + return \OC_App::getAppInfo($appId); |
|
177 | + } |
|
178 | 178 | } |
@@ -74,8 +74,6 @@ |
||
74 | 74 | /** |
75 | 75 | * save the configuration value as provided |
76 | 76 | * @param string $configID |
77 | - * @param string $configKey |
|
78 | - * @param string $configValue |
|
79 | 77 | */ |
80 | 78 | protected function setValue($configID, $key, $value) { |
81 | 79 | $configHolder = new Configuration($configID); |
@@ -34,53 +34,53 @@ |
||
34 | 34 | |
35 | 35 | class SetConfig extends Command { |
36 | 36 | |
37 | - protected function configure() { |
|
38 | - $this |
|
39 | - ->setName('ldap:set-config') |
|
40 | - ->setDescription('modifies an LDAP configuration') |
|
41 | - ->addArgument( |
|
42 | - 'configID', |
|
43 | - InputArgument::REQUIRED, |
|
44 | - 'the configuration ID' |
|
45 | - ) |
|
46 | - ->addArgument( |
|
47 | - 'configKey', |
|
48 | - InputArgument::REQUIRED, |
|
49 | - 'the configuration key' |
|
50 | - ) |
|
51 | - ->addArgument( |
|
52 | - 'configValue', |
|
53 | - InputArgument::REQUIRED, |
|
54 | - 'the new configuration value' |
|
55 | - ) |
|
56 | - ; |
|
57 | - } |
|
37 | + protected function configure() { |
|
38 | + $this |
|
39 | + ->setName('ldap:set-config') |
|
40 | + ->setDescription('modifies an LDAP configuration') |
|
41 | + ->addArgument( |
|
42 | + 'configID', |
|
43 | + InputArgument::REQUIRED, |
|
44 | + 'the configuration ID' |
|
45 | + ) |
|
46 | + ->addArgument( |
|
47 | + 'configKey', |
|
48 | + InputArgument::REQUIRED, |
|
49 | + 'the configuration key' |
|
50 | + ) |
|
51 | + ->addArgument( |
|
52 | + 'configValue', |
|
53 | + InputArgument::REQUIRED, |
|
54 | + 'the new configuration value' |
|
55 | + ) |
|
56 | + ; |
|
57 | + } |
|
58 | 58 | |
59 | - protected function execute(InputInterface $input, OutputInterface $output) { |
|
60 | - $helper = new Helper(\OC::$server->getConfig()); |
|
61 | - $availableConfigs = $helper->getServerConfigurationPrefixes(); |
|
62 | - $configID = $input->getArgument('configID'); |
|
63 | - if(!in_array($configID, $availableConfigs)) { |
|
64 | - $output->writeln("Invalid configID"); |
|
65 | - return; |
|
66 | - } |
|
59 | + protected function execute(InputInterface $input, OutputInterface $output) { |
|
60 | + $helper = new Helper(\OC::$server->getConfig()); |
|
61 | + $availableConfigs = $helper->getServerConfigurationPrefixes(); |
|
62 | + $configID = $input->getArgument('configID'); |
|
63 | + if(!in_array($configID, $availableConfigs)) { |
|
64 | + $output->writeln("Invalid configID"); |
|
65 | + return; |
|
66 | + } |
|
67 | 67 | |
68 | - $this->setValue( |
|
69 | - $configID, |
|
70 | - $input->getArgument('configKey'), |
|
71 | - $input->getArgument('configValue') |
|
72 | - ); |
|
73 | - } |
|
68 | + $this->setValue( |
|
69 | + $configID, |
|
70 | + $input->getArgument('configKey'), |
|
71 | + $input->getArgument('configValue') |
|
72 | + ); |
|
73 | + } |
|
74 | 74 | |
75 | - /** |
|
76 | - * save the configuration value as provided |
|
77 | - * @param string $configID |
|
78 | - * @param string $configKey |
|
79 | - * @param string $configValue |
|
80 | - */ |
|
81 | - protected function setValue($configID, $key, $value) { |
|
82 | - $configHolder = new Configuration($configID); |
|
83 | - $configHolder->$key = $value; |
|
84 | - $configHolder->saveConfiguration(); |
|
85 | - } |
|
75 | + /** |
|
76 | + * save the configuration value as provided |
|
77 | + * @param string $configID |
|
78 | + * @param string $configKey |
|
79 | + * @param string $configValue |
|
80 | + */ |
|
81 | + protected function setValue($configID, $key, $value) { |
|
82 | + $configHolder = new Configuration($configID); |
|
83 | + $configHolder->$key = $value; |
|
84 | + $configHolder->saveConfiguration(); |
|
85 | + } |
|
86 | 86 | } |
@@ -60,7 +60,7 @@ |
||
60 | 60 | $helper = new Helper(\OC::$server->getConfig()); |
61 | 61 | $availableConfigs = $helper->getServerConfigurationPrefixes(); |
62 | 62 | $configID = $input->getArgument('configID'); |
63 | - if(!in_array($configID, $availableConfigs)) { |
|
63 | + if (!in_array($configID, $availableConfigs)) { |
|
64 | 64 | $output->writeln("Invalid configID"); |
65 | 65 | return; |
66 | 66 | } |
@@ -77,7 +77,7 @@ |
||
77 | 77 | } |
78 | 78 | |
79 | 79 | /** |
80 | - * @return int |
|
80 | + * @return string |
|
81 | 81 | */ |
82 | 82 | static private function getRefreshInterval() { |
83 | 83 | //defaults to every hour |
@@ -46,183 +46,183 @@ |
||
46 | 46 | use OCP\ILogger; |
47 | 47 | |
48 | 48 | class UpdateGroups extends \OC\BackgroundJob\TimedJob { |
49 | - static private $groupsFromDB; |
|
50 | - |
|
51 | - static private $groupBE; |
|
52 | - |
|
53 | - public function __construct(){ |
|
54 | - $this->interval = self::getRefreshInterval(); |
|
55 | - } |
|
56 | - |
|
57 | - /** |
|
58 | - * @param mixed $argument |
|
59 | - */ |
|
60 | - public function run($argument){ |
|
61 | - self::updateGroups(); |
|
62 | - } |
|
63 | - |
|
64 | - static public function updateGroups() { |
|
65 | - \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG); |
|
66 | - |
|
67 | - $knownGroups = array_keys(self::getKnownGroups()); |
|
68 | - $actualGroups = self::getGroupBE()->getGroups(); |
|
69 | - |
|
70 | - if(empty($actualGroups) && empty($knownGroups)) { |
|
71 | - \OCP\Util::writeLog('user_ldap', |
|
72 | - 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', |
|
73 | - ILogger::INFO); |
|
74 | - return; |
|
75 | - } |
|
76 | - |
|
77 | - self::handleKnownGroups(array_intersect($actualGroups, $knownGroups)); |
|
78 | - self::handleCreatedGroups(array_diff($actualGroups, $knownGroups)); |
|
79 | - self::handleRemovedGroups(array_diff($knownGroups, $actualGroups)); |
|
80 | - |
|
81 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG); |
|
82 | - } |
|
83 | - |
|
84 | - /** |
|
85 | - * @return int |
|
86 | - */ |
|
87 | - static private function getRefreshInterval() { |
|
88 | - //defaults to every hour |
|
89 | - return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600); |
|
90 | - } |
|
91 | - |
|
92 | - /** |
|
93 | - * @param string[] $groups |
|
94 | - */ |
|
95 | - static private function handleKnownGroups($groups) { |
|
96 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG); |
|
97 | - $query = \OC_DB::prepare(' |
|
49 | + static private $groupsFromDB; |
|
50 | + |
|
51 | + static private $groupBE; |
|
52 | + |
|
53 | + public function __construct(){ |
|
54 | + $this->interval = self::getRefreshInterval(); |
|
55 | + } |
|
56 | + |
|
57 | + /** |
|
58 | + * @param mixed $argument |
|
59 | + */ |
|
60 | + public function run($argument){ |
|
61 | + self::updateGroups(); |
|
62 | + } |
|
63 | + |
|
64 | + static public function updateGroups() { |
|
65 | + \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG); |
|
66 | + |
|
67 | + $knownGroups = array_keys(self::getKnownGroups()); |
|
68 | + $actualGroups = self::getGroupBE()->getGroups(); |
|
69 | + |
|
70 | + if(empty($actualGroups) && empty($knownGroups)) { |
|
71 | + \OCP\Util::writeLog('user_ldap', |
|
72 | + 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', |
|
73 | + ILogger::INFO); |
|
74 | + return; |
|
75 | + } |
|
76 | + |
|
77 | + self::handleKnownGroups(array_intersect($actualGroups, $knownGroups)); |
|
78 | + self::handleCreatedGroups(array_diff($actualGroups, $knownGroups)); |
|
79 | + self::handleRemovedGroups(array_diff($knownGroups, $actualGroups)); |
|
80 | + |
|
81 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG); |
|
82 | + } |
|
83 | + |
|
84 | + /** |
|
85 | + * @return int |
|
86 | + */ |
|
87 | + static private function getRefreshInterval() { |
|
88 | + //defaults to every hour |
|
89 | + return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600); |
|
90 | + } |
|
91 | + |
|
92 | + /** |
|
93 | + * @param string[] $groups |
|
94 | + */ |
|
95 | + static private function handleKnownGroups($groups) { |
|
96 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG); |
|
97 | + $query = \OC_DB::prepare(' |
|
98 | 98 | UPDATE `*PREFIX*ldap_group_members` |
99 | 99 | SET `owncloudusers` = ? |
100 | 100 | WHERE `owncloudname` = ? |
101 | 101 | '); |
102 | - foreach($groups as $group) { |
|
103 | - //we assume, that self::$groupsFromDB has been retrieved already |
|
104 | - $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']); |
|
105 | - $actualUsers = self::getGroupBE()->usersInGroup($group); |
|
106 | - $hasChanged = false; |
|
107 | - foreach(array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
108 | - \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group)); |
|
109 | - \OCP\Util::writeLog('user_ldap', |
|
110 | - 'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".', |
|
111 | - ILogger::INFO); |
|
112 | - $hasChanged = true; |
|
113 | - } |
|
114 | - foreach(array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
115 | - \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group)); |
|
116 | - \OCP\Util::writeLog('user_ldap', |
|
117 | - 'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".', |
|
118 | - ILogger::INFO); |
|
119 | - $hasChanged = true; |
|
120 | - } |
|
121 | - if($hasChanged) { |
|
122 | - $query->execute(array(serialize($actualUsers), $group)); |
|
123 | - } |
|
124 | - } |
|
125 | - \OCP\Util::writeLog('user_ldap', |
|
126 | - 'bgJ "updateGroups" – FINISHED dealing with known Groups.', |
|
127 | - ILogger::DEBUG); |
|
128 | - } |
|
129 | - |
|
130 | - /** |
|
131 | - * @param string[] $createdGroups |
|
132 | - */ |
|
133 | - static private function handleCreatedGroups($createdGroups) { |
|
134 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG); |
|
135 | - $query = \OC_DB::prepare(' |
|
102 | + foreach($groups as $group) { |
|
103 | + //we assume, that self::$groupsFromDB has been retrieved already |
|
104 | + $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']); |
|
105 | + $actualUsers = self::getGroupBE()->usersInGroup($group); |
|
106 | + $hasChanged = false; |
|
107 | + foreach(array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
108 | + \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group)); |
|
109 | + \OCP\Util::writeLog('user_ldap', |
|
110 | + 'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".', |
|
111 | + ILogger::INFO); |
|
112 | + $hasChanged = true; |
|
113 | + } |
|
114 | + foreach(array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
115 | + \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group)); |
|
116 | + \OCP\Util::writeLog('user_ldap', |
|
117 | + 'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".', |
|
118 | + ILogger::INFO); |
|
119 | + $hasChanged = true; |
|
120 | + } |
|
121 | + if($hasChanged) { |
|
122 | + $query->execute(array(serialize($actualUsers), $group)); |
|
123 | + } |
|
124 | + } |
|
125 | + \OCP\Util::writeLog('user_ldap', |
|
126 | + 'bgJ "updateGroups" – FINISHED dealing with known Groups.', |
|
127 | + ILogger::DEBUG); |
|
128 | + } |
|
129 | + |
|
130 | + /** |
|
131 | + * @param string[] $createdGroups |
|
132 | + */ |
|
133 | + static private function handleCreatedGroups($createdGroups) { |
|
134 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG); |
|
135 | + $query = \OC_DB::prepare(' |
|
136 | 136 | INSERT |
137 | 137 | INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`) |
138 | 138 | VALUES (?, ?) |
139 | 139 | '); |
140 | - foreach($createdGroups as $createdGroup) { |
|
141 | - \OCP\Util::writeLog('user_ldap', |
|
142 | - 'bgJ "updateGroups" – new group "'.$createdGroup.'" found.', |
|
143 | - ILogger::INFO); |
|
144 | - $users = serialize(self::getGroupBE()->usersInGroup($createdGroup)); |
|
145 | - $query->execute(array($createdGroup, $users)); |
|
146 | - } |
|
147 | - \OCP\Util::writeLog('user_ldap', |
|
148 | - 'bgJ "updateGroups" – FINISHED dealing with created Groups.', |
|
149 | - ILogger::DEBUG); |
|
150 | - } |
|
151 | - |
|
152 | - /** |
|
153 | - * @param string[] $removedGroups |
|
154 | - */ |
|
155 | - static private function handleRemovedGroups($removedGroups) { |
|
156 | - \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG); |
|
157 | - $query = \OC_DB::prepare(' |
|
140 | + foreach($createdGroups as $createdGroup) { |
|
141 | + \OCP\Util::writeLog('user_ldap', |
|
142 | + 'bgJ "updateGroups" – new group "'.$createdGroup.'" found.', |
|
143 | + ILogger::INFO); |
|
144 | + $users = serialize(self::getGroupBE()->usersInGroup($createdGroup)); |
|
145 | + $query->execute(array($createdGroup, $users)); |
|
146 | + } |
|
147 | + \OCP\Util::writeLog('user_ldap', |
|
148 | + 'bgJ "updateGroups" – FINISHED dealing with created Groups.', |
|
149 | + ILogger::DEBUG); |
|
150 | + } |
|
151 | + |
|
152 | + /** |
|
153 | + * @param string[] $removedGroups |
|
154 | + */ |
|
155 | + static private function handleRemovedGroups($removedGroups) { |
|
156 | + \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG); |
|
157 | + $query = \OC_DB::prepare(' |
|
158 | 158 | DELETE |
159 | 159 | FROM `*PREFIX*ldap_group_members` |
160 | 160 | WHERE `owncloudname` = ? |
161 | 161 | '); |
162 | - foreach($removedGroups as $removedGroup) { |
|
163 | - \OCP\Util::writeLog('user_ldap', |
|
164 | - 'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.', |
|
165 | - ILogger::INFO); |
|
166 | - $query->execute(array($removedGroup)); |
|
167 | - } |
|
168 | - \OCP\Util::writeLog('user_ldap', |
|
169 | - 'bgJ "updateGroups" – FINISHED dealing with removed groups.', |
|
170 | - ILogger::DEBUG); |
|
171 | - } |
|
172 | - |
|
173 | - /** |
|
174 | - * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy |
|
175 | - */ |
|
176 | - static private function getGroupBE() { |
|
177 | - if(!is_null(self::$groupBE)) { |
|
178 | - return self::$groupBE; |
|
179 | - } |
|
180 | - $helper = new Helper(\OC::$server->getConfig()); |
|
181 | - $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
182 | - $ldapWrapper = new LDAP(); |
|
183 | - if(count($configPrefixes) === 1) { |
|
184 | - //avoid the proxy when there is only one LDAP server configured |
|
185 | - $dbc = \OC::$server->getDatabaseConnection(); |
|
186 | - $userManager = new Manager( |
|
187 | - \OC::$server->getConfig(), |
|
188 | - new FilesystemHelper(), |
|
189 | - new LogWrapper(), |
|
190 | - \OC::$server->getAvatarManager(), |
|
191 | - new \OCP\Image(), |
|
192 | - $dbc, |
|
193 | - \OC::$server->getUserManager(), |
|
194 | - \OC::$server->getNotificationManager()); |
|
195 | - $connector = new Connection($ldapWrapper, $configPrefixes[0]); |
|
196 | - $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager()); |
|
197 | - $groupMapper = new GroupMapping($dbc); |
|
198 | - $userMapper = new UserMapping($dbc); |
|
199 | - $ldapAccess->setGroupMapper($groupMapper); |
|
200 | - $ldapAccess->setUserMapper($userMapper); |
|
201 | - self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager')); |
|
202 | - } else { |
|
203 | - self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager')); |
|
204 | - } |
|
205 | - |
|
206 | - return self::$groupBE; |
|
207 | - } |
|
208 | - |
|
209 | - /** |
|
210 | - * @return array |
|
211 | - */ |
|
212 | - static private function getKnownGroups() { |
|
213 | - if(is_array(self::$groupsFromDB)) { |
|
214 | - return self::$groupsFromDB; |
|
215 | - } |
|
216 | - $query = \OC_DB::prepare(' |
|
162 | + foreach($removedGroups as $removedGroup) { |
|
163 | + \OCP\Util::writeLog('user_ldap', |
|
164 | + 'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.', |
|
165 | + ILogger::INFO); |
|
166 | + $query->execute(array($removedGroup)); |
|
167 | + } |
|
168 | + \OCP\Util::writeLog('user_ldap', |
|
169 | + 'bgJ "updateGroups" – FINISHED dealing with removed groups.', |
|
170 | + ILogger::DEBUG); |
|
171 | + } |
|
172 | + |
|
173 | + /** |
|
174 | + * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy |
|
175 | + */ |
|
176 | + static private function getGroupBE() { |
|
177 | + if(!is_null(self::$groupBE)) { |
|
178 | + return self::$groupBE; |
|
179 | + } |
|
180 | + $helper = new Helper(\OC::$server->getConfig()); |
|
181 | + $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
182 | + $ldapWrapper = new LDAP(); |
|
183 | + if(count($configPrefixes) === 1) { |
|
184 | + //avoid the proxy when there is only one LDAP server configured |
|
185 | + $dbc = \OC::$server->getDatabaseConnection(); |
|
186 | + $userManager = new Manager( |
|
187 | + \OC::$server->getConfig(), |
|
188 | + new FilesystemHelper(), |
|
189 | + new LogWrapper(), |
|
190 | + \OC::$server->getAvatarManager(), |
|
191 | + new \OCP\Image(), |
|
192 | + $dbc, |
|
193 | + \OC::$server->getUserManager(), |
|
194 | + \OC::$server->getNotificationManager()); |
|
195 | + $connector = new Connection($ldapWrapper, $configPrefixes[0]); |
|
196 | + $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager()); |
|
197 | + $groupMapper = new GroupMapping($dbc); |
|
198 | + $userMapper = new UserMapping($dbc); |
|
199 | + $ldapAccess->setGroupMapper($groupMapper); |
|
200 | + $ldapAccess->setUserMapper($userMapper); |
|
201 | + self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager')); |
|
202 | + } else { |
|
203 | + self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager')); |
|
204 | + } |
|
205 | + |
|
206 | + return self::$groupBE; |
|
207 | + } |
|
208 | + |
|
209 | + /** |
|
210 | + * @return array |
|
211 | + */ |
|
212 | + static private function getKnownGroups() { |
|
213 | + if(is_array(self::$groupsFromDB)) { |
|
214 | + return self::$groupsFromDB; |
|
215 | + } |
|
216 | + $query = \OC_DB::prepare(' |
|
217 | 217 | SELECT `owncloudname`, `owncloudusers` |
218 | 218 | FROM `*PREFIX*ldap_group_members` |
219 | 219 | '); |
220 | - $result = $query->execute()->fetchAll(); |
|
221 | - self::$groupsFromDB = array(); |
|
222 | - foreach($result as $dataset) { |
|
223 | - self::$groupsFromDB[$dataset['owncloudname']] = $dataset; |
|
224 | - } |
|
225 | - |
|
226 | - return self::$groupsFromDB; |
|
227 | - } |
|
220 | + $result = $query->execute()->fetchAll(); |
|
221 | + self::$groupsFromDB = array(); |
|
222 | + foreach($result as $dataset) { |
|
223 | + self::$groupsFromDB[$dataset['owncloudname']] = $dataset; |
|
224 | + } |
|
225 | + |
|
226 | + return self::$groupsFromDB; |
|
227 | + } |
|
228 | 228 | } |
@@ -50,14 +50,14 @@ discard block |
||
50 | 50 | |
51 | 51 | static private $groupBE; |
52 | 52 | |
53 | - public function __construct(){ |
|
53 | + public function __construct() { |
|
54 | 54 | $this->interval = self::getRefreshInterval(); |
55 | 55 | } |
56 | 56 | |
57 | 57 | /** |
58 | 58 | * @param mixed $argument |
59 | 59 | */ |
60 | - public function run($argument){ |
|
60 | + public function run($argument) { |
|
61 | 61 | self::updateGroups(); |
62 | 62 | } |
63 | 63 | |
@@ -67,7 +67,7 @@ discard block |
||
67 | 67 | $knownGroups = array_keys(self::getKnownGroups()); |
68 | 68 | $actualGroups = self::getGroupBE()->getGroups(); |
69 | 69 | |
70 | - if(empty($actualGroups) && empty($knownGroups)) { |
|
70 | + if (empty($actualGroups) && empty($knownGroups)) { |
|
71 | 71 | \OCP\Util::writeLog('user_ldap', |
72 | 72 | 'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.', |
73 | 73 | ILogger::INFO); |
@@ -99,26 +99,26 @@ discard block |
||
99 | 99 | SET `owncloudusers` = ? |
100 | 100 | WHERE `owncloudname` = ? |
101 | 101 | '); |
102 | - foreach($groups as $group) { |
|
102 | + foreach ($groups as $group) { |
|
103 | 103 | //we assume, that self::$groupsFromDB has been retrieved already |
104 | 104 | $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']); |
105 | 105 | $actualUsers = self::getGroupBE()->usersInGroup($group); |
106 | 106 | $hasChanged = false; |
107 | - foreach(array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
107 | + foreach (array_diff($knownUsers, $actualUsers) as $removedUser) { |
|
108 | 108 | \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group)); |
109 | 109 | \OCP\Util::writeLog('user_ldap', |
110 | 110 | 'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".', |
111 | 111 | ILogger::INFO); |
112 | 112 | $hasChanged = true; |
113 | 113 | } |
114 | - foreach(array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
114 | + foreach (array_diff($actualUsers, $knownUsers) as $addedUser) { |
|
115 | 115 | \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group)); |
116 | 116 | \OCP\Util::writeLog('user_ldap', |
117 | 117 | 'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".', |
118 | 118 | ILogger::INFO); |
119 | 119 | $hasChanged = true; |
120 | 120 | } |
121 | - if($hasChanged) { |
|
121 | + if ($hasChanged) { |
|
122 | 122 | $query->execute(array(serialize($actualUsers), $group)); |
123 | 123 | } |
124 | 124 | } |
@@ -137,7 +137,7 @@ discard block |
||
137 | 137 | INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`) |
138 | 138 | VALUES (?, ?) |
139 | 139 | '); |
140 | - foreach($createdGroups as $createdGroup) { |
|
140 | + foreach ($createdGroups as $createdGroup) { |
|
141 | 141 | \OCP\Util::writeLog('user_ldap', |
142 | 142 | 'bgJ "updateGroups" – new group "'.$createdGroup.'" found.', |
143 | 143 | ILogger::INFO); |
@@ -159,7 +159,7 @@ discard block |
||
159 | 159 | FROM `*PREFIX*ldap_group_members` |
160 | 160 | WHERE `owncloudname` = ? |
161 | 161 | '); |
162 | - foreach($removedGroups as $removedGroup) { |
|
162 | + foreach ($removedGroups as $removedGroup) { |
|
163 | 163 | \OCP\Util::writeLog('user_ldap', |
164 | 164 | 'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.', |
165 | 165 | ILogger::INFO); |
@@ -174,13 +174,13 @@ discard block |
||
174 | 174 | * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy |
175 | 175 | */ |
176 | 176 | static private function getGroupBE() { |
177 | - if(!is_null(self::$groupBE)) { |
|
177 | + if (!is_null(self::$groupBE)) { |
|
178 | 178 | return self::$groupBE; |
179 | 179 | } |
180 | 180 | $helper = new Helper(\OC::$server->getConfig()); |
181 | 181 | $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
182 | 182 | $ldapWrapper = new LDAP(); |
183 | - if(count($configPrefixes) === 1) { |
|
183 | + if (count($configPrefixes) === 1) { |
|
184 | 184 | //avoid the proxy when there is only one LDAP server configured |
185 | 185 | $dbc = \OC::$server->getDatabaseConnection(); |
186 | 186 | $userManager = new Manager( |
@@ -210,7 +210,7 @@ discard block |
||
210 | 210 | * @return array |
211 | 211 | */ |
212 | 212 | static private function getKnownGroups() { |
213 | - if(is_array(self::$groupsFromDB)) { |
|
213 | + if (is_array(self::$groupsFromDB)) { |
|
214 | 214 | return self::$groupsFromDB; |
215 | 215 | } |
216 | 216 | $query = \OC_DB::prepare(' |
@@ -219,7 +219,7 @@ discard block |
||
219 | 219 | '); |
220 | 220 | $result = $query->execute()->fetchAll(); |
221 | 221 | self::$groupsFromDB = array(); |
222 | - foreach($result as $dataset) { |
|
222 | + foreach ($result as $dataset) { |
|
223 | 223 | self::$groupsFromDB[$dataset['owncloudname']] = $dataset; |
224 | 224 | } |
225 | 225 |
@@ -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 = '') { |
@@ -39,427 +39,427 @@ |
||
39 | 39 | * Class to combine all the configuration options ownCloud offers |
40 | 40 | */ |
41 | 41 | class AllConfig implements \OCP\IConfig { |
42 | - /** @var SystemConfig */ |
|
43 | - private $systemConfig; |
|
44 | - |
|
45 | - /** @var IDBConnection */ |
|
46 | - private $connection; |
|
47 | - |
|
48 | - /** |
|
49 | - * 3 dimensional array with the following structure: |
|
50 | - * [ $userId => |
|
51 | - * [ $appId => |
|
52 | - * [ $key => $value ] |
|
53 | - * ] |
|
54 | - * ] |
|
55 | - * |
|
56 | - * database table: preferences |
|
57 | - * |
|
58 | - * methods that use this: |
|
59 | - * - setUserValue |
|
60 | - * - getUserValue |
|
61 | - * - getUserKeys |
|
62 | - * - deleteUserValue |
|
63 | - * - deleteAllUserValues |
|
64 | - * - deleteAppFromAllUsers |
|
65 | - * |
|
66 | - * @var CappedMemoryCache $userCache |
|
67 | - */ |
|
68 | - private $userCache; |
|
69 | - |
|
70 | - /** |
|
71 | - * @param SystemConfig $systemConfig |
|
72 | - */ |
|
73 | - public function __construct(SystemConfig $systemConfig) { |
|
74 | - $this->userCache = new CappedMemoryCache(); |
|
75 | - $this->systemConfig = $systemConfig; |
|
76 | - } |
|
77 | - |
|
78 | - /** |
|
79 | - * TODO - FIXME This fixes an issue with base.php that cause cyclic |
|
80 | - * dependencies, especially with autoconfig setup |
|
81 | - * |
|
82 | - * Replace this by properly injected database connection. Currently the |
|
83 | - * base.php triggers the getDatabaseConnection too early which causes in |
|
84 | - * autoconfig setup case a too early distributed database connection and |
|
85 | - * the autoconfig then needs to reinit all already initialized dependencies |
|
86 | - * that use the database connection. |
|
87 | - * |
|
88 | - * otherwise a SQLite database is created in the wrong directory |
|
89 | - * because the database connection was created with an uninitialized config |
|
90 | - */ |
|
91 | - private function fixDIInit() { |
|
92 | - if($this->connection === null) { |
|
93 | - $this->connection = \OC::$server->getDatabaseConnection(); |
|
94 | - } |
|
95 | - } |
|
96 | - |
|
97 | - /** |
|
98 | - * Sets and deletes system wide values |
|
99 | - * |
|
100 | - * @param array $configs Associative array with `key => value` pairs |
|
101 | - * If value is null, the config key will be deleted |
|
102 | - */ |
|
103 | - public function setSystemValues(array $configs) { |
|
104 | - $this->systemConfig->setValues($configs); |
|
105 | - } |
|
106 | - |
|
107 | - /** |
|
108 | - * Sets a new system wide value |
|
109 | - * |
|
110 | - * @param string $key the key of the value, under which will be saved |
|
111 | - * @param mixed $value the value that should be stored |
|
112 | - */ |
|
113 | - public function setSystemValue($key, $value) { |
|
114 | - $this->systemConfig->setValue($key, $value); |
|
115 | - } |
|
116 | - |
|
117 | - /** |
|
118 | - * Looks up a system wide defined value |
|
119 | - * |
|
120 | - * @param string $key the key of the value, under which it was saved |
|
121 | - * @param mixed $default the default value to be returned if the value isn't set |
|
122 | - * @return mixed the value or $default |
|
123 | - */ |
|
124 | - public function getSystemValue($key, $default = '') { |
|
125 | - return $this->systemConfig->getValue($key, $default); |
|
126 | - } |
|
127 | - |
|
128 | - /** |
|
129 | - * Looks up a system wide defined value and filters out sensitive data |
|
130 | - * |
|
131 | - * @param string $key the key of the value, under which it was saved |
|
132 | - * @param mixed $default the default value to be returned if the value isn't set |
|
133 | - * @return mixed the value or $default |
|
134 | - */ |
|
135 | - public function getFilteredSystemValue($key, $default = '') { |
|
136 | - return $this->systemConfig->getFilteredValue($key, $default); |
|
137 | - } |
|
138 | - |
|
139 | - /** |
|
140 | - * Delete a system wide defined value |
|
141 | - * |
|
142 | - * @param string $key the key of the value, under which it was saved |
|
143 | - */ |
|
144 | - public function deleteSystemValue($key) { |
|
145 | - $this->systemConfig->deleteValue($key); |
|
146 | - } |
|
147 | - |
|
148 | - /** |
|
149 | - * Get all keys stored for an app |
|
150 | - * |
|
151 | - * @param string $appName the appName that we stored the value under |
|
152 | - * @return string[] the keys stored for the app |
|
153 | - */ |
|
154 | - public function getAppKeys($appName) { |
|
155 | - return \OC::$server->query(\OC\AppConfig::class)->getKeys($appName); |
|
156 | - } |
|
157 | - |
|
158 | - /** |
|
159 | - * Writes a new app wide value |
|
160 | - * |
|
161 | - * @param string $appName the appName that we want to store the value under |
|
162 | - * @param string $key the key of the value, under which will be saved |
|
163 | - * @param string|float|int $value the value that should be stored |
|
164 | - */ |
|
165 | - public function setAppValue($appName, $key, $value) { |
|
166 | - \OC::$server->query(\OC\AppConfig::class)->setValue($appName, $key, $value); |
|
167 | - } |
|
168 | - |
|
169 | - /** |
|
170 | - * Looks up an app wide defined value |
|
171 | - * |
|
172 | - * @param string $appName the appName that we stored the value under |
|
173 | - * @param string $key the key of the value, under which it was saved |
|
174 | - * @param string $default the default value to be returned if the value isn't set |
|
175 | - * @return string the saved value |
|
176 | - */ |
|
177 | - public function getAppValue($appName, $key, $default = '') { |
|
178 | - return \OC::$server->query(\OC\AppConfig::class)->getValue($appName, $key, $default); |
|
179 | - } |
|
180 | - |
|
181 | - /** |
|
182 | - * Delete an app wide defined value |
|
183 | - * |
|
184 | - * @param string $appName the appName that we stored the value under |
|
185 | - * @param string $key the key of the value, under which it was saved |
|
186 | - */ |
|
187 | - public function deleteAppValue($appName, $key) { |
|
188 | - \OC::$server->query(\OC\AppConfig::class)->deleteKey($appName, $key); |
|
189 | - } |
|
190 | - |
|
191 | - /** |
|
192 | - * Removes all keys in appconfig belonging to the app |
|
193 | - * |
|
194 | - * @param string $appName the appName the configs are stored under |
|
195 | - */ |
|
196 | - public function deleteAppValues($appName) { |
|
197 | - \OC::$server->query(\OC\AppConfig::class)->deleteApp($appName); |
|
198 | - } |
|
199 | - |
|
200 | - |
|
201 | - /** |
|
202 | - * Set a user defined value |
|
203 | - * |
|
204 | - * @param string $userId the userId of the user that we want to store the value under |
|
205 | - * @param string $appName the appName that we want to store the value under |
|
206 | - * @param string $key the key under which the value is being stored |
|
207 | - * @param string|float|int $value the value that you want to store |
|
208 | - * @param string $preCondition only update if the config value was previously the value passed as $preCondition |
|
209 | - * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met |
|
210 | - * @throws \UnexpectedValueException when trying to store an unexpected value |
|
211 | - */ |
|
212 | - public function setUserValue($userId, $appName, $key, $value, $preCondition = null) { |
|
213 | - if (!is_int($value) && !is_float($value) && !is_string($value)) { |
|
214 | - throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value'); |
|
215 | - } |
|
216 | - |
|
217 | - // TODO - FIXME |
|
218 | - $this->fixDIInit(); |
|
219 | - |
|
220 | - $prevValue = $this->getUserValue($userId, $appName, $key, null); |
|
221 | - |
|
222 | - if ($prevValue !== null) { |
|
223 | - if ($prevValue === (string)$value) { |
|
224 | - return; |
|
225 | - } else if ($preCondition !== null && $prevValue !== (string)$preCondition) { |
|
226 | - throw new PreConditionNotMetException(); |
|
227 | - } else { |
|
228 | - $qb = $this->connection->getQueryBuilder(); |
|
229 | - $qb->update('preferences') |
|
230 | - ->set('configvalue', $qb->createNamedParameter($value)) |
|
231 | - ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) |
|
232 | - ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName))) |
|
233 | - ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key))); |
|
234 | - $qb->execute(); |
|
235 | - |
|
236 | - $this->userCache[$userId][$appName][$key] = (string)$value; |
|
237 | - return; |
|
238 | - } |
|
239 | - } |
|
240 | - |
|
241 | - $preconditionArray = []; |
|
242 | - if (isset($preCondition)) { |
|
243 | - $preconditionArray = [ |
|
244 | - 'configvalue' => $preCondition, |
|
245 | - ]; |
|
246 | - } |
|
247 | - |
|
248 | - $this->connection->setValues('preferences', [ |
|
249 | - 'userid' => $userId, |
|
250 | - 'appid' => $appName, |
|
251 | - 'configkey' => $key, |
|
252 | - ], [ |
|
253 | - 'configvalue' => $value, |
|
254 | - ], $preconditionArray); |
|
255 | - |
|
256 | - // only add to the cache if we already loaded data for the user |
|
257 | - if (isset($this->userCache[$userId])) { |
|
258 | - if (!isset($this->userCache[$userId][$appName])) { |
|
259 | - $this->userCache[$userId][$appName] = array(); |
|
260 | - } |
|
261 | - $this->userCache[$userId][$appName][$key] = (string)$value; |
|
262 | - } |
|
263 | - } |
|
264 | - |
|
265 | - /** |
|
266 | - * Getting a user defined value |
|
267 | - * |
|
268 | - * @param string $userId the userId of the user that we want to store the value under |
|
269 | - * @param string $appName the appName that we stored the value under |
|
270 | - * @param string $key the key under which the value is being stored |
|
271 | - * @param mixed $default the default value to be returned if the value isn't set |
|
272 | - * @return string |
|
273 | - */ |
|
274 | - public function getUserValue($userId, $appName, $key, $default = '') { |
|
275 | - $data = $this->getUserValues($userId); |
|
276 | - if (isset($data[$appName]) and isset($data[$appName][$key])) { |
|
277 | - return $data[$appName][$key]; |
|
278 | - } else { |
|
279 | - return $default; |
|
280 | - } |
|
281 | - } |
|
282 | - |
|
283 | - /** |
|
284 | - * Get the keys of all stored by an app for the user |
|
285 | - * |
|
286 | - * @param string $userId the userId of the user that we want to store the value under |
|
287 | - * @param string $appName the appName that we stored the value under |
|
288 | - * @return string[] |
|
289 | - */ |
|
290 | - public function getUserKeys($userId, $appName) { |
|
291 | - $data = $this->getUserValues($userId); |
|
292 | - if (isset($data[$appName])) { |
|
293 | - return array_keys($data[$appName]); |
|
294 | - } else { |
|
295 | - return array(); |
|
296 | - } |
|
297 | - } |
|
298 | - |
|
299 | - /** |
|
300 | - * Delete a user value |
|
301 | - * |
|
302 | - * @param string $userId the userId of the user that we want to store the value under |
|
303 | - * @param string $appName the appName that we stored the value under |
|
304 | - * @param string $key the key under which the value is being stored |
|
305 | - */ |
|
306 | - public function deleteUserValue($userId, $appName, $key) { |
|
307 | - // TODO - FIXME |
|
308 | - $this->fixDIInit(); |
|
309 | - |
|
310 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
311 | - 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; |
|
312 | - $this->connection->executeUpdate($sql, array($userId, $appName, $key)); |
|
313 | - |
|
314 | - if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) { |
|
315 | - unset($this->userCache[$userId][$appName][$key]); |
|
316 | - } |
|
317 | - } |
|
318 | - |
|
319 | - /** |
|
320 | - * Delete all user values |
|
321 | - * |
|
322 | - * @param string $userId the userId of the user that we want to remove all values from |
|
323 | - */ |
|
324 | - public function deleteAllUserValues($userId) { |
|
325 | - // TODO - FIXME |
|
326 | - $this->fixDIInit(); |
|
327 | - |
|
328 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
329 | - 'WHERE `userid` = ?'; |
|
330 | - $this->connection->executeUpdate($sql, array($userId)); |
|
331 | - |
|
332 | - unset($this->userCache[$userId]); |
|
333 | - } |
|
334 | - |
|
335 | - /** |
|
336 | - * Delete all user related values of one app |
|
337 | - * |
|
338 | - * @param string $appName the appName of the app that we want to remove all values from |
|
339 | - */ |
|
340 | - public function deleteAppFromAllUsers($appName) { |
|
341 | - // TODO - FIXME |
|
342 | - $this->fixDIInit(); |
|
343 | - |
|
344 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
345 | - 'WHERE `appid` = ?'; |
|
346 | - $this->connection->executeUpdate($sql, array($appName)); |
|
347 | - |
|
348 | - foreach ($this->userCache as &$userCache) { |
|
349 | - unset($userCache[$appName]); |
|
350 | - } |
|
351 | - } |
|
352 | - |
|
353 | - /** |
|
354 | - * Returns all user configs sorted by app of one user |
|
355 | - * |
|
356 | - * @param string $userId the user ID to get the app configs from |
|
357 | - * @return array[] - 2 dimensional array with the following structure: |
|
358 | - * [ $appId => |
|
359 | - * [ $key => $value ] |
|
360 | - * ] |
|
361 | - */ |
|
362 | - private function getUserValues($userId) { |
|
363 | - if (isset($this->userCache[$userId])) { |
|
364 | - return $this->userCache[$userId]; |
|
365 | - } |
|
366 | - if ($userId === null || $userId === '') { |
|
367 | - $this->userCache[$userId]=array(); |
|
368 | - return $this->userCache[$userId]; |
|
369 | - } |
|
370 | - |
|
371 | - // TODO - FIXME |
|
372 | - $this->fixDIInit(); |
|
373 | - |
|
374 | - $data = array(); |
|
375 | - $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; |
|
376 | - $result = $this->connection->executeQuery($query, array($userId)); |
|
377 | - while ($row = $result->fetch()) { |
|
378 | - $appId = $row['appid']; |
|
379 | - if (!isset($data[$appId])) { |
|
380 | - $data[$appId] = array(); |
|
381 | - } |
|
382 | - $data[$appId][$row['configkey']] = $row['configvalue']; |
|
383 | - } |
|
384 | - $this->userCache[$userId] = $data; |
|
385 | - return $data; |
|
386 | - } |
|
387 | - |
|
388 | - /** |
|
389 | - * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs. |
|
390 | - * |
|
391 | - * @param string $appName app to get the value for |
|
392 | - * @param string $key the key to get the value for |
|
393 | - * @param array $userIds the user IDs to fetch the values for |
|
394 | - * @return array Mapped values: userId => value |
|
395 | - */ |
|
396 | - public function getUserValueForUsers($appName, $key, $userIds) { |
|
397 | - // TODO - FIXME |
|
398 | - $this->fixDIInit(); |
|
399 | - |
|
400 | - if (empty($userIds) || !is_array($userIds)) { |
|
401 | - return array(); |
|
402 | - } |
|
403 | - |
|
404 | - $chunkedUsers = array_chunk($userIds, 50, true); |
|
405 | - $placeholders50 = implode(',', array_fill(0, 50, '?')); |
|
406 | - |
|
407 | - $userValues = array(); |
|
408 | - foreach ($chunkedUsers as $chunk) { |
|
409 | - $queryParams = $chunk; |
|
410 | - // create [$app, $key, $chunkedUsers] |
|
411 | - array_unshift($queryParams, $key); |
|
412 | - array_unshift($queryParams, $appName); |
|
413 | - |
|
414 | - $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?')); |
|
415 | - |
|
416 | - $query = 'SELECT `userid`, `configvalue` ' . |
|
417 | - 'FROM `*PREFIX*preferences` ' . |
|
418 | - 'WHERE `appid` = ? AND `configkey` = ? ' . |
|
419 | - 'AND `userid` IN (' . $placeholders . ')'; |
|
420 | - $result = $this->connection->executeQuery($query, $queryParams); |
|
421 | - |
|
422 | - while ($row = $result->fetch()) { |
|
423 | - $userValues[$row['userid']] = $row['configvalue']; |
|
424 | - } |
|
425 | - } |
|
426 | - |
|
427 | - return $userValues; |
|
428 | - } |
|
429 | - |
|
430 | - /** |
|
431 | - * Determines the users that have the given value set for a specific app-key-pair |
|
432 | - * |
|
433 | - * @param string $appName the app to get the user for |
|
434 | - * @param string $key the key to get the user for |
|
435 | - * @param string $value the value to get the user for |
|
436 | - * @return array of user IDs |
|
437 | - */ |
|
438 | - public function getUsersForUserValue($appName, $key, $value) { |
|
439 | - // TODO - FIXME |
|
440 | - $this->fixDIInit(); |
|
441 | - |
|
442 | - $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . |
|
443 | - 'WHERE `appid` = ? AND `configkey` = ? '; |
|
444 | - |
|
445 | - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
446 | - //oracle hack: need to explicitly cast CLOB to CHAR for comparison |
|
447 | - $sql .= 'AND to_char(`configvalue`) = ?'; |
|
448 | - } else { |
|
449 | - $sql .= 'AND `configvalue` = ?'; |
|
450 | - } |
|
451 | - |
|
452 | - $result = $this->connection->executeQuery($sql, array($appName, $key, $value)); |
|
453 | - |
|
454 | - $userIDs = array(); |
|
455 | - while ($row = $result->fetch()) { |
|
456 | - $userIDs[] = $row['userid']; |
|
457 | - } |
|
458 | - |
|
459 | - return $userIDs; |
|
460 | - } |
|
461 | - |
|
462 | - public function getSystemConfig() { |
|
463 | - return $this->systemConfig; |
|
464 | - } |
|
42 | + /** @var SystemConfig */ |
|
43 | + private $systemConfig; |
|
44 | + |
|
45 | + /** @var IDBConnection */ |
|
46 | + private $connection; |
|
47 | + |
|
48 | + /** |
|
49 | + * 3 dimensional array with the following structure: |
|
50 | + * [ $userId => |
|
51 | + * [ $appId => |
|
52 | + * [ $key => $value ] |
|
53 | + * ] |
|
54 | + * ] |
|
55 | + * |
|
56 | + * database table: preferences |
|
57 | + * |
|
58 | + * methods that use this: |
|
59 | + * - setUserValue |
|
60 | + * - getUserValue |
|
61 | + * - getUserKeys |
|
62 | + * - deleteUserValue |
|
63 | + * - deleteAllUserValues |
|
64 | + * - deleteAppFromAllUsers |
|
65 | + * |
|
66 | + * @var CappedMemoryCache $userCache |
|
67 | + */ |
|
68 | + private $userCache; |
|
69 | + |
|
70 | + /** |
|
71 | + * @param SystemConfig $systemConfig |
|
72 | + */ |
|
73 | + public function __construct(SystemConfig $systemConfig) { |
|
74 | + $this->userCache = new CappedMemoryCache(); |
|
75 | + $this->systemConfig = $systemConfig; |
|
76 | + } |
|
77 | + |
|
78 | + /** |
|
79 | + * TODO - FIXME This fixes an issue with base.php that cause cyclic |
|
80 | + * dependencies, especially with autoconfig setup |
|
81 | + * |
|
82 | + * Replace this by properly injected database connection. Currently the |
|
83 | + * base.php triggers the getDatabaseConnection too early which causes in |
|
84 | + * autoconfig setup case a too early distributed database connection and |
|
85 | + * the autoconfig then needs to reinit all already initialized dependencies |
|
86 | + * that use the database connection. |
|
87 | + * |
|
88 | + * otherwise a SQLite database is created in the wrong directory |
|
89 | + * because the database connection was created with an uninitialized config |
|
90 | + */ |
|
91 | + private function fixDIInit() { |
|
92 | + if($this->connection === null) { |
|
93 | + $this->connection = \OC::$server->getDatabaseConnection(); |
|
94 | + } |
|
95 | + } |
|
96 | + |
|
97 | + /** |
|
98 | + * Sets and deletes system wide values |
|
99 | + * |
|
100 | + * @param array $configs Associative array with `key => value` pairs |
|
101 | + * If value is null, the config key will be deleted |
|
102 | + */ |
|
103 | + public function setSystemValues(array $configs) { |
|
104 | + $this->systemConfig->setValues($configs); |
|
105 | + } |
|
106 | + |
|
107 | + /** |
|
108 | + * Sets a new system wide value |
|
109 | + * |
|
110 | + * @param string $key the key of the value, under which will be saved |
|
111 | + * @param mixed $value the value that should be stored |
|
112 | + */ |
|
113 | + public function setSystemValue($key, $value) { |
|
114 | + $this->systemConfig->setValue($key, $value); |
|
115 | + } |
|
116 | + |
|
117 | + /** |
|
118 | + * Looks up a system wide defined value |
|
119 | + * |
|
120 | + * @param string $key the key of the value, under which it was saved |
|
121 | + * @param mixed $default the default value to be returned if the value isn't set |
|
122 | + * @return mixed the value or $default |
|
123 | + */ |
|
124 | + public function getSystemValue($key, $default = '') { |
|
125 | + return $this->systemConfig->getValue($key, $default); |
|
126 | + } |
|
127 | + |
|
128 | + /** |
|
129 | + * Looks up a system wide defined value and filters out sensitive data |
|
130 | + * |
|
131 | + * @param string $key the key of the value, under which it was saved |
|
132 | + * @param mixed $default the default value to be returned if the value isn't set |
|
133 | + * @return mixed the value or $default |
|
134 | + */ |
|
135 | + public function getFilteredSystemValue($key, $default = '') { |
|
136 | + return $this->systemConfig->getFilteredValue($key, $default); |
|
137 | + } |
|
138 | + |
|
139 | + /** |
|
140 | + * Delete a system wide defined value |
|
141 | + * |
|
142 | + * @param string $key the key of the value, under which it was saved |
|
143 | + */ |
|
144 | + public function deleteSystemValue($key) { |
|
145 | + $this->systemConfig->deleteValue($key); |
|
146 | + } |
|
147 | + |
|
148 | + /** |
|
149 | + * Get all keys stored for an app |
|
150 | + * |
|
151 | + * @param string $appName the appName that we stored the value under |
|
152 | + * @return string[] the keys stored for the app |
|
153 | + */ |
|
154 | + public function getAppKeys($appName) { |
|
155 | + return \OC::$server->query(\OC\AppConfig::class)->getKeys($appName); |
|
156 | + } |
|
157 | + |
|
158 | + /** |
|
159 | + * Writes a new app wide value |
|
160 | + * |
|
161 | + * @param string $appName the appName that we want to store the value under |
|
162 | + * @param string $key the key of the value, under which will be saved |
|
163 | + * @param string|float|int $value the value that should be stored |
|
164 | + */ |
|
165 | + public function setAppValue($appName, $key, $value) { |
|
166 | + \OC::$server->query(\OC\AppConfig::class)->setValue($appName, $key, $value); |
|
167 | + } |
|
168 | + |
|
169 | + /** |
|
170 | + * Looks up an app wide defined value |
|
171 | + * |
|
172 | + * @param string $appName the appName that we stored the value under |
|
173 | + * @param string $key the key of the value, under which it was saved |
|
174 | + * @param string $default the default value to be returned if the value isn't set |
|
175 | + * @return string the saved value |
|
176 | + */ |
|
177 | + public function getAppValue($appName, $key, $default = '') { |
|
178 | + return \OC::$server->query(\OC\AppConfig::class)->getValue($appName, $key, $default); |
|
179 | + } |
|
180 | + |
|
181 | + /** |
|
182 | + * Delete an app wide defined value |
|
183 | + * |
|
184 | + * @param string $appName the appName that we stored the value under |
|
185 | + * @param string $key the key of the value, under which it was saved |
|
186 | + */ |
|
187 | + public function deleteAppValue($appName, $key) { |
|
188 | + \OC::$server->query(\OC\AppConfig::class)->deleteKey($appName, $key); |
|
189 | + } |
|
190 | + |
|
191 | + /** |
|
192 | + * Removes all keys in appconfig belonging to the app |
|
193 | + * |
|
194 | + * @param string $appName the appName the configs are stored under |
|
195 | + */ |
|
196 | + public function deleteAppValues($appName) { |
|
197 | + \OC::$server->query(\OC\AppConfig::class)->deleteApp($appName); |
|
198 | + } |
|
199 | + |
|
200 | + |
|
201 | + /** |
|
202 | + * Set a user defined value |
|
203 | + * |
|
204 | + * @param string $userId the userId of the user that we want to store the value under |
|
205 | + * @param string $appName the appName that we want to store the value under |
|
206 | + * @param string $key the key under which the value is being stored |
|
207 | + * @param string|float|int $value the value that you want to store |
|
208 | + * @param string $preCondition only update if the config value was previously the value passed as $preCondition |
|
209 | + * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met |
|
210 | + * @throws \UnexpectedValueException when trying to store an unexpected value |
|
211 | + */ |
|
212 | + public function setUserValue($userId, $appName, $key, $value, $preCondition = null) { |
|
213 | + if (!is_int($value) && !is_float($value) && !is_string($value)) { |
|
214 | + throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value'); |
|
215 | + } |
|
216 | + |
|
217 | + // TODO - FIXME |
|
218 | + $this->fixDIInit(); |
|
219 | + |
|
220 | + $prevValue = $this->getUserValue($userId, $appName, $key, null); |
|
221 | + |
|
222 | + if ($prevValue !== null) { |
|
223 | + if ($prevValue === (string)$value) { |
|
224 | + return; |
|
225 | + } else if ($preCondition !== null && $prevValue !== (string)$preCondition) { |
|
226 | + throw new PreConditionNotMetException(); |
|
227 | + } else { |
|
228 | + $qb = $this->connection->getQueryBuilder(); |
|
229 | + $qb->update('preferences') |
|
230 | + ->set('configvalue', $qb->createNamedParameter($value)) |
|
231 | + ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) |
|
232 | + ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName))) |
|
233 | + ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key))); |
|
234 | + $qb->execute(); |
|
235 | + |
|
236 | + $this->userCache[$userId][$appName][$key] = (string)$value; |
|
237 | + return; |
|
238 | + } |
|
239 | + } |
|
240 | + |
|
241 | + $preconditionArray = []; |
|
242 | + if (isset($preCondition)) { |
|
243 | + $preconditionArray = [ |
|
244 | + 'configvalue' => $preCondition, |
|
245 | + ]; |
|
246 | + } |
|
247 | + |
|
248 | + $this->connection->setValues('preferences', [ |
|
249 | + 'userid' => $userId, |
|
250 | + 'appid' => $appName, |
|
251 | + 'configkey' => $key, |
|
252 | + ], [ |
|
253 | + 'configvalue' => $value, |
|
254 | + ], $preconditionArray); |
|
255 | + |
|
256 | + // only add to the cache if we already loaded data for the user |
|
257 | + if (isset($this->userCache[$userId])) { |
|
258 | + if (!isset($this->userCache[$userId][$appName])) { |
|
259 | + $this->userCache[$userId][$appName] = array(); |
|
260 | + } |
|
261 | + $this->userCache[$userId][$appName][$key] = (string)$value; |
|
262 | + } |
|
263 | + } |
|
264 | + |
|
265 | + /** |
|
266 | + * Getting a user defined value |
|
267 | + * |
|
268 | + * @param string $userId the userId of the user that we want to store the value under |
|
269 | + * @param string $appName the appName that we stored the value under |
|
270 | + * @param string $key the key under which the value is being stored |
|
271 | + * @param mixed $default the default value to be returned if the value isn't set |
|
272 | + * @return string |
|
273 | + */ |
|
274 | + public function getUserValue($userId, $appName, $key, $default = '') { |
|
275 | + $data = $this->getUserValues($userId); |
|
276 | + if (isset($data[$appName]) and isset($data[$appName][$key])) { |
|
277 | + return $data[$appName][$key]; |
|
278 | + } else { |
|
279 | + return $default; |
|
280 | + } |
|
281 | + } |
|
282 | + |
|
283 | + /** |
|
284 | + * Get the keys of all stored by an app for the user |
|
285 | + * |
|
286 | + * @param string $userId the userId of the user that we want to store the value under |
|
287 | + * @param string $appName the appName that we stored the value under |
|
288 | + * @return string[] |
|
289 | + */ |
|
290 | + public function getUserKeys($userId, $appName) { |
|
291 | + $data = $this->getUserValues($userId); |
|
292 | + if (isset($data[$appName])) { |
|
293 | + return array_keys($data[$appName]); |
|
294 | + } else { |
|
295 | + return array(); |
|
296 | + } |
|
297 | + } |
|
298 | + |
|
299 | + /** |
|
300 | + * Delete a user value |
|
301 | + * |
|
302 | + * @param string $userId the userId of the user that we want to store the value under |
|
303 | + * @param string $appName the appName that we stored the value under |
|
304 | + * @param string $key the key under which the value is being stored |
|
305 | + */ |
|
306 | + public function deleteUserValue($userId, $appName, $key) { |
|
307 | + // TODO - FIXME |
|
308 | + $this->fixDIInit(); |
|
309 | + |
|
310 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
311 | + 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; |
|
312 | + $this->connection->executeUpdate($sql, array($userId, $appName, $key)); |
|
313 | + |
|
314 | + if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) { |
|
315 | + unset($this->userCache[$userId][$appName][$key]); |
|
316 | + } |
|
317 | + } |
|
318 | + |
|
319 | + /** |
|
320 | + * Delete all user values |
|
321 | + * |
|
322 | + * @param string $userId the userId of the user that we want to remove all values from |
|
323 | + */ |
|
324 | + public function deleteAllUserValues($userId) { |
|
325 | + // TODO - FIXME |
|
326 | + $this->fixDIInit(); |
|
327 | + |
|
328 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
329 | + 'WHERE `userid` = ?'; |
|
330 | + $this->connection->executeUpdate($sql, array($userId)); |
|
331 | + |
|
332 | + unset($this->userCache[$userId]); |
|
333 | + } |
|
334 | + |
|
335 | + /** |
|
336 | + * Delete all user related values of one app |
|
337 | + * |
|
338 | + * @param string $appName the appName of the app that we want to remove all values from |
|
339 | + */ |
|
340 | + public function deleteAppFromAllUsers($appName) { |
|
341 | + // TODO - FIXME |
|
342 | + $this->fixDIInit(); |
|
343 | + |
|
344 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
345 | + 'WHERE `appid` = ?'; |
|
346 | + $this->connection->executeUpdate($sql, array($appName)); |
|
347 | + |
|
348 | + foreach ($this->userCache as &$userCache) { |
|
349 | + unset($userCache[$appName]); |
|
350 | + } |
|
351 | + } |
|
352 | + |
|
353 | + /** |
|
354 | + * Returns all user configs sorted by app of one user |
|
355 | + * |
|
356 | + * @param string $userId the user ID to get the app configs from |
|
357 | + * @return array[] - 2 dimensional array with the following structure: |
|
358 | + * [ $appId => |
|
359 | + * [ $key => $value ] |
|
360 | + * ] |
|
361 | + */ |
|
362 | + private function getUserValues($userId) { |
|
363 | + if (isset($this->userCache[$userId])) { |
|
364 | + return $this->userCache[$userId]; |
|
365 | + } |
|
366 | + if ($userId === null || $userId === '') { |
|
367 | + $this->userCache[$userId]=array(); |
|
368 | + return $this->userCache[$userId]; |
|
369 | + } |
|
370 | + |
|
371 | + // TODO - FIXME |
|
372 | + $this->fixDIInit(); |
|
373 | + |
|
374 | + $data = array(); |
|
375 | + $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; |
|
376 | + $result = $this->connection->executeQuery($query, array($userId)); |
|
377 | + while ($row = $result->fetch()) { |
|
378 | + $appId = $row['appid']; |
|
379 | + if (!isset($data[$appId])) { |
|
380 | + $data[$appId] = array(); |
|
381 | + } |
|
382 | + $data[$appId][$row['configkey']] = $row['configvalue']; |
|
383 | + } |
|
384 | + $this->userCache[$userId] = $data; |
|
385 | + return $data; |
|
386 | + } |
|
387 | + |
|
388 | + /** |
|
389 | + * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs. |
|
390 | + * |
|
391 | + * @param string $appName app to get the value for |
|
392 | + * @param string $key the key to get the value for |
|
393 | + * @param array $userIds the user IDs to fetch the values for |
|
394 | + * @return array Mapped values: userId => value |
|
395 | + */ |
|
396 | + public function getUserValueForUsers($appName, $key, $userIds) { |
|
397 | + // TODO - FIXME |
|
398 | + $this->fixDIInit(); |
|
399 | + |
|
400 | + if (empty($userIds) || !is_array($userIds)) { |
|
401 | + return array(); |
|
402 | + } |
|
403 | + |
|
404 | + $chunkedUsers = array_chunk($userIds, 50, true); |
|
405 | + $placeholders50 = implode(',', array_fill(0, 50, '?')); |
|
406 | + |
|
407 | + $userValues = array(); |
|
408 | + foreach ($chunkedUsers as $chunk) { |
|
409 | + $queryParams = $chunk; |
|
410 | + // create [$app, $key, $chunkedUsers] |
|
411 | + array_unshift($queryParams, $key); |
|
412 | + array_unshift($queryParams, $appName); |
|
413 | + |
|
414 | + $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?')); |
|
415 | + |
|
416 | + $query = 'SELECT `userid`, `configvalue` ' . |
|
417 | + 'FROM `*PREFIX*preferences` ' . |
|
418 | + 'WHERE `appid` = ? AND `configkey` = ? ' . |
|
419 | + 'AND `userid` IN (' . $placeholders . ')'; |
|
420 | + $result = $this->connection->executeQuery($query, $queryParams); |
|
421 | + |
|
422 | + while ($row = $result->fetch()) { |
|
423 | + $userValues[$row['userid']] = $row['configvalue']; |
|
424 | + } |
|
425 | + } |
|
426 | + |
|
427 | + return $userValues; |
|
428 | + } |
|
429 | + |
|
430 | + /** |
|
431 | + * Determines the users that have the given value set for a specific app-key-pair |
|
432 | + * |
|
433 | + * @param string $appName the app to get the user for |
|
434 | + * @param string $key the key to get the user for |
|
435 | + * @param string $value the value to get the user for |
|
436 | + * @return array of user IDs |
|
437 | + */ |
|
438 | + public function getUsersForUserValue($appName, $key, $value) { |
|
439 | + // TODO - FIXME |
|
440 | + $this->fixDIInit(); |
|
441 | + |
|
442 | + $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . |
|
443 | + 'WHERE `appid` = ? AND `configkey` = ? '; |
|
444 | + |
|
445 | + if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
446 | + //oracle hack: need to explicitly cast CLOB to CHAR for comparison |
|
447 | + $sql .= 'AND to_char(`configvalue`) = ?'; |
|
448 | + } else { |
|
449 | + $sql .= 'AND `configvalue` = ?'; |
|
450 | + } |
|
451 | + |
|
452 | + $result = $this->connection->executeQuery($sql, array($appName, $key, $value)); |
|
453 | + |
|
454 | + $userIDs = array(); |
|
455 | + while ($row = $result->fetch()) { |
|
456 | + $userIDs[] = $row['userid']; |
|
457 | + } |
|
458 | + |
|
459 | + return $userIDs; |
|
460 | + } |
|
461 | + |
|
462 | + public function getSystemConfig() { |
|
463 | + return $this->systemConfig; |
|
464 | + } |
|
465 | 465 | } |
@@ -89,7 +89,7 @@ discard block |
||
89 | 89 | * because the database connection was created with an uninitialized config |
90 | 90 | */ |
91 | 91 | private function fixDIInit() { |
92 | - if($this->connection === null) { |
|
92 | + if ($this->connection === null) { |
|
93 | 93 | $this->connection = \OC::$server->getDatabaseConnection(); |
94 | 94 | } |
95 | 95 | } |
@@ -220,9 +220,9 @@ discard block |
||
220 | 220 | $prevValue = $this->getUserValue($userId, $appName, $key, null); |
221 | 221 | |
222 | 222 | if ($prevValue !== null) { |
223 | - if ($prevValue === (string)$value) { |
|
223 | + if ($prevValue === (string) $value) { |
|
224 | 224 | return; |
225 | - } else if ($preCondition !== null && $prevValue !== (string)$preCondition) { |
|
225 | + } else if ($preCondition !== null && $prevValue !== (string) $preCondition) { |
|
226 | 226 | throw new PreConditionNotMetException(); |
227 | 227 | } else { |
228 | 228 | $qb = $this->connection->getQueryBuilder(); |
@@ -233,7 +233,7 @@ discard block |
||
233 | 233 | ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key))); |
234 | 234 | $qb->execute(); |
235 | 235 | |
236 | - $this->userCache[$userId][$appName][$key] = (string)$value; |
|
236 | + $this->userCache[$userId][$appName][$key] = (string) $value; |
|
237 | 237 | return; |
238 | 238 | } |
239 | 239 | } |
@@ -258,7 +258,7 @@ discard block |
||
258 | 258 | if (!isset($this->userCache[$userId][$appName])) { |
259 | 259 | $this->userCache[$userId][$appName] = array(); |
260 | 260 | } |
261 | - $this->userCache[$userId][$appName][$key] = (string)$value; |
|
261 | + $this->userCache[$userId][$appName][$key] = (string) $value; |
|
262 | 262 | } |
263 | 263 | } |
264 | 264 | |
@@ -307,7 +307,7 @@ discard block |
||
307 | 307 | // TODO - FIXME |
308 | 308 | $this->fixDIInit(); |
309 | 309 | |
310 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
310 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
311 | 311 | 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'; |
312 | 312 | $this->connection->executeUpdate($sql, array($userId, $appName, $key)); |
313 | 313 | |
@@ -325,7 +325,7 @@ discard block |
||
325 | 325 | // TODO - FIXME |
326 | 326 | $this->fixDIInit(); |
327 | 327 | |
328 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
328 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
329 | 329 | 'WHERE `userid` = ?'; |
330 | 330 | $this->connection->executeUpdate($sql, array($userId)); |
331 | 331 | |
@@ -341,7 +341,7 @@ discard block |
||
341 | 341 | // TODO - FIXME |
342 | 342 | $this->fixDIInit(); |
343 | 343 | |
344 | - $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
344 | + $sql = 'DELETE FROM `*PREFIX*preferences` '. |
|
345 | 345 | 'WHERE `appid` = ?'; |
346 | 346 | $this->connection->executeUpdate($sql, array($appName)); |
347 | 347 | |
@@ -364,7 +364,7 @@ discard block |
||
364 | 364 | return $this->userCache[$userId]; |
365 | 365 | } |
366 | 366 | if ($userId === null || $userId === '') { |
367 | - $this->userCache[$userId]=array(); |
|
367 | + $this->userCache[$userId] = array(); |
|
368 | 368 | return $this->userCache[$userId]; |
369 | 369 | } |
370 | 370 | |
@@ -411,12 +411,12 @@ discard block |
||
411 | 411 | array_unshift($queryParams, $key); |
412 | 412 | array_unshift($queryParams, $appName); |
413 | 413 | |
414 | - $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?')); |
|
414 | + $placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?')); |
|
415 | 415 | |
416 | - $query = 'SELECT `userid`, `configvalue` ' . |
|
417 | - 'FROM `*PREFIX*preferences` ' . |
|
418 | - 'WHERE `appid` = ? AND `configkey` = ? ' . |
|
419 | - 'AND `userid` IN (' . $placeholders . ')'; |
|
416 | + $query = 'SELECT `userid`, `configvalue` '. |
|
417 | + 'FROM `*PREFIX*preferences` '. |
|
418 | + 'WHERE `appid` = ? AND `configkey` = ? '. |
|
419 | + 'AND `userid` IN ('.$placeholders.')'; |
|
420 | 420 | $result = $this->connection->executeQuery($query, $queryParams); |
421 | 421 | |
422 | 422 | while ($row = $result->fetch()) { |
@@ -439,10 +439,10 @@ discard block |
||
439 | 439 | // TODO - FIXME |
440 | 440 | $this->fixDIInit(); |
441 | 441 | |
442 | - $sql = 'SELECT `userid` FROM `*PREFIX*preferences` ' . |
|
442 | + $sql = 'SELECT `userid` FROM `*PREFIX*preferences` '. |
|
443 | 443 | 'WHERE `appid` = ? AND `configkey` = ? '; |
444 | 444 | |
445 | - if($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
445 | + if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') { |
|
446 | 446 | //oracle hack: need to explicitly cast CLOB to CHAR for comparison |
447 | 447 | $sql .= 'AND to_char(`configvalue`) = ?'; |
448 | 448 | } 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(), |
@@ -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) { |
@@ -58,7 +58,7 @@ discard block |
||
58 | 58 | return parent::connect(); |
59 | 59 | } catch (DBALException $e) { |
60 | 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()); |
|
61 | + throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode()); |
|
62 | 62 | } |
63 | 63 | } |
64 | 64 | |
@@ -110,7 +110,7 @@ discard block |
||
110 | 110 | // 0 is the method where we use `getCallerBacktrace` |
111 | 111 | // 1 is the target method which uses the method we want to log |
112 | 112 | if (isset($traces[1])) { |
113 | - return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
113 | + return $traces[1]['file'].':'.$traces[1]['line']; |
|
114 | 114 | } |
115 | 115 | |
116 | 116 | return ''; |
@@ -156,7 +156,7 @@ discard block |
||
156 | 156 | * @param int $offset |
157 | 157 | * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
158 | 158 | */ |
159 | - public function prepare( $statement, $limit=null, $offset=null ) { |
|
159 | + public function prepare($statement, $limit = null, $offset = null) { |
|
160 | 160 | if ($limit === -1) { |
161 | 161 | $limit = null; |
162 | 162 | } |
@@ -321,7 +321,7 @@ discard block |
||
321 | 321 | throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
322 | 322 | } |
323 | 323 | |
324 | - $tableName = $this->tablePrefix . $tableName; |
|
324 | + $tableName = $this->tablePrefix.$tableName; |
|
325 | 325 | $this->lockedTable = $tableName; |
326 | 326 | $this->adapter->lockTable($tableName); |
327 | 327 | } |
@@ -342,11 +342,11 @@ discard block |
||
342 | 342 | * @return string |
343 | 343 | */ |
344 | 344 | public function getError() { |
345 | - $msg = $this->errorCode() . ': '; |
|
345 | + $msg = $this->errorCode().': '; |
|
346 | 346 | $errorInfo = $this->errorInfo(); |
347 | 347 | if (is_array($errorInfo)) { |
348 | - $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
349 | - $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
348 | + $msg .= 'SQLSTATE = '.$errorInfo[0].', '; |
|
349 | + $msg .= 'Driver Code = '.$errorInfo[1].', '; |
|
350 | 350 | $msg .= 'Driver Message = '.$errorInfo[2]; |
351 | 351 | } |
352 | 352 | return $msg; |
@@ -358,9 +358,9 @@ discard block |
||
358 | 358 | * @param string $table table name without the prefix |
359 | 359 | */ |
360 | 360 | public function dropTable($table) { |
361 | - $table = $this->tablePrefix . trim($table); |
|
361 | + $table = $this->tablePrefix.trim($table); |
|
362 | 362 | $schema = $this->getSchemaManager(); |
363 | - if($schema->tablesExist(array($table))) { |
|
363 | + if ($schema->tablesExist(array($table))) { |
|
364 | 364 | $schema->dropTable($table); |
365 | 365 | } |
366 | 366 | } |
@@ -371,8 +371,8 @@ discard block |
||
371 | 371 | * @param string $table table name without the prefix |
372 | 372 | * @return bool |
373 | 373 | */ |
374 | - public function tableExists($table){ |
|
375 | - $table = $this->tablePrefix . trim($table); |
|
374 | + public function tableExists($table) { |
|
375 | + $table = $this->tablePrefix.trim($table); |
|
376 | 376 | $schema = $this->getSchemaManager(); |
377 | 377 | return $schema->tablesExist(array($table)); |
378 | 378 | } |
@@ -383,7 +383,7 @@ discard block |
||
383 | 383 | * @return string |
384 | 384 | */ |
385 | 385 | protected function replaceTablePrefix($statement) { |
386 | - return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
386 | + return str_replace('*PREFIX*', $this->tablePrefix, $statement); |
|
387 | 387 | } |
388 | 388 | |
389 | 389 | /** |
@@ -44,405 +44,405 @@ |
||
44 | 44 | use OCP\PreConditionNotMetException; |
45 | 45 | |
46 | 46 | class Connection extends ReconnectWrapper implements IDBConnection { |
47 | - /** |
|
48 | - * @var string $tablePrefix |
|
49 | - */ |
|
50 | - protected $tablePrefix; |
|
51 | - |
|
52 | - /** |
|
53 | - * @var \OC\DB\Adapter $adapter |
|
54 | - */ |
|
55 | - protected $adapter; |
|
56 | - |
|
57 | - protected $lockedTable = null; |
|
58 | - |
|
59 | - public function connect() { |
|
60 | - try { |
|
61 | - return parent::connect(); |
|
62 | - } catch (DBALException $e) { |
|
63 | - // throw a new exception to prevent leaking info from the stacktrace |
|
64 | - throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
65 | - } |
|
66 | - } |
|
67 | - |
|
68 | - /** |
|
69 | - * Returns a QueryBuilder for the connection. |
|
70 | - * |
|
71 | - * @return \OCP\DB\QueryBuilder\IQueryBuilder |
|
72 | - */ |
|
73 | - public function getQueryBuilder() { |
|
74 | - return new QueryBuilder( |
|
75 | - $this, |
|
76 | - \OC::$server->getSystemConfig(), |
|
77 | - \OC::$server->getLogger() |
|
78 | - ); |
|
79 | - } |
|
80 | - |
|
81 | - /** |
|
82 | - * Gets the QueryBuilder for the connection. |
|
83 | - * |
|
84 | - * @return \Doctrine\DBAL\Query\QueryBuilder |
|
85 | - * @deprecated please use $this->getQueryBuilder() instead |
|
86 | - */ |
|
87 | - public function createQueryBuilder() { |
|
88 | - $backtrace = $this->getCallerBacktrace(); |
|
89 | - \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
90 | - return parent::createQueryBuilder(); |
|
91 | - } |
|
92 | - |
|
93 | - /** |
|
94 | - * Gets the ExpressionBuilder for the connection. |
|
95 | - * |
|
96 | - * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder |
|
97 | - * @deprecated please use $this->getQueryBuilder()->expr() instead |
|
98 | - */ |
|
99 | - public function getExpressionBuilder() { |
|
100 | - $backtrace = $this->getCallerBacktrace(); |
|
101 | - \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
102 | - return parent::getExpressionBuilder(); |
|
103 | - } |
|
104 | - |
|
105 | - /** |
|
106 | - * Get the file and line that called the method where `getCallerBacktrace()` was used |
|
107 | - * |
|
108 | - * @return string |
|
109 | - */ |
|
110 | - protected function getCallerBacktrace() { |
|
111 | - $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
|
112 | - |
|
113 | - // 0 is the method where we use `getCallerBacktrace` |
|
114 | - // 1 is the target method which uses the method we want to log |
|
115 | - if (isset($traces[1])) { |
|
116 | - return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
117 | - } |
|
118 | - |
|
119 | - return ''; |
|
120 | - } |
|
121 | - |
|
122 | - /** |
|
123 | - * @return string |
|
124 | - */ |
|
125 | - public function getPrefix() { |
|
126 | - return $this->tablePrefix; |
|
127 | - } |
|
128 | - |
|
129 | - /** |
|
130 | - * Initializes a new instance of the Connection class. |
|
131 | - * |
|
132 | - * @param array $params The connection parameters. |
|
133 | - * @param \Doctrine\DBAL\Driver $driver |
|
134 | - * @param \Doctrine\DBAL\Configuration $config |
|
135 | - * @param \Doctrine\Common\EventManager $eventManager |
|
136 | - * @throws \Exception |
|
137 | - */ |
|
138 | - public function __construct(array $params, Driver $driver, Configuration $config = null, |
|
139 | - EventManager $eventManager = null) |
|
140 | - { |
|
141 | - if (!isset($params['adapter'])) { |
|
142 | - throw new \Exception('adapter not set'); |
|
143 | - } |
|
144 | - if (!isset($params['tablePrefix'])) { |
|
145 | - throw new \Exception('tablePrefix not set'); |
|
146 | - } |
|
147 | - parent::__construct($params, $driver, $config, $eventManager); |
|
148 | - $this->adapter = new $params['adapter']($this); |
|
149 | - $this->tablePrefix = $params['tablePrefix']; |
|
150 | - |
|
151 | - parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED); |
|
152 | - } |
|
153 | - |
|
154 | - /** |
|
155 | - * Prepares an SQL statement. |
|
156 | - * |
|
157 | - * @param string $statement The SQL statement to prepare. |
|
158 | - * @param int $limit |
|
159 | - * @param int $offset |
|
160 | - * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
|
161 | - */ |
|
162 | - public function prepare( $statement, $limit=null, $offset=null ) { |
|
163 | - if ($limit === -1) { |
|
164 | - $limit = null; |
|
165 | - } |
|
166 | - if (!is_null($limit)) { |
|
167 | - $platform = $this->getDatabasePlatform(); |
|
168 | - $statement = $platform->modifyLimitQuery($statement, $limit, $offset); |
|
169 | - } |
|
170 | - $statement = $this->replaceTablePrefix($statement); |
|
171 | - $statement = $this->adapter->fixupStatement($statement); |
|
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 | - * @suppress SqlInjectionChecker |
|
278 | - */ |
|
279 | - public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { |
|
280 | - try { |
|
281 | - $insertQb = $this->getQueryBuilder(); |
|
282 | - $insertQb->insert($table) |
|
283 | - ->values( |
|
284 | - array_map(function($value) use ($insertQb) { |
|
285 | - return $insertQb->createNamedParameter($value, $this->getType($value)); |
|
286 | - }, array_merge($keys, $values)) |
|
287 | - ); |
|
288 | - return $insertQb->execute(); |
|
289 | - } catch (ConstraintViolationException $e) { |
|
290 | - // value already exists, try update |
|
291 | - $updateQb = $this->getQueryBuilder(); |
|
292 | - $updateQb->update($table); |
|
293 | - foreach ($values as $name => $value) { |
|
294 | - $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value))); |
|
295 | - } |
|
296 | - $where = $updateQb->expr()->andX(); |
|
297 | - $whereValues = array_merge($keys, $updatePreconditionValues); |
|
298 | - foreach ($whereValues as $name => $value) { |
|
299 | - $where->add($updateQb->expr()->eq( |
|
300 | - $name, |
|
301 | - $updateQb->createNamedParameter($value, $this->getType($value)), |
|
302 | - $this->getType($value) |
|
303 | - )); |
|
304 | - } |
|
305 | - $updateQb->where($where); |
|
306 | - $affected = $updateQb->execute(); |
|
307 | - |
|
308 | - if ($affected === 0 && !empty($updatePreconditionValues)) { |
|
309 | - throw new PreConditionNotMetException(); |
|
310 | - } |
|
311 | - |
|
312 | - return 0; |
|
313 | - } |
|
314 | - } |
|
315 | - |
|
316 | - /** |
|
317 | - * Create an exclusive read+write lock on a table |
|
318 | - * |
|
319 | - * @param string $tableName |
|
320 | - * @throws \BadMethodCallException When trying to acquire a second lock |
|
321 | - * @since 9.1.0 |
|
322 | - */ |
|
323 | - public function lockTable($tableName) { |
|
324 | - if ($this->lockedTable !== null) { |
|
325 | - throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
|
326 | - } |
|
327 | - |
|
328 | - $tableName = $this->tablePrefix . $tableName; |
|
329 | - $this->lockedTable = $tableName; |
|
330 | - $this->adapter->lockTable($tableName); |
|
331 | - } |
|
332 | - |
|
333 | - /** |
|
334 | - * Release a previous acquired lock again |
|
335 | - * |
|
336 | - * @since 9.1.0 |
|
337 | - */ |
|
338 | - public function unlockTable() { |
|
339 | - $this->adapter->unlockTable(); |
|
340 | - $this->lockedTable = null; |
|
341 | - } |
|
342 | - |
|
343 | - /** |
|
344 | - * returns the error code and message as a string for logging |
|
345 | - * works with DoctrineException |
|
346 | - * @return string |
|
347 | - */ |
|
348 | - public function getError() { |
|
349 | - $msg = $this->errorCode() . ': '; |
|
350 | - $errorInfo = $this->errorInfo(); |
|
351 | - if (is_array($errorInfo)) { |
|
352 | - $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
353 | - $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
354 | - $msg .= 'Driver Message = '.$errorInfo[2]; |
|
355 | - } |
|
356 | - return $msg; |
|
357 | - } |
|
358 | - |
|
359 | - /** |
|
360 | - * Drop a table from the database if it exists |
|
361 | - * |
|
362 | - * @param string $table table name without the prefix |
|
363 | - */ |
|
364 | - public function dropTable($table) { |
|
365 | - $table = $this->tablePrefix . trim($table); |
|
366 | - $schema = $this->getSchemaManager(); |
|
367 | - if($schema->tablesExist(array($table))) { |
|
368 | - $schema->dropTable($table); |
|
369 | - } |
|
370 | - } |
|
371 | - |
|
372 | - /** |
|
373 | - * Check if a table exists |
|
374 | - * |
|
375 | - * @param string $table table name without the prefix |
|
376 | - * @return bool |
|
377 | - */ |
|
378 | - public function tableExists($table){ |
|
379 | - $table = $this->tablePrefix . trim($table); |
|
380 | - $schema = $this->getSchemaManager(); |
|
381 | - return $schema->tablesExist(array($table)); |
|
382 | - } |
|
383 | - |
|
384 | - // internal use |
|
385 | - /** |
|
386 | - * @param string $statement |
|
387 | - * @return string |
|
388 | - */ |
|
389 | - protected function replaceTablePrefix($statement) { |
|
390 | - return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
391 | - } |
|
392 | - |
|
393 | - /** |
|
394 | - * Check if a transaction is active |
|
395 | - * |
|
396 | - * @return bool |
|
397 | - * @since 8.2.0 |
|
398 | - */ |
|
399 | - public function inTransaction() { |
|
400 | - return $this->getTransactionNestingLevel() > 0; |
|
401 | - } |
|
402 | - |
|
403 | - /** |
|
404 | - * Escape a parameter to be used in a LIKE query |
|
405 | - * |
|
406 | - * @param string $param |
|
407 | - * @return string |
|
408 | - */ |
|
409 | - public function escapeLikeParameter($param) { |
|
410 | - return addcslashes($param, '\\_%'); |
|
411 | - } |
|
412 | - |
|
413 | - /** |
|
414 | - * Check whether or not the current database support 4byte wide unicode |
|
415 | - * |
|
416 | - * @return bool |
|
417 | - * @since 11.0.0 |
|
418 | - */ |
|
419 | - public function supports4ByteText() { |
|
420 | - if (!$this->getDatabasePlatform() instanceof MySqlPlatform) { |
|
421 | - return true; |
|
422 | - } |
|
423 | - return $this->getParams()['charset'] === 'utf8mb4'; |
|
424 | - } |
|
425 | - |
|
426 | - |
|
427 | - /** |
|
428 | - * Create the schema of the connected database |
|
429 | - * |
|
430 | - * @return Schema |
|
431 | - */ |
|
432 | - public function createSchema() { |
|
433 | - $schemaManager = new MDB2SchemaManager($this); |
|
434 | - $migrator = $schemaManager->getMigrator(); |
|
435 | - return $migrator->createSchema(); |
|
436 | - } |
|
437 | - |
|
438 | - /** |
|
439 | - * Migrate the database to the given schema |
|
440 | - * |
|
441 | - * @param Schema $toSchema |
|
442 | - */ |
|
443 | - public function migrateToSchema(Schema $toSchema) { |
|
444 | - $schemaManager = new MDB2SchemaManager($this); |
|
445 | - $migrator = $schemaManager->getMigrator(); |
|
446 | - $migrator->migrate($toSchema); |
|
447 | - } |
|
47 | + /** |
|
48 | + * @var string $tablePrefix |
|
49 | + */ |
|
50 | + protected $tablePrefix; |
|
51 | + |
|
52 | + /** |
|
53 | + * @var \OC\DB\Adapter $adapter |
|
54 | + */ |
|
55 | + protected $adapter; |
|
56 | + |
|
57 | + protected $lockedTable = null; |
|
58 | + |
|
59 | + public function connect() { |
|
60 | + try { |
|
61 | + return parent::connect(); |
|
62 | + } catch (DBALException $e) { |
|
63 | + // throw a new exception to prevent leaking info from the stacktrace |
|
64 | + throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode()); |
|
65 | + } |
|
66 | + } |
|
67 | + |
|
68 | + /** |
|
69 | + * Returns a QueryBuilder for the connection. |
|
70 | + * |
|
71 | + * @return \OCP\DB\QueryBuilder\IQueryBuilder |
|
72 | + */ |
|
73 | + public function getQueryBuilder() { |
|
74 | + return new QueryBuilder( |
|
75 | + $this, |
|
76 | + \OC::$server->getSystemConfig(), |
|
77 | + \OC::$server->getLogger() |
|
78 | + ); |
|
79 | + } |
|
80 | + |
|
81 | + /** |
|
82 | + * Gets the QueryBuilder for the connection. |
|
83 | + * |
|
84 | + * @return \Doctrine\DBAL\Query\QueryBuilder |
|
85 | + * @deprecated please use $this->getQueryBuilder() instead |
|
86 | + */ |
|
87 | + public function createQueryBuilder() { |
|
88 | + $backtrace = $this->getCallerBacktrace(); |
|
89 | + \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
90 | + return parent::createQueryBuilder(); |
|
91 | + } |
|
92 | + |
|
93 | + /** |
|
94 | + * Gets the ExpressionBuilder for the connection. |
|
95 | + * |
|
96 | + * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder |
|
97 | + * @deprecated please use $this->getQueryBuilder()->expr() instead |
|
98 | + */ |
|
99 | + public function getExpressionBuilder() { |
|
100 | + $backtrace = $this->getCallerBacktrace(); |
|
101 | + \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]); |
|
102 | + return parent::getExpressionBuilder(); |
|
103 | + } |
|
104 | + |
|
105 | + /** |
|
106 | + * Get the file and line that called the method where `getCallerBacktrace()` was used |
|
107 | + * |
|
108 | + * @return string |
|
109 | + */ |
|
110 | + protected function getCallerBacktrace() { |
|
111 | + $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); |
|
112 | + |
|
113 | + // 0 is the method where we use `getCallerBacktrace` |
|
114 | + // 1 is the target method which uses the method we want to log |
|
115 | + if (isset($traces[1])) { |
|
116 | + return $traces[1]['file'] . ':' . $traces[1]['line']; |
|
117 | + } |
|
118 | + |
|
119 | + return ''; |
|
120 | + } |
|
121 | + |
|
122 | + /** |
|
123 | + * @return string |
|
124 | + */ |
|
125 | + public function getPrefix() { |
|
126 | + return $this->tablePrefix; |
|
127 | + } |
|
128 | + |
|
129 | + /** |
|
130 | + * Initializes a new instance of the Connection class. |
|
131 | + * |
|
132 | + * @param array $params The connection parameters. |
|
133 | + * @param \Doctrine\DBAL\Driver $driver |
|
134 | + * @param \Doctrine\DBAL\Configuration $config |
|
135 | + * @param \Doctrine\Common\EventManager $eventManager |
|
136 | + * @throws \Exception |
|
137 | + */ |
|
138 | + public function __construct(array $params, Driver $driver, Configuration $config = null, |
|
139 | + EventManager $eventManager = null) |
|
140 | + { |
|
141 | + if (!isset($params['adapter'])) { |
|
142 | + throw new \Exception('adapter not set'); |
|
143 | + } |
|
144 | + if (!isset($params['tablePrefix'])) { |
|
145 | + throw new \Exception('tablePrefix not set'); |
|
146 | + } |
|
147 | + parent::__construct($params, $driver, $config, $eventManager); |
|
148 | + $this->adapter = new $params['adapter']($this); |
|
149 | + $this->tablePrefix = $params['tablePrefix']; |
|
150 | + |
|
151 | + parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED); |
|
152 | + } |
|
153 | + |
|
154 | + /** |
|
155 | + * Prepares an SQL statement. |
|
156 | + * |
|
157 | + * @param string $statement The SQL statement to prepare. |
|
158 | + * @param int $limit |
|
159 | + * @param int $offset |
|
160 | + * @return \Doctrine\DBAL\Driver\Statement The prepared statement. |
|
161 | + */ |
|
162 | + public function prepare( $statement, $limit=null, $offset=null ) { |
|
163 | + if ($limit === -1) { |
|
164 | + $limit = null; |
|
165 | + } |
|
166 | + if (!is_null($limit)) { |
|
167 | + $platform = $this->getDatabasePlatform(); |
|
168 | + $statement = $platform->modifyLimitQuery($statement, $limit, $offset); |
|
169 | + } |
|
170 | + $statement = $this->replaceTablePrefix($statement); |
|
171 | + $statement = $this->adapter->fixupStatement($statement); |
|
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 | + * @suppress SqlInjectionChecker |
|
278 | + */ |
|
279 | + public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) { |
|
280 | + try { |
|
281 | + $insertQb = $this->getQueryBuilder(); |
|
282 | + $insertQb->insert($table) |
|
283 | + ->values( |
|
284 | + array_map(function($value) use ($insertQb) { |
|
285 | + return $insertQb->createNamedParameter($value, $this->getType($value)); |
|
286 | + }, array_merge($keys, $values)) |
|
287 | + ); |
|
288 | + return $insertQb->execute(); |
|
289 | + } catch (ConstraintViolationException $e) { |
|
290 | + // value already exists, try update |
|
291 | + $updateQb = $this->getQueryBuilder(); |
|
292 | + $updateQb->update($table); |
|
293 | + foreach ($values as $name => $value) { |
|
294 | + $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value))); |
|
295 | + } |
|
296 | + $where = $updateQb->expr()->andX(); |
|
297 | + $whereValues = array_merge($keys, $updatePreconditionValues); |
|
298 | + foreach ($whereValues as $name => $value) { |
|
299 | + $where->add($updateQb->expr()->eq( |
|
300 | + $name, |
|
301 | + $updateQb->createNamedParameter($value, $this->getType($value)), |
|
302 | + $this->getType($value) |
|
303 | + )); |
|
304 | + } |
|
305 | + $updateQb->where($where); |
|
306 | + $affected = $updateQb->execute(); |
|
307 | + |
|
308 | + if ($affected === 0 && !empty($updatePreconditionValues)) { |
|
309 | + throw new PreConditionNotMetException(); |
|
310 | + } |
|
311 | + |
|
312 | + return 0; |
|
313 | + } |
|
314 | + } |
|
315 | + |
|
316 | + /** |
|
317 | + * Create an exclusive read+write lock on a table |
|
318 | + * |
|
319 | + * @param string $tableName |
|
320 | + * @throws \BadMethodCallException When trying to acquire a second lock |
|
321 | + * @since 9.1.0 |
|
322 | + */ |
|
323 | + public function lockTable($tableName) { |
|
324 | + if ($this->lockedTable !== null) { |
|
325 | + throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.'); |
|
326 | + } |
|
327 | + |
|
328 | + $tableName = $this->tablePrefix . $tableName; |
|
329 | + $this->lockedTable = $tableName; |
|
330 | + $this->adapter->lockTable($tableName); |
|
331 | + } |
|
332 | + |
|
333 | + /** |
|
334 | + * Release a previous acquired lock again |
|
335 | + * |
|
336 | + * @since 9.1.0 |
|
337 | + */ |
|
338 | + public function unlockTable() { |
|
339 | + $this->adapter->unlockTable(); |
|
340 | + $this->lockedTable = null; |
|
341 | + } |
|
342 | + |
|
343 | + /** |
|
344 | + * returns the error code and message as a string for logging |
|
345 | + * works with DoctrineException |
|
346 | + * @return string |
|
347 | + */ |
|
348 | + public function getError() { |
|
349 | + $msg = $this->errorCode() . ': '; |
|
350 | + $errorInfo = $this->errorInfo(); |
|
351 | + if (is_array($errorInfo)) { |
|
352 | + $msg .= 'SQLSTATE = '.$errorInfo[0] . ', '; |
|
353 | + $msg .= 'Driver Code = '.$errorInfo[1] . ', '; |
|
354 | + $msg .= 'Driver Message = '.$errorInfo[2]; |
|
355 | + } |
|
356 | + return $msg; |
|
357 | + } |
|
358 | + |
|
359 | + /** |
|
360 | + * Drop a table from the database if it exists |
|
361 | + * |
|
362 | + * @param string $table table name without the prefix |
|
363 | + */ |
|
364 | + public function dropTable($table) { |
|
365 | + $table = $this->tablePrefix . trim($table); |
|
366 | + $schema = $this->getSchemaManager(); |
|
367 | + if($schema->tablesExist(array($table))) { |
|
368 | + $schema->dropTable($table); |
|
369 | + } |
|
370 | + } |
|
371 | + |
|
372 | + /** |
|
373 | + * Check if a table exists |
|
374 | + * |
|
375 | + * @param string $table table name without the prefix |
|
376 | + * @return bool |
|
377 | + */ |
|
378 | + public function tableExists($table){ |
|
379 | + $table = $this->tablePrefix . trim($table); |
|
380 | + $schema = $this->getSchemaManager(); |
|
381 | + return $schema->tablesExist(array($table)); |
|
382 | + } |
|
383 | + |
|
384 | + // internal use |
|
385 | + /** |
|
386 | + * @param string $statement |
|
387 | + * @return string |
|
388 | + */ |
|
389 | + protected function replaceTablePrefix($statement) { |
|
390 | + return str_replace( '*PREFIX*', $this->tablePrefix, $statement ); |
|
391 | + } |
|
392 | + |
|
393 | + /** |
|
394 | + * Check if a transaction is active |
|
395 | + * |
|
396 | + * @return bool |
|
397 | + * @since 8.2.0 |
|
398 | + */ |
|
399 | + public function inTransaction() { |
|
400 | + return $this->getTransactionNestingLevel() > 0; |
|
401 | + } |
|
402 | + |
|
403 | + /** |
|
404 | + * Escape a parameter to be used in a LIKE query |
|
405 | + * |
|
406 | + * @param string $param |
|
407 | + * @return string |
|
408 | + */ |
|
409 | + public function escapeLikeParameter($param) { |
|
410 | + return addcslashes($param, '\\_%'); |
|
411 | + } |
|
412 | + |
|
413 | + /** |
|
414 | + * Check whether or not the current database support 4byte wide unicode |
|
415 | + * |
|
416 | + * @return bool |
|
417 | + * @since 11.0.0 |
|
418 | + */ |
|
419 | + public function supports4ByteText() { |
|
420 | + if (!$this->getDatabasePlatform() instanceof MySqlPlatform) { |
|
421 | + return true; |
|
422 | + } |
|
423 | + return $this->getParams()['charset'] === 'utf8mb4'; |
|
424 | + } |
|
425 | + |
|
426 | + |
|
427 | + /** |
|
428 | + * Create the schema of the connected database |
|
429 | + * |
|
430 | + * @return Schema |
|
431 | + */ |
|
432 | + public function createSchema() { |
|
433 | + $schemaManager = new MDB2SchemaManager($this); |
|
434 | + $migrator = $schemaManager->getMigrator(); |
|
435 | + return $migrator->createSchema(); |
|
436 | + } |
|
437 | + |
|
438 | + /** |
|
439 | + * Migrate the database to the given schema |
|
440 | + * |
|
441 | + * @param Schema $toSchema |
|
442 | + */ |
|
443 | + public function migrateToSchema(Schema $toSchema) { |
|
444 | + $schemaManager = new MDB2SchemaManager($this); |
|
445 | + $migrator = $schemaManager->getMigrator(); |
|
446 | + $migrator->migrate($toSchema); |
|
447 | + } |
|
448 | 448 | } |
@@ -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(); |
@@ -53,504 +53,504 @@ |
||
53 | 53 | * @package OC\Files\Cache |
54 | 54 | */ |
55 | 55 | class Scanner extends BasicEmitter implements IScanner { |
56 | - /** |
|
57 | - * @var \OC\Files\Storage\Storage $storage |
|
58 | - */ |
|
59 | - protected $storage; |
|
60 | - |
|
61 | - /** |
|
62 | - * @var string $storageId |
|
63 | - */ |
|
64 | - protected $storageId; |
|
65 | - |
|
66 | - /** |
|
67 | - * @var \OC\Files\Cache\Cache $cache |
|
68 | - */ |
|
69 | - protected $cache; |
|
70 | - |
|
71 | - /** |
|
72 | - * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache |
|
73 | - */ |
|
74 | - protected $cacheActive; |
|
75 | - |
|
76 | - /** |
|
77 | - * @var bool $useTransactions whether to use transactions |
|
78 | - */ |
|
79 | - protected $useTransactions = true; |
|
80 | - |
|
81 | - /** |
|
82 | - * @var \OCP\Lock\ILockingProvider |
|
83 | - */ |
|
84 | - protected $lockingProvider; |
|
85 | - |
|
86 | - public function __construct(\OC\Files\Storage\Storage $storage) { |
|
87 | - $this->storage = $storage; |
|
88 | - $this->storageId = $this->storage->getId(); |
|
89 | - $this->cache = $storage->getCache(); |
|
90 | - $this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false); |
|
91 | - $this->lockingProvider = \OC::$server->getLockingProvider(); |
|
92 | - } |
|
93 | - |
|
94 | - /** |
|
95 | - * Whether to wrap the scanning of a folder in a database transaction |
|
96 | - * On default transactions are used |
|
97 | - * |
|
98 | - * @param bool $useTransactions |
|
99 | - */ |
|
100 | - public function setUseTransactions($useTransactions) { |
|
101 | - $this->useTransactions = $useTransactions; |
|
102 | - } |
|
103 | - |
|
104 | - /** |
|
105 | - * get all the metadata of a file or folder |
|
106 | - * * |
|
107 | - * |
|
108 | - * @param string $path |
|
109 | - * @return array an array of metadata of the file |
|
110 | - */ |
|
111 | - protected function getData($path) { |
|
112 | - $data = $this->storage->getMetaData($path); |
|
113 | - if (is_null($data)) { |
|
114 | - \OCP\Util::writeLog(Scanner::class, "!!! Path '$path' is not accessible or present !!!", ILogger::DEBUG); |
|
115 | - } |
|
116 | - return $data; |
|
117 | - } |
|
118 | - |
|
119 | - /** |
|
120 | - * scan a single file and store it in the cache |
|
121 | - * |
|
122 | - * @param string $file |
|
123 | - * @param int $reuseExisting |
|
124 | - * @param int $parentId |
|
125 | - * @param array | null $cacheData existing data in the cache for the file to be scanned |
|
126 | - * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
127 | - * @return array an array of metadata of the scanned file |
|
128 | - * @throws \OC\ServerNotAvailableException |
|
129 | - * @throws \OCP\Lock\LockedException |
|
130 | - */ |
|
131 | - public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) { |
|
132 | - if ($file !== '') { |
|
133 | - try { |
|
134 | - $this->storage->verifyPath(dirname($file), basename($file)); |
|
135 | - } catch (\Exception $e) { |
|
136 | - return null; |
|
137 | - } |
|
138 | - } |
|
139 | - // only proceed if $file is not a partial file nor a blacklisted file |
|
140 | - if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) { |
|
141 | - |
|
142 | - //acquire a lock |
|
143 | - if ($lock) { |
|
144 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
145 | - $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
146 | - } |
|
147 | - } |
|
148 | - |
|
149 | - try { |
|
150 | - $data = $this->getData($file); |
|
151 | - } catch (ForbiddenException $e) { |
|
152 | - if ($lock) { |
|
153 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
154 | - $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
155 | - } |
|
156 | - } |
|
157 | - |
|
158 | - return null; |
|
159 | - } |
|
160 | - |
|
161 | - try { |
|
162 | - if ($data) { |
|
163 | - |
|
164 | - // pre-emit only if it was a file. By that we avoid counting/treating folders as files |
|
165 | - if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
166 | - $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId)); |
|
167 | - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
168 | - } |
|
169 | - |
|
170 | - $parent = dirname($file); |
|
171 | - if ($parent === '.' or $parent === '/') { |
|
172 | - $parent = ''; |
|
173 | - } |
|
174 | - if ($parentId === -1) { |
|
175 | - $parentId = $this->cache->getParentId($file); |
|
176 | - } |
|
177 | - |
|
178 | - // scan the parent if it's not in the cache (id -1) and the current file is not the root folder |
|
179 | - if ($file and $parentId === -1) { |
|
180 | - $parentData = $this->scanFile($parent); |
|
181 | - if (!$parentData) { |
|
182 | - return null; |
|
183 | - } |
|
184 | - $parentId = $parentData['fileid']; |
|
185 | - } |
|
186 | - if ($parent) { |
|
187 | - $data['parent'] = $parentId; |
|
188 | - } |
|
189 | - if (is_null($cacheData)) { |
|
190 | - /** @var CacheEntry $cacheData */ |
|
191 | - $cacheData = $this->cache->get($file); |
|
192 | - } |
|
193 | - if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) { |
|
194 | - // prevent empty etag |
|
195 | - if (empty($cacheData['etag'])) { |
|
196 | - $etag = $data['etag']; |
|
197 | - } else { |
|
198 | - $etag = $cacheData['etag']; |
|
199 | - } |
|
200 | - $fileId = $cacheData['fileid']; |
|
201 | - $data['fileid'] = $fileId; |
|
202 | - // only reuse data if the file hasn't explicitly changed |
|
203 | - if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) { |
|
204 | - $data['mtime'] = $cacheData['mtime']; |
|
205 | - if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) { |
|
206 | - $data['size'] = $cacheData['size']; |
|
207 | - } |
|
208 | - if ($reuseExisting & self::REUSE_ETAG) { |
|
209 | - $data['etag'] = $etag; |
|
210 | - } |
|
211 | - } |
|
212 | - // Only update metadata that has changed |
|
213 | - $newData = array_diff_assoc($data, $cacheData->getData()); |
|
214 | - } else { |
|
215 | - $newData = $data; |
|
216 | - $fileId = -1; |
|
217 | - } |
|
218 | - if (!empty($newData)) { |
|
219 | - // Reset the checksum if the data has changed |
|
220 | - $newData['checksum'] = ''; |
|
221 | - $data['fileid'] = $this->addToCache($file, $newData, $fileId); |
|
222 | - } |
|
223 | - if (isset($cacheData['size'])) { |
|
224 | - $data['oldSize'] = $cacheData['size']; |
|
225 | - } else { |
|
226 | - $data['oldSize'] = 0; |
|
227 | - } |
|
228 | - |
|
229 | - if (isset($cacheData['encrypted'])) { |
|
230 | - $data['encrypted'] = $cacheData['encrypted']; |
|
231 | - } |
|
232 | - |
|
233 | - // post-emit only if it was a file. By that we avoid counting/treating folders as files |
|
234 | - if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
235 | - $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); |
|
236 | - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
237 | - } |
|
238 | - |
|
239 | - } else { |
|
240 | - $this->removeFromCache($file); |
|
241 | - } |
|
242 | - } catch (\Exception $e) { |
|
243 | - if ($lock) { |
|
244 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
245 | - $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
246 | - } |
|
247 | - } |
|
248 | - throw $e; |
|
249 | - } |
|
250 | - |
|
251 | - //release the acquired lock |
|
252 | - if ($lock) { |
|
253 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
254 | - $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
255 | - } |
|
256 | - } |
|
257 | - |
|
258 | - if ($data && !isset($data['encrypted'])) { |
|
259 | - $data['encrypted'] = false; |
|
260 | - } |
|
261 | - return $data; |
|
262 | - } |
|
263 | - |
|
264 | - return null; |
|
265 | - } |
|
266 | - |
|
267 | - protected function removeFromCache($path) { |
|
268 | - \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path)); |
|
269 | - $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path)); |
|
270 | - if ($this->cacheActive) { |
|
271 | - $this->cache->remove($path); |
|
272 | - } |
|
273 | - } |
|
274 | - |
|
275 | - /** |
|
276 | - * @param string $path |
|
277 | - * @param array $data |
|
278 | - * @param int $fileId |
|
279 | - * @return int the id of the added file |
|
280 | - */ |
|
281 | - protected function addToCache($path, $data, $fileId = -1) { |
|
282 | - if (isset($data['scan_permissions'])) { |
|
283 | - $data['permissions'] = $data['scan_permissions']; |
|
284 | - } |
|
285 | - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
286 | - $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data)); |
|
287 | - if ($this->cacheActive) { |
|
288 | - if ($fileId !== -1) { |
|
289 | - $this->cache->update($fileId, $data); |
|
290 | - return $fileId; |
|
291 | - } else { |
|
292 | - return $this->cache->put($path, $data); |
|
293 | - } |
|
294 | - } else { |
|
295 | - return -1; |
|
296 | - } |
|
297 | - } |
|
298 | - |
|
299 | - /** |
|
300 | - * @param string $path |
|
301 | - * @param array $data |
|
302 | - * @param int $fileId |
|
303 | - */ |
|
304 | - protected function updateCache($path, $data, $fileId = -1) { |
|
305 | - \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
306 | - $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data)); |
|
307 | - if ($this->cacheActive) { |
|
308 | - if ($fileId !== -1) { |
|
309 | - $this->cache->update($fileId, $data); |
|
310 | - } else { |
|
311 | - $this->cache->put($path, $data); |
|
312 | - } |
|
313 | - } |
|
314 | - } |
|
315 | - |
|
316 | - /** |
|
317 | - * scan a folder and all it's children |
|
318 | - * |
|
319 | - * @param string $path |
|
320 | - * @param bool $recursive |
|
321 | - * @param int $reuse |
|
322 | - * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
323 | - * @return array an array of the meta data of the scanned file or folder |
|
324 | - */ |
|
325 | - public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) { |
|
326 | - if ($reuse === -1) { |
|
327 | - $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
328 | - } |
|
329 | - if ($lock) { |
|
330 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
331 | - $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
332 | - $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
333 | - } |
|
334 | - } |
|
335 | - try { |
|
336 | - $data = $this->scanFile($path, $reuse, -1, null, $lock); |
|
337 | - if ($data and $data['mimetype'] === 'httpd/unix-directory') { |
|
338 | - $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock); |
|
339 | - $data['size'] = $size; |
|
340 | - } |
|
341 | - } finally { |
|
342 | - if ($lock) { |
|
343 | - if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
344 | - $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
345 | - $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
346 | - } |
|
347 | - } |
|
348 | - } |
|
349 | - return $data; |
|
350 | - } |
|
351 | - |
|
352 | - /** |
|
353 | - * Get the children currently in the cache |
|
354 | - * |
|
355 | - * @param int $folderId |
|
356 | - * @return array[] |
|
357 | - */ |
|
358 | - protected function getExistingChildren($folderId) { |
|
359 | - $existingChildren = array(); |
|
360 | - $children = $this->cache->getFolderContentsById($folderId); |
|
361 | - foreach ($children as $child) { |
|
362 | - $existingChildren[$child['name']] = $child; |
|
363 | - } |
|
364 | - return $existingChildren; |
|
365 | - } |
|
366 | - |
|
367 | - /** |
|
368 | - * Get the children from the storage |
|
369 | - * |
|
370 | - * @param string $folder |
|
371 | - * @return string[] |
|
372 | - */ |
|
373 | - protected function getNewChildren($folder) { |
|
374 | - $children = array(); |
|
375 | - if ($dh = $this->storage->opendir($folder)) { |
|
376 | - if (is_resource($dh)) { |
|
377 | - while (($file = readdir($dh)) !== false) { |
|
378 | - if (!Filesystem::isIgnoredDir($file)) { |
|
379 | - $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/'); |
|
380 | - } |
|
381 | - } |
|
382 | - } |
|
383 | - } |
|
384 | - return $children; |
|
385 | - } |
|
386 | - |
|
387 | - /** |
|
388 | - * scan all the files and folders in a folder |
|
389 | - * |
|
390 | - * @param string $path |
|
391 | - * @param bool $recursive |
|
392 | - * @param int $reuse |
|
393 | - * @param int $folderId id for the folder to be scanned |
|
394 | - * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
395 | - * @return int the size of the scanned folder or -1 if the size is unknown at this stage |
|
396 | - */ |
|
397 | - protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) { |
|
398 | - if ($reuse === -1) { |
|
399 | - $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
400 | - } |
|
401 | - $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId)); |
|
402 | - $size = 0; |
|
403 | - if (!is_null($folderId)) { |
|
404 | - $folderId = $this->cache->getId($path); |
|
405 | - } |
|
406 | - $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size); |
|
407 | - |
|
408 | - foreach ($childQueue as $child => $childId) { |
|
409 | - $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock); |
|
410 | - if ($childSize === -1) { |
|
411 | - $size = -1; |
|
412 | - } else if ($size !== -1) { |
|
413 | - $size += $childSize; |
|
414 | - } |
|
415 | - } |
|
416 | - if ($this->cacheActive) { |
|
417 | - $this->cache->update($folderId, array('size' => $size)); |
|
418 | - } |
|
419 | - $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId)); |
|
420 | - return $size; |
|
421 | - } |
|
422 | - |
|
423 | - private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) { |
|
424 | - // we put this in it's own function so it cleans up the memory before we start recursing |
|
425 | - $existingChildren = $this->getExistingChildren($folderId); |
|
426 | - $newChildren = $this->getNewChildren($path); |
|
427 | - |
|
428 | - if ($this->useTransactions) { |
|
429 | - \OC::$server->getDatabaseConnection()->beginTransaction(); |
|
430 | - } |
|
431 | - |
|
432 | - $exceptionOccurred = false; |
|
433 | - $childQueue = []; |
|
434 | - foreach ($newChildren as $file) { |
|
435 | - $child = $path ? $path . '/' . $file : $file; |
|
436 | - try { |
|
437 | - $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; |
|
438 | - $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); |
|
439 | - if ($data) { |
|
440 | - if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) { |
|
441 | - $childQueue[$child] = $data['fileid']; |
|
442 | - } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) { |
|
443 | - // only recurse into folders which aren't fully scanned |
|
444 | - $childQueue[$child] = $data['fileid']; |
|
445 | - } else if ($data['size'] === -1) { |
|
446 | - $size = -1; |
|
447 | - } else if ($size !== -1) { |
|
448 | - $size += $data['size']; |
|
449 | - } |
|
450 | - } |
|
451 | - } catch (\Doctrine\DBAL\DBALException $ex) { |
|
452 | - // might happen if inserting duplicate while a scanning |
|
453 | - // process is running in parallel |
|
454 | - // log and ignore |
|
455 | - if ($this->useTransactions) { |
|
456 | - \OC::$server->getDatabaseConnection()->rollback(); |
|
457 | - \OC::$server->getDatabaseConnection()->beginTransaction(); |
|
458 | - } |
|
459 | - \OC::$server->getLogger()->logException($ex, [ |
|
460 | - 'message' => 'Exception while scanning file "' . $child . '"', |
|
461 | - 'level' => ILogger::DEBUG, |
|
462 | - 'app' => 'core', |
|
463 | - ]); |
|
464 | - $exceptionOccurred = true; |
|
465 | - } catch (\OCP\Lock\LockedException $e) { |
|
466 | - if ($this->useTransactions) { |
|
467 | - \OC::$server->getDatabaseConnection()->rollback(); |
|
468 | - } |
|
469 | - throw $e; |
|
470 | - } |
|
471 | - } |
|
472 | - $removedChildren = \array_diff(array_keys($existingChildren), $newChildren); |
|
473 | - foreach ($removedChildren as $childName) { |
|
474 | - $child = $path ? $path . '/' . $childName : $childName; |
|
475 | - $this->removeFromCache($child); |
|
476 | - } |
|
477 | - if ($this->useTransactions) { |
|
478 | - \OC::$server->getDatabaseConnection()->commit(); |
|
479 | - } |
|
480 | - if ($exceptionOccurred) { |
|
481 | - // It might happen that the parallel scan process has already |
|
482 | - // inserted mimetypes but those weren't available yet inside the transaction |
|
483 | - // To make sure to have the updated mime types in such cases, |
|
484 | - // we reload them here |
|
485 | - \OC::$server->getMimeTypeLoader()->reset(); |
|
486 | - } |
|
487 | - return $childQueue; |
|
488 | - } |
|
489 | - |
|
490 | - /** |
|
491 | - * check if the file should be ignored when scanning |
|
492 | - * NOTE: files with a '.part' extension are ignored as well! |
|
493 | - * prevents unfinished put requests to be scanned |
|
494 | - * |
|
495 | - * @param string $file |
|
496 | - * @return boolean |
|
497 | - */ |
|
498 | - public static function isPartialFile($file) { |
|
499 | - if (pathinfo($file, PATHINFO_EXTENSION) === 'part') { |
|
500 | - return true; |
|
501 | - } |
|
502 | - if (strpos($file, '.part/') !== false) { |
|
503 | - return true; |
|
504 | - } |
|
505 | - |
|
506 | - return false; |
|
507 | - } |
|
508 | - |
|
509 | - /** |
|
510 | - * walk over any folders that are not fully scanned yet and scan them |
|
511 | - */ |
|
512 | - public function backgroundScan() { |
|
513 | - if (!$this->cache->inCache('')) { |
|
514 | - $this->runBackgroundScanJob(function () { |
|
515 | - $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); |
|
516 | - }, ''); |
|
517 | - } else { |
|
518 | - $lastPath = null; |
|
519 | - while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { |
|
520 | - $this->runBackgroundScanJob(function () use ($path) { |
|
521 | - $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); |
|
522 | - }, $path); |
|
523 | - // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() |
|
524 | - // to make this possible |
|
525 | - $lastPath = $path; |
|
526 | - } |
|
527 | - } |
|
528 | - } |
|
529 | - |
|
530 | - private function runBackgroundScanJob(callable $callback, $path) { |
|
531 | - try { |
|
532 | - $callback(); |
|
533 | - \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); |
|
534 | - if ($this->cacheActive && $this->cache instanceof Cache) { |
|
535 | - $this->cache->correctFolderSize($path); |
|
536 | - } |
|
537 | - } catch (\OCP\Files\StorageInvalidException $e) { |
|
538 | - // skip unavailable storages |
|
539 | - } catch (\OCP\Files\StorageNotAvailableException $e) { |
|
540 | - // skip unavailable storages |
|
541 | - } catch (\OCP\Files\ForbiddenException $e) { |
|
542 | - // skip forbidden storages |
|
543 | - } catch (\OCP\Lock\LockedException $e) { |
|
544 | - // skip unavailable storages |
|
545 | - } |
|
546 | - } |
|
547 | - |
|
548 | - /** |
|
549 | - * Set whether the cache is affected by scan operations |
|
550 | - * |
|
551 | - * @param boolean $active The active state of the cache |
|
552 | - */ |
|
553 | - public function setCacheActive($active) { |
|
554 | - $this->cacheActive = $active; |
|
555 | - } |
|
56 | + /** |
|
57 | + * @var \OC\Files\Storage\Storage $storage |
|
58 | + */ |
|
59 | + protected $storage; |
|
60 | + |
|
61 | + /** |
|
62 | + * @var string $storageId |
|
63 | + */ |
|
64 | + protected $storageId; |
|
65 | + |
|
66 | + /** |
|
67 | + * @var \OC\Files\Cache\Cache $cache |
|
68 | + */ |
|
69 | + protected $cache; |
|
70 | + |
|
71 | + /** |
|
72 | + * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache |
|
73 | + */ |
|
74 | + protected $cacheActive; |
|
75 | + |
|
76 | + /** |
|
77 | + * @var bool $useTransactions whether to use transactions |
|
78 | + */ |
|
79 | + protected $useTransactions = true; |
|
80 | + |
|
81 | + /** |
|
82 | + * @var \OCP\Lock\ILockingProvider |
|
83 | + */ |
|
84 | + protected $lockingProvider; |
|
85 | + |
|
86 | + public function __construct(\OC\Files\Storage\Storage $storage) { |
|
87 | + $this->storage = $storage; |
|
88 | + $this->storageId = $this->storage->getId(); |
|
89 | + $this->cache = $storage->getCache(); |
|
90 | + $this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false); |
|
91 | + $this->lockingProvider = \OC::$server->getLockingProvider(); |
|
92 | + } |
|
93 | + |
|
94 | + /** |
|
95 | + * Whether to wrap the scanning of a folder in a database transaction |
|
96 | + * On default transactions are used |
|
97 | + * |
|
98 | + * @param bool $useTransactions |
|
99 | + */ |
|
100 | + public function setUseTransactions($useTransactions) { |
|
101 | + $this->useTransactions = $useTransactions; |
|
102 | + } |
|
103 | + |
|
104 | + /** |
|
105 | + * get all the metadata of a file or folder |
|
106 | + * * |
|
107 | + * |
|
108 | + * @param string $path |
|
109 | + * @return array an array of metadata of the file |
|
110 | + */ |
|
111 | + protected function getData($path) { |
|
112 | + $data = $this->storage->getMetaData($path); |
|
113 | + if (is_null($data)) { |
|
114 | + \OCP\Util::writeLog(Scanner::class, "!!! Path '$path' is not accessible or present !!!", ILogger::DEBUG); |
|
115 | + } |
|
116 | + return $data; |
|
117 | + } |
|
118 | + |
|
119 | + /** |
|
120 | + * scan a single file and store it in the cache |
|
121 | + * |
|
122 | + * @param string $file |
|
123 | + * @param int $reuseExisting |
|
124 | + * @param int $parentId |
|
125 | + * @param array | null $cacheData existing data in the cache for the file to be scanned |
|
126 | + * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
127 | + * @return array an array of metadata of the scanned file |
|
128 | + * @throws \OC\ServerNotAvailableException |
|
129 | + * @throws \OCP\Lock\LockedException |
|
130 | + */ |
|
131 | + public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) { |
|
132 | + if ($file !== '') { |
|
133 | + try { |
|
134 | + $this->storage->verifyPath(dirname($file), basename($file)); |
|
135 | + } catch (\Exception $e) { |
|
136 | + return null; |
|
137 | + } |
|
138 | + } |
|
139 | + // only proceed if $file is not a partial file nor a blacklisted file |
|
140 | + if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) { |
|
141 | + |
|
142 | + //acquire a lock |
|
143 | + if ($lock) { |
|
144 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
145 | + $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
146 | + } |
|
147 | + } |
|
148 | + |
|
149 | + try { |
|
150 | + $data = $this->getData($file); |
|
151 | + } catch (ForbiddenException $e) { |
|
152 | + if ($lock) { |
|
153 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
154 | + $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
155 | + } |
|
156 | + } |
|
157 | + |
|
158 | + return null; |
|
159 | + } |
|
160 | + |
|
161 | + try { |
|
162 | + if ($data) { |
|
163 | + |
|
164 | + // pre-emit only if it was a file. By that we avoid counting/treating folders as files |
|
165 | + if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
166 | + $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId)); |
|
167 | + \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
168 | + } |
|
169 | + |
|
170 | + $parent = dirname($file); |
|
171 | + if ($parent === '.' or $parent === '/') { |
|
172 | + $parent = ''; |
|
173 | + } |
|
174 | + if ($parentId === -1) { |
|
175 | + $parentId = $this->cache->getParentId($file); |
|
176 | + } |
|
177 | + |
|
178 | + // scan the parent if it's not in the cache (id -1) and the current file is not the root folder |
|
179 | + if ($file and $parentId === -1) { |
|
180 | + $parentData = $this->scanFile($parent); |
|
181 | + if (!$parentData) { |
|
182 | + return null; |
|
183 | + } |
|
184 | + $parentId = $parentData['fileid']; |
|
185 | + } |
|
186 | + if ($parent) { |
|
187 | + $data['parent'] = $parentId; |
|
188 | + } |
|
189 | + if (is_null($cacheData)) { |
|
190 | + /** @var CacheEntry $cacheData */ |
|
191 | + $cacheData = $this->cache->get($file); |
|
192 | + } |
|
193 | + if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) { |
|
194 | + // prevent empty etag |
|
195 | + if (empty($cacheData['etag'])) { |
|
196 | + $etag = $data['etag']; |
|
197 | + } else { |
|
198 | + $etag = $cacheData['etag']; |
|
199 | + } |
|
200 | + $fileId = $cacheData['fileid']; |
|
201 | + $data['fileid'] = $fileId; |
|
202 | + // only reuse data if the file hasn't explicitly changed |
|
203 | + if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) { |
|
204 | + $data['mtime'] = $cacheData['mtime']; |
|
205 | + if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) { |
|
206 | + $data['size'] = $cacheData['size']; |
|
207 | + } |
|
208 | + if ($reuseExisting & self::REUSE_ETAG) { |
|
209 | + $data['etag'] = $etag; |
|
210 | + } |
|
211 | + } |
|
212 | + // Only update metadata that has changed |
|
213 | + $newData = array_diff_assoc($data, $cacheData->getData()); |
|
214 | + } else { |
|
215 | + $newData = $data; |
|
216 | + $fileId = -1; |
|
217 | + } |
|
218 | + if (!empty($newData)) { |
|
219 | + // Reset the checksum if the data has changed |
|
220 | + $newData['checksum'] = ''; |
|
221 | + $data['fileid'] = $this->addToCache($file, $newData, $fileId); |
|
222 | + } |
|
223 | + if (isset($cacheData['size'])) { |
|
224 | + $data['oldSize'] = $cacheData['size']; |
|
225 | + } else { |
|
226 | + $data['oldSize'] = 0; |
|
227 | + } |
|
228 | + |
|
229 | + if (isset($cacheData['encrypted'])) { |
|
230 | + $data['encrypted'] = $cacheData['encrypted']; |
|
231 | + } |
|
232 | + |
|
233 | + // post-emit only if it was a file. By that we avoid counting/treating folders as files |
|
234 | + if ($data['mimetype'] !== 'httpd/unix-directory') { |
|
235 | + $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId)); |
|
236 | + \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId)); |
|
237 | + } |
|
238 | + |
|
239 | + } else { |
|
240 | + $this->removeFromCache($file); |
|
241 | + } |
|
242 | + } catch (\Exception $e) { |
|
243 | + if ($lock) { |
|
244 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
245 | + $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
246 | + } |
|
247 | + } |
|
248 | + throw $e; |
|
249 | + } |
|
250 | + |
|
251 | + //release the acquired lock |
|
252 | + if ($lock) { |
|
253 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
254 | + $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
255 | + } |
|
256 | + } |
|
257 | + |
|
258 | + if ($data && !isset($data['encrypted'])) { |
|
259 | + $data['encrypted'] = false; |
|
260 | + } |
|
261 | + return $data; |
|
262 | + } |
|
263 | + |
|
264 | + return null; |
|
265 | + } |
|
266 | + |
|
267 | + protected function removeFromCache($path) { |
|
268 | + \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path)); |
|
269 | + $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path)); |
|
270 | + if ($this->cacheActive) { |
|
271 | + $this->cache->remove($path); |
|
272 | + } |
|
273 | + } |
|
274 | + |
|
275 | + /** |
|
276 | + * @param string $path |
|
277 | + * @param array $data |
|
278 | + * @param int $fileId |
|
279 | + * @return int the id of the added file |
|
280 | + */ |
|
281 | + protected function addToCache($path, $data, $fileId = -1) { |
|
282 | + if (isset($data['scan_permissions'])) { |
|
283 | + $data['permissions'] = $data['scan_permissions']; |
|
284 | + } |
|
285 | + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
286 | + $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data)); |
|
287 | + if ($this->cacheActive) { |
|
288 | + if ($fileId !== -1) { |
|
289 | + $this->cache->update($fileId, $data); |
|
290 | + return $fileId; |
|
291 | + } else { |
|
292 | + return $this->cache->put($path, $data); |
|
293 | + } |
|
294 | + } else { |
|
295 | + return -1; |
|
296 | + } |
|
297 | + } |
|
298 | + |
|
299 | + /** |
|
300 | + * @param string $path |
|
301 | + * @param array $data |
|
302 | + * @param int $fileId |
|
303 | + */ |
|
304 | + protected function updateCache($path, $data, $fileId = -1) { |
|
305 | + \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data)); |
|
306 | + $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data)); |
|
307 | + if ($this->cacheActive) { |
|
308 | + if ($fileId !== -1) { |
|
309 | + $this->cache->update($fileId, $data); |
|
310 | + } else { |
|
311 | + $this->cache->put($path, $data); |
|
312 | + } |
|
313 | + } |
|
314 | + } |
|
315 | + |
|
316 | + /** |
|
317 | + * scan a folder and all it's children |
|
318 | + * |
|
319 | + * @param string $path |
|
320 | + * @param bool $recursive |
|
321 | + * @param int $reuse |
|
322 | + * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
323 | + * @return array an array of the meta data of the scanned file or folder |
|
324 | + */ |
|
325 | + public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) { |
|
326 | + if ($reuse === -1) { |
|
327 | + $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
328 | + } |
|
329 | + if ($lock) { |
|
330 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
331 | + $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
332 | + $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
333 | + } |
|
334 | + } |
|
335 | + try { |
|
336 | + $data = $this->scanFile($path, $reuse, -1, null, $lock); |
|
337 | + if ($data and $data['mimetype'] === 'httpd/unix-directory') { |
|
338 | + $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock); |
|
339 | + $data['size'] = $size; |
|
340 | + } |
|
341 | + } finally { |
|
342 | + if ($lock) { |
|
343 | + if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
|
344 | + $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
|
345 | + $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
346 | + } |
|
347 | + } |
|
348 | + } |
|
349 | + return $data; |
|
350 | + } |
|
351 | + |
|
352 | + /** |
|
353 | + * Get the children currently in the cache |
|
354 | + * |
|
355 | + * @param int $folderId |
|
356 | + * @return array[] |
|
357 | + */ |
|
358 | + protected function getExistingChildren($folderId) { |
|
359 | + $existingChildren = array(); |
|
360 | + $children = $this->cache->getFolderContentsById($folderId); |
|
361 | + foreach ($children as $child) { |
|
362 | + $existingChildren[$child['name']] = $child; |
|
363 | + } |
|
364 | + return $existingChildren; |
|
365 | + } |
|
366 | + |
|
367 | + /** |
|
368 | + * Get the children from the storage |
|
369 | + * |
|
370 | + * @param string $folder |
|
371 | + * @return string[] |
|
372 | + */ |
|
373 | + protected function getNewChildren($folder) { |
|
374 | + $children = array(); |
|
375 | + if ($dh = $this->storage->opendir($folder)) { |
|
376 | + if (is_resource($dh)) { |
|
377 | + while (($file = readdir($dh)) !== false) { |
|
378 | + if (!Filesystem::isIgnoredDir($file)) { |
|
379 | + $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/'); |
|
380 | + } |
|
381 | + } |
|
382 | + } |
|
383 | + } |
|
384 | + return $children; |
|
385 | + } |
|
386 | + |
|
387 | + /** |
|
388 | + * scan all the files and folders in a folder |
|
389 | + * |
|
390 | + * @param string $path |
|
391 | + * @param bool $recursive |
|
392 | + * @param int $reuse |
|
393 | + * @param int $folderId id for the folder to be scanned |
|
394 | + * @param bool $lock set to false to disable getting an additional read lock during scanning |
|
395 | + * @return int the size of the scanned folder or -1 if the size is unknown at this stage |
|
396 | + */ |
|
397 | + protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) { |
|
398 | + if ($reuse === -1) { |
|
399 | + $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; |
|
400 | + } |
|
401 | + $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId)); |
|
402 | + $size = 0; |
|
403 | + if (!is_null($folderId)) { |
|
404 | + $folderId = $this->cache->getId($path); |
|
405 | + } |
|
406 | + $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size); |
|
407 | + |
|
408 | + foreach ($childQueue as $child => $childId) { |
|
409 | + $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock); |
|
410 | + if ($childSize === -1) { |
|
411 | + $size = -1; |
|
412 | + } else if ($size !== -1) { |
|
413 | + $size += $childSize; |
|
414 | + } |
|
415 | + } |
|
416 | + if ($this->cacheActive) { |
|
417 | + $this->cache->update($folderId, array('size' => $size)); |
|
418 | + } |
|
419 | + $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId)); |
|
420 | + return $size; |
|
421 | + } |
|
422 | + |
|
423 | + private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) { |
|
424 | + // we put this in it's own function so it cleans up the memory before we start recursing |
|
425 | + $existingChildren = $this->getExistingChildren($folderId); |
|
426 | + $newChildren = $this->getNewChildren($path); |
|
427 | + |
|
428 | + if ($this->useTransactions) { |
|
429 | + \OC::$server->getDatabaseConnection()->beginTransaction(); |
|
430 | + } |
|
431 | + |
|
432 | + $exceptionOccurred = false; |
|
433 | + $childQueue = []; |
|
434 | + foreach ($newChildren as $file) { |
|
435 | + $child = $path ? $path . '/' . $file : $file; |
|
436 | + try { |
|
437 | + $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; |
|
438 | + $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); |
|
439 | + if ($data) { |
|
440 | + if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) { |
|
441 | + $childQueue[$child] = $data['fileid']; |
|
442 | + } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) { |
|
443 | + // only recurse into folders which aren't fully scanned |
|
444 | + $childQueue[$child] = $data['fileid']; |
|
445 | + } else if ($data['size'] === -1) { |
|
446 | + $size = -1; |
|
447 | + } else if ($size !== -1) { |
|
448 | + $size += $data['size']; |
|
449 | + } |
|
450 | + } |
|
451 | + } catch (\Doctrine\DBAL\DBALException $ex) { |
|
452 | + // might happen if inserting duplicate while a scanning |
|
453 | + // process is running in parallel |
|
454 | + // log and ignore |
|
455 | + if ($this->useTransactions) { |
|
456 | + \OC::$server->getDatabaseConnection()->rollback(); |
|
457 | + \OC::$server->getDatabaseConnection()->beginTransaction(); |
|
458 | + } |
|
459 | + \OC::$server->getLogger()->logException($ex, [ |
|
460 | + 'message' => 'Exception while scanning file "' . $child . '"', |
|
461 | + 'level' => ILogger::DEBUG, |
|
462 | + 'app' => 'core', |
|
463 | + ]); |
|
464 | + $exceptionOccurred = true; |
|
465 | + } catch (\OCP\Lock\LockedException $e) { |
|
466 | + if ($this->useTransactions) { |
|
467 | + \OC::$server->getDatabaseConnection()->rollback(); |
|
468 | + } |
|
469 | + throw $e; |
|
470 | + } |
|
471 | + } |
|
472 | + $removedChildren = \array_diff(array_keys($existingChildren), $newChildren); |
|
473 | + foreach ($removedChildren as $childName) { |
|
474 | + $child = $path ? $path . '/' . $childName : $childName; |
|
475 | + $this->removeFromCache($child); |
|
476 | + } |
|
477 | + if ($this->useTransactions) { |
|
478 | + \OC::$server->getDatabaseConnection()->commit(); |
|
479 | + } |
|
480 | + if ($exceptionOccurred) { |
|
481 | + // It might happen that the parallel scan process has already |
|
482 | + // inserted mimetypes but those weren't available yet inside the transaction |
|
483 | + // To make sure to have the updated mime types in such cases, |
|
484 | + // we reload them here |
|
485 | + \OC::$server->getMimeTypeLoader()->reset(); |
|
486 | + } |
|
487 | + return $childQueue; |
|
488 | + } |
|
489 | + |
|
490 | + /** |
|
491 | + * check if the file should be ignored when scanning |
|
492 | + * NOTE: files with a '.part' extension are ignored as well! |
|
493 | + * prevents unfinished put requests to be scanned |
|
494 | + * |
|
495 | + * @param string $file |
|
496 | + * @return boolean |
|
497 | + */ |
|
498 | + public static function isPartialFile($file) { |
|
499 | + if (pathinfo($file, PATHINFO_EXTENSION) === 'part') { |
|
500 | + return true; |
|
501 | + } |
|
502 | + if (strpos($file, '.part/') !== false) { |
|
503 | + return true; |
|
504 | + } |
|
505 | + |
|
506 | + return false; |
|
507 | + } |
|
508 | + |
|
509 | + /** |
|
510 | + * walk over any folders that are not fully scanned yet and scan them |
|
511 | + */ |
|
512 | + public function backgroundScan() { |
|
513 | + if (!$this->cache->inCache('')) { |
|
514 | + $this->runBackgroundScanJob(function () { |
|
515 | + $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); |
|
516 | + }, ''); |
|
517 | + } else { |
|
518 | + $lastPath = null; |
|
519 | + while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { |
|
520 | + $this->runBackgroundScanJob(function () use ($path) { |
|
521 | + $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); |
|
522 | + }, $path); |
|
523 | + // FIXME: this won't proceed with the next item, needs revamping of getIncomplete() |
|
524 | + // to make this possible |
|
525 | + $lastPath = $path; |
|
526 | + } |
|
527 | + } |
|
528 | + } |
|
529 | + |
|
530 | + private function runBackgroundScanJob(callable $callback, $path) { |
|
531 | + try { |
|
532 | + $callback(); |
|
533 | + \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path)); |
|
534 | + if ($this->cacheActive && $this->cache instanceof Cache) { |
|
535 | + $this->cache->correctFolderSize($path); |
|
536 | + } |
|
537 | + } catch (\OCP\Files\StorageInvalidException $e) { |
|
538 | + // skip unavailable storages |
|
539 | + } catch (\OCP\Files\StorageNotAvailableException $e) { |
|
540 | + // skip unavailable storages |
|
541 | + } catch (\OCP\Files\ForbiddenException $e) { |
|
542 | + // skip forbidden storages |
|
543 | + } catch (\OCP\Lock\LockedException $e) { |
|
544 | + // skip unavailable storages |
|
545 | + } |
|
546 | + } |
|
547 | + |
|
548 | + /** |
|
549 | + * Set whether the cache is affected by scan operations |
|
550 | + * |
|
551 | + * @param boolean $active The active state of the cache |
|
552 | + */ |
|
553 | + public function setCacheActive($active) { |
|
554 | + $this->cacheActive = $active; |
|
555 | + } |
|
556 | 556 | } |
@@ -328,7 +328,7 @@ discard block |
||
328 | 328 | } |
329 | 329 | if ($lock) { |
330 | 330 | if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
331 | - $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
331 | + $this->storage->acquireLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
332 | 332 | $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
333 | 333 | } |
334 | 334 | } |
@@ -342,7 +342,7 @@ discard block |
||
342 | 342 | if ($lock) { |
343 | 343 | if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { |
344 | 344 | $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider); |
345 | - $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
345 | + $this->storage->releaseLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); |
|
346 | 346 | } |
347 | 347 | } |
348 | 348 | } |
@@ -432,7 +432,7 @@ discard block |
||
432 | 432 | $exceptionOccurred = false; |
433 | 433 | $childQueue = []; |
434 | 434 | foreach ($newChildren as $file) { |
435 | - $child = $path ? $path . '/' . $file : $file; |
|
435 | + $child = $path ? $path.'/'.$file : $file; |
|
436 | 436 | try { |
437 | 437 | $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; |
438 | 438 | $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); |
@@ -457,7 +457,7 @@ discard block |
||
457 | 457 | \OC::$server->getDatabaseConnection()->beginTransaction(); |
458 | 458 | } |
459 | 459 | \OC::$server->getLogger()->logException($ex, [ |
460 | - 'message' => 'Exception while scanning file "' . $child . '"', |
|
460 | + 'message' => 'Exception while scanning file "'.$child.'"', |
|
461 | 461 | 'level' => ILogger::DEBUG, |
462 | 462 | 'app' => 'core', |
463 | 463 | ]); |
@@ -471,7 +471,7 @@ discard block |
||
471 | 471 | } |
472 | 472 | $removedChildren = \array_diff(array_keys($existingChildren), $newChildren); |
473 | 473 | foreach ($removedChildren as $childName) { |
474 | - $child = $path ? $path . '/' . $childName : $childName; |
|
474 | + $child = $path ? $path.'/'.$childName : $childName; |
|
475 | 475 | $this->removeFromCache($child); |
476 | 476 | } |
477 | 477 | if ($this->useTransactions) { |
@@ -511,13 +511,13 @@ discard block |
||
511 | 511 | */ |
512 | 512 | public function backgroundScan() { |
513 | 513 | if (!$this->cache->inCache('')) { |
514 | - $this->runBackgroundScanJob(function () { |
|
514 | + $this->runBackgroundScanJob(function() { |
|
515 | 515 | $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG); |
516 | 516 | }, ''); |
517 | 517 | } else { |
518 | 518 | $lastPath = null; |
519 | 519 | while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) { |
520 | - $this->runBackgroundScanJob(function () use ($path) { |
|
520 | + $this->runBackgroundScanJob(function() use ($path) { |
|
521 | 521 | $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE); |
522 | 522 | }, $path); |
523 | 523 | // 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 | */ |
@@ -44,350 +44,350 @@ |
||
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 | - $mount_id = $row['mount_id']; |
|
200 | - if (!is_null($mount_id)) { |
|
201 | - $mount_id = (int) $mount_id; |
|
202 | - } |
|
203 | - return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : ''); |
|
204 | - } |
|
205 | - |
|
206 | - /** |
|
207 | - * @param IUser $user |
|
208 | - * @return ICachedMountInfo[] |
|
209 | - */ |
|
210 | - public function getMountsForUser(IUser $user) { |
|
211 | - if (!isset($this->mountsForUsers[$user->getUID()])) { |
|
212 | - $builder = $this->connection->getQueryBuilder(); |
|
213 | - $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
214 | - ->from('mounts', 'm') |
|
215 | - ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
216 | - ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID()))); |
|
217 | - |
|
218 | - $rows = $query->execute()->fetchAll(); |
|
219 | - |
|
220 | - $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
221 | - } |
|
222 | - return $this->mountsForUsers[$user->getUID()]; |
|
223 | - } |
|
224 | - |
|
225 | - /** |
|
226 | - * @param int $numericStorageId |
|
227 | - * @param string|null $user limit the results to a single user |
|
228 | - * @return CachedMountInfo[] |
|
229 | - */ |
|
230 | - public function getMountsForStorageId($numericStorageId, $user = null) { |
|
231 | - $builder = $this->connection->getQueryBuilder(); |
|
232 | - $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
233 | - ->from('mounts', 'm') |
|
234 | - ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
235 | - ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT))); |
|
236 | - |
|
237 | - if ($user) { |
|
238 | - $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user))); |
|
239 | - } |
|
240 | - |
|
241 | - $rows = $query->execute()->fetchAll(); |
|
242 | - |
|
243 | - return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
244 | - } |
|
245 | - |
|
246 | - /** |
|
247 | - * @param int $rootFileId |
|
248 | - * @return CachedMountInfo[] |
|
249 | - */ |
|
250 | - public function getMountsForRootId($rootFileId) { |
|
251 | - $builder = $this->connection->getQueryBuilder(); |
|
252 | - $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
253 | - ->from('mounts', 'm') |
|
254 | - ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
255 | - ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT))); |
|
256 | - |
|
257 | - $rows = $query->execute()->fetchAll(); |
|
258 | - |
|
259 | - return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
260 | - } |
|
261 | - |
|
262 | - /** |
|
263 | - * @param $fileId |
|
264 | - * @return array |
|
265 | - * @throws \OCP\Files\NotFoundException |
|
266 | - */ |
|
267 | - private function getCacheInfoFromFileId($fileId) { |
|
268 | - if (!isset($this->cacheInfoCache[$fileId])) { |
|
269 | - $builder = $this->connection->getQueryBuilder(); |
|
270 | - $query = $builder->select('storage', 'path', 'mimetype') |
|
271 | - ->from('filecache') |
|
272 | - ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT))); |
|
273 | - |
|
274 | - $row = $query->execute()->fetch(); |
|
275 | - if (is_array($row)) { |
|
276 | - $this->cacheInfoCache[$fileId] = [ |
|
277 | - (int)$row['storage'], |
|
278 | - $row['path'], |
|
279 | - (int)$row['mimetype'] |
|
280 | - ]; |
|
281 | - } else { |
|
282 | - throw new NotFoundException('File with id "' . $fileId . '" not found'); |
|
283 | - } |
|
284 | - } |
|
285 | - return $this->cacheInfoCache[$fileId]; |
|
286 | - } |
|
287 | - |
|
288 | - /** |
|
289 | - * @param int $fileId |
|
290 | - * @param string|null $user optionally restrict the results to a single user |
|
291 | - * @return ICachedMountFileInfo[] |
|
292 | - * @since 9.0.0 |
|
293 | - */ |
|
294 | - public function getMountsForFileId($fileId, $user = null) { |
|
295 | - try { |
|
296 | - list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId); |
|
297 | - } catch (NotFoundException $e) { |
|
298 | - return []; |
|
299 | - } |
|
300 | - $mountsForStorage = $this->getMountsForStorageId($storageId, $user); |
|
301 | - |
|
302 | - // filter mounts that are from the same storage but a different directory |
|
303 | - $filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
304 | - if ($fileId === $mount->getRootId()) { |
|
305 | - return true; |
|
306 | - } |
|
307 | - $internalMountPath = $mount->getRootInternalPath(); |
|
308 | - |
|
309 | - return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/'; |
|
310 | - }); |
|
311 | - |
|
312 | - return array_map(function (ICachedMountInfo $mount) use ($internalPath) { |
|
313 | - return new CachedMountFileInfo( |
|
314 | - $mount->getUser(), |
|
315 | - $mount->getStorageId(), |
|
316 | - $mount->getRootId(), |
|
317 | - $mount->getMountPoint(), |
|
318 | - $mount->getMountId(), |
|
319 | - $mount->getRootInternalPath(), |
|
320 | - $internalPath |
|
321 | - ); |
|
322 | - }, $filteredMounts); |
|
323 | - } |
|
324 | - |
|
325 | - /** |
|
326 | - * Remove all cached mounts for a user |
|
327 | - * |
|
328 | - * @param IUser $user |
|
329 | - */ |
|
330 | - public function removeUserMounts(IUser $user) { |
|
331 | - $builder = $this->connection->getQueryBuilder(); |
|
332 | - |
|
333 | - $query = $builder->delete('mounts') |
|
334 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID()))); |
|
335 | - $query->execute(); |
|
336 | - } |
|
337 | - |
|
338 | - public function removeUserStorageMount($storageId, $userId) { |
|
339 | - $builder = $this->connection->getQueryBuilder(); |
|
340 | - |
|
341 | - $query = $builder->delete('mounts') |
|
342 | - ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId))) |
|
343 | - ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
344 | - $query->execute(); |
|
345 | - } |
|
346 | - |
|
347 | - public function remoteStorageMounts($storageId) { |
|
348 | - $builder = $this->connection->getQueryBuilder(); |
|
349 | - |
|
350 | - $query = $builder->delete('mounts') |
|
351 | - ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
352 | - $query->execute(); |
|
353 | - } |
|
354 | - |
|
355 | - /** |
|
356 | - * @param array $users |
|
357 | - * @return array |
|
358 | - * @suppress SqlInjectionChecker |
|
359 | - */ |
|
360 | - public function getUsedSpaceForUsers(array $users) { |
|
361 | - $builder = $this->connection->getQueryBuilder(); |
|
362 | - |
|
363 | - $slash = $builder->createNamedParameter('/'); |
|
364 | - |
|
365 | - $mountPoint = $builder->func()->concat( |
|
366 | - $builder->func()->concat($slash, 'user_id'), |
|
367 | - $slash |
|
368 | - ); |
|
369 | - |
|
370 | - $userIds = array_map(function (IUser $user) { |
|
371 | - return $user->getUID(); |
|
372 | - }, $users); |
|
373 | - |
|
374 | - $query = $builder->select('m.user_id', 'f.size') |
|
375 | - ->from('mounts', 'm') |
|
376 | - ->innerJoin('m', 'filecache', 'f', |
|
377 | - $builder->expr()->andX( |
|
378 | - $builder->expr()->eq('m.storage_id', 'f.storage'), |
|
379 | - $builder->expr()->eq('f.path', $builder->createNamedParameter('files')) |
|
380 | - )) |
|
381 | - ->where($builder->expr()->eq('m.mount_point', $mountPoint)) |
|
382 | - ->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY))); |
|
383 | - |
|
384 | - $result = $query->execute(); |
|
385 | - |
|
386 | - $results = []; |
|
387 | - while ($row = $result->fetch()) { |
|
388 | - $results[$row['user_id']] = $row['size']; |
|
389 | - } |
|
390 | - $result->closeCursor(); |
|
391 | - return $results; |
|
392 | - } |
|
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 | + $mount_id = $row['mount_id']; |
|
200 | + if (!is_null($mount_id)) { |
|
201 | + $mount_id = (int) $mount_id; |
|
202 | + } |
|
203 | + return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : ''); |
|
204 | + } |
|
205 | + |
|
206 | + /** |
|
207 | + * @param IUser $user |
|
208 | + * @return ICachedMountInfo[] |
|
209 | + */ |
|
210 | + public function getMountsForUser(IUser $user) { |
|
211 | + if (!isset($this->mountsForUsers[$user->getUID()])) { |
|
212 | + $builder = $this->connection->getQueryBuilder(); |
|
213 | + $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
214 | + ->from('mounts', 'm') |
|
215 | + ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
216 | + ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID()))); |
|
217 | + |
|
218 | + $rows = $query->execute()->fetchAll(); |
|
219 | + |
|
220 | + $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
221 | + } |
|
222 | + return $this->mountsForUsers[$user->getUID()]; |
|
223 | + } |
|
224 | + |
|
225 | + /** |
|
226 | + * @param int $numericStorageId |
|
227 | + * @param string|null $user limit the results to a single user |
|
228 | + * @return CachedMountInfo[] |
|
229 | + */ |
|
230 | + public function getMountsForStorageId($numericStorageId, $user = null) { |
|
231 | + $builder = $this->connection->getQueryBuilder(); |
|
232 | + $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
233 | + ->from('mounts', 'm') |
|
234 | + ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
235 | + ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT))); |
|
236 | + |
|
237 | + if ($user) { |
|
238 | + $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user))); |
|
239 | + } |
|
240 | + |
|
241 | + $rows = $query->execute()->fetchAll(); |
|
242 | + |
|
243 | + return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
244 | + } |
|
245 | + |
|
246 | + /** |
|
247 | + * @param int $rootFileId |
|
248 | + * @return CachedMountInfo[] |
|
249 | + */ |
|
250 | + public function getMountsForRootId($rootFileId) { |
|
251 | + $builder = $this->connection->getQueryBuilder(); |
|
252 | + $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path') |
|
253 | + ->from('mounts', 'm') |
|
254 | + ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid')) |
|
255 | + ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT))); |
|
256 | + |
|
257 | + $rows = $query->execute()->fetchAll(); |
|
258 | + |
|
259 | + return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows)); |
|
260 | + } |
|
261 | + |
|
262 | + /** |
|
263 | + * @param $fileId |
|
264 | + * @return array |
|
265 | + * @throws \OCP\Files\NotFoundException |
|
266 | + */ |
|
267 | + private function getCacheInfoFromFileId($fileId) { |
|
268 | + if (!isset($this->cacheInfoCache[$fileId])) { |
|
269 | + $builder = $this->connection->getQueryBuilder(); |
|
270 | + $query = $builder->select('storage', 'path', 'mimetype') |
|
271 | + ->from('filecache') |
|
272 | + ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT))); |
|
273 | + |
|
274 | + $row = $query->execute()->fetch(); |
|
275 | + if (is_array($row)) { |
|
276 | + $this->cacheInfoCache[$fileId] = [ |
|
277 | + (int)$row['storage'], |
|
278 | + $row['path'], |
|
279 | + (int)$row['mimetype'] |
|
280 | + ]; |
|
281 | + } else { |
|
282 | + throw new NotFoundException('File with id "' . $fileId . '" not found'); |
|
283 | + } |
|
284 | + } |
|
285 | + return $this->cacheInfoCache[$fileId]; |
|
286 | + } |
|
287 | + |
|
288 | + /** |
|
289 | + * @param int $fileId |
|
290 | + * @param string|null $user optionally restrict the results to a single user |
|
291 | + * @return ICachedMountFileInfo[] |
|
292 | + * @since 9.0.0 |
|
293 | + */ |
|
294 | + public function getMountsForFileId($fileId, $user = null) { |
|
295 | + try { |
|
296 | + list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId); |
|
297 | + } catch (NotFoundException $e) { |
|
298 | + return []; |
|
299 | + } |
|
300 | + $mountsForStorage = $this->getMountsForStorageId($storageId, $user); |
|
301 | + |
|
302 | + // filter mounts that are from the same storage but a different directory |
|
303 | + $filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
304 | + if ($fileId === $mount->getRootId()) { |
|
305 | + return true; |
|
306 | + } |
|
307 | + $internalMountPath = $mount->getRootInternalPath(); |
|
308 | + |
|
309 | + return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/'; |
|
310 | + }); |
|
311 | + |
|
312 | + return array_map(function (ICachedMountInfo $mount) use ($internalPath) { |
|
313 | + return new CachedMountFileInfo( |
|
314 | + $mount->getUser(), |
|
315 | + $mount->getStorageId(), |
|
316 | + $mount->getRootId(), |
|
317 | + $mount->getMountPoint(), |
|
318 | + $mount->getMountId(), |
|
319 | + $mount->getRootInternalPath(), |
|
320 | + $internalPath |
|
321 | + ); |
|
322 | + }, $filteredMounts); |
|
323 | + } |
|
324 | + |
|
325 | + /** |
|
326 | + * Remove all cached mounts for a user |
|
327 | + * |
|
328 | + * @param IUser $user |
|
329 | + */ |
|
330 | + public function removeUserMounts(IUser $user) { |
|
331 | + $builder = $this->connection->getQueryBuilder(); |
|
332 | + |
|
333 | + $query = $builder->delete('mounts') |
|
334 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID()))); |
|
335 | + $query->execute(); |
|
336 | + } |
|
337 | + |
|
338 | + public function removeUserStorageMount($storageId, $userId) { |
|
339 | + $builder = $this->connection->getQueryBuilder(); |
|
340 | + |
|
341 | + $query = $builder->delete('mounts') |
|
342 | + ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId))) |
|
343 | + ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
344 | + $query->execute(); |
|
345 | + } |
|
346 | + |
|
347 | + public function remoteStorageMounts($storageId) { |
|
348 | + $builder = $this->connection->getQueryBuilder(); |
|
349 | + |
|
350 | + $query = $builder->delete('mounts') |
|
351 | + ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))); |
|
352 | + $query->execute(); |
|
353 | + } |
|
354 | + |
|
355 | + /** |
|
356 | + * @param array $users |
|
357 | + * @return array |
|
358 | + * @suppress SqlInjectionChecker |
|
359 | + */ |
|
360 | + public function getUsedSpaceForUsers(array $users) { |
|
361 | + $builder = $this->connection->getQueryBuilder(); |
|
362 | + |
|
363 | + $slash = $builder->createNamedParameter('/'); |
|
364 | + |
|
365 | + $mountPoint = $builder->func()->concat( |
|
366 | + $builder->func()->concat($slash, 'user_id'), |
|
367 | + $slash |
|
368 | + ); |
|
369 | + |
|
370 | + $userIds = array_map(function (IUser $user) { |
|
371 | + return $user->getUID(); |
|
372 | + }, $users); |
|
373 | + |
|
374 | + $query = $builder->select('m.user_id', 'f.size') |
|
375 | + ->from('mounts', 'm') |
|
376 | + ->innerJoin('m', 'filecache', 'f', |
|
377 | + $builder->expr()->andX( |
|
378 | + $builder->expr()->eq('m.storage_id', 'f.storage'), |
|
379 | + $builder->expr()->eq('f.path', $builder->createNamedParameter('files')) |
|
380 | + )) |
|
381 | + ->where($builder->expr()->eq('m.mount_point', $mountPoint)) |
|
382 | + ->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY))); |
|
383 | + |
|
384 | + $result = $query->execute(); |
|
385 | + |
|
386 | + $results = []; |
|
387 | + while ($row = $result->fetch()) { |
|
388 | + $results[$row['user_id']] = $row['size']; |
|
389 | + } |
|
390 | + $result->closeCursor(); |
|
391 | + return $results; |
|
392 | + } |
|
393 | 393 | } |
@@ -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 | |
@@ -200,7 +200,7 @@ discard block |
||
200 | 200 | if (!is_null($mount_id)) { |
201 | 201 | $mount_id = (int) $mount_id; |
202 | 202 | } |
203 | - return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : ''); |
|
203 | + return new CachedMountInfo($user, (int) $row['storage_id'], (int) $row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : ''); |
|
204 | 204 | } |
205 | 205 | |
206 | 206 | /** |
@@ -274,12 +274,12 @@ discard block |
||
274 | 274 | $row = $query->execute()->fetch(); |
275 | 275 | if (is_array($row)) { |
276 | 276 | $this->cacheInfoCache[$fileId] = [ |
277 | - (int)$row['storage'], |
|
277 | + (int) $row['storage'], |
|
278 | 278 | $row['path'], |
279 | - (int)$row['mimetype'] |
|
279 | + (int) $row['mimetype'] |
|
280 | 280 | ]; |
281 | 281 | } else { |
282 | - throw new NotFoundException('File with id "' . $fileId . '" not found'); |
|
282 | + throw new NotFoundException('File with id "'.$fileId.'" not found'); |
|
283 | 283 | } |
284 | 284 | } |
285 | 285 | return $this->cacheInfoCache[$fileId]; |
@@ -300,16 +300,16 @@ discard block |
||
300 | 300 | $mountsForStorage = $this->getMountsForStorageId($storageId, $user); |
301 | 301 | |
302 | 302 | // filter mounts that are from the same storage but a different directory |
303 | - $filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
303 | + $filteredMounts = array_filter($mountsForStorage, function(ICachedMountInfo $mount) use ($internalPath, $fileId) { |
|
304 | 304 | if ($fileId === $mount->getRootId()) { |
305 | 305 | return true; |
306 | 306 | } |
307 | 307 | $internalMountPath = $mount->getRootInternalPath(); |
308 | 308 | |
309 | - return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/'; |
|
309 | + return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath.'/'; |
|
310 | 310 | }); |
311 | 311 | |
312 | - return array_map(function (ICachedMountInfo $mount) use ($internalPath) { |
|
312 | + return array_map(function(ICachedMountInfo $mount) use ($internalPath) { |
|
313 | 313 | return new CachedMountFileInfo( |
314 | 314 | $mount->getUser(), |
315 | 315 | $mount->getStorageId(), |
@@ -367,7 +367,7 @@ discard block |
||
367 | 367 | $slash |
368 | 368 | ); |
369 | 369 | |
370 | - $userIds = array_map(function (IUser $user) { |
|
370 | + $userIds = array_map(function(IUser $user) { |
|
371 | 371 | return $user->getUID(); |
372 | 372 | }, $users); |
373 | 373 |