Completed
Pull Request — master (#3998)
by Morris
22:58 queued 12:02
created
apps/files_trashbin/lib/Trashbin.php 1 patch
Indentation   +937 added lines, -937 removed lines patch added patch discarded remove patch
@@ -47,941 +47,941 @@
 block discarded – undo
47 47
 
48 48
 class Trashbin {
49 49
 
50
-	// unit: percentage; 50% of available disk space/quota
51
-	const DEFAULTMAXSIZE = 50;
52
-
53
-	/**
54
-	 * Whether versions have already be rescanned during this PHP request
55
-	 *
56
-	 * @var bool
57
-	 */
58
-	private static $scannedVersions = false;
59
-
60
-	/**
61
-	 * Ensure we don't need to scan the file during the move to trash
62
-	 * by triggering the scan in the pre-hook
63
-	 *
64
-	 * @param array $params
65
-	 */
66
-	public static function ensureFileScannedHook($params) {
67
-		try {
68
-			self::getUidAndFilename($params['path']);
69
-		} catch (NotFoundException $e) {
70
-			// nothing to scan for non existing files
71
-		}
72
-	}
73
-
74
-	/**
75
-	 * get the UID of the owner of the file and the path to the file relative to
76
-	 * owners files folder
77
-	 *
78
-	 * @param string $filename
79
-	 * @return array
80
-	 * @throws \OC\User\NoUserException
81
-	 */
82
-	public static function getUidAndFilename($filename) {
83
-		$uid = Filesystem::getOwner($filename);
84
-		$userManager = \OC::$server->getUserManager();
85
-		// if the user with the UID doesn't exists, e.g. because the UID points
86
-		// to a remote user with a federated cloud ID we use the current logged-in
87
-		// user. We need a valid local user to move the file to the right trash bin
88
-		if (!$userManager->userExists($uid)) {
89
-			$uid = User::getUser();
90
-		}
91
-		if (!$uid) {
92
-			// no owner, usually because of share link from ext storage
93
-			return [null, null];
94
-		}
95
-		Filesystem::initMountPoints($uid);
96
-		if ($uid != User::getUser()) {
97
-			$info = Filesystem::getFileInfo($filename);
98
-			$ownerView = new View('/' . $uid . '/files');
99
-			try {
100
-				$filename = $ownerView->getPath($info['fileid']);
101
-			} catch (NotFoundException $e) {
102
-				$filename = null;
103
-			}
104
-		}
105
-		return [$uid, $filename];
106
-	}
107
-
108
-	/**
109
-	 * get original location of files for user
110
-	 *
111
-	 * @param string $user
112
-	 * @return array (filename => array (timestamp => original location))
113
-	 */
114
-	public static function getLocations($user) {
115
-		$query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`'
116
-			. ' FROM `*PREFIX*files_trash` WHERE `user`=?');
117
-		$result = $query->execute(array($user));
118
-		$array = array();
119
-		while ($row = $result->fetchRow()) {
120
-			if (isset($array[$row['id']])) {
121
-				$array[$row['id']][$row['timestamp']] = $row['location'];
122
-			} else {
123
-				$array[$row['id']] = array($row['timestamp'] => $row['location']);
124
-			}
125
-		}
126
-		return $array;
127
-	}
128
-
129
-	/**
130
-	 * get original location of file
131
-	 *
132
-	 * @param string $user
133
-	 * @param string $filename
134
-	 * @param string $timestamp
135
-	 * @return string original location
136
-	 */
137
-	public static function getLocation($user, $filename, $timestamp) {
138
-		$query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`'
139
-			. ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
140
-		$result = $query->execute(array($user, $filename, $timestamp))->fetchAll();
141
-		if (isset($result[0]['location'])) {
142
-			return $result[0]['location'];
143
-		} else {
144
-			return false;
145
-		}
146
-	}
147
-
148
-	private static function setUpTrash($user) {
149
-		$view = new View('/' . $user);
150
-		if (!$view->is_dir('files_trashbin')) {
151
-			$view->mkdir('files_trashbin');
152
-		}
153
-		if (!$view->is_dir('files_trashbin/files')) {
154
-			$view->mkdir('files_trashbin/files');
155
-		}
156
-		if (!$view->is_dir('files_trashbin/versions')) {
157
-			$view->mkdir('files_trashbin/versions');
158
-		}
159
-		if (!$view->is_dir('files_trashbin/keys')) {
160
-			$view->mkdir('files_trashbin/keys');
161
-		}
162
-	}
163
-
164
-
165
-	/**
166
-	 * copy file to owners trash
167
-	 *
168
-	 * @param string $sourcePath
169
-	 * @param string $owner
170
-	 * @param string $targetPath
171
-	 * @param $user
172
-	 * @param integer $timestamp
173
-	 */
174
-	private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
175
-		self::setUpTrash($owner);
176
-
177
-		$targetFilename = basename($targetPath);
178
-		$targetLocation = dirname($targetPath);
179
-
180
-		$sourceFilename = basename($sourcePath);
181
-
182
-		$view = new View('/');
183
-
184
-		$target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
185
-		$source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
186
-		self::copy_recursive($source, $target, $view);
187
-
188
-
189
-		if ($view->file_exists($target)) {
190
-			$query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
191
-			$result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user));
192
-			if (!$result) {
193
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR);
194
-			}
195
-		}
196
-	}
197
-
198
-
199
-	/**
200
-	 * move file to the trash bin
201
-	 *
202
-	 * @param string $file_path path to the deleted file/directory relative to the files root directory
203
-	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
204
-	 *
205
-	 * @return bool
206
-	 */
207
-	public static function move2trash($file_path, $ownerOnly = false) {
208
-		// get the user for which the filesystem is setup
209
-		$root = Filesystem::getRoot();
210
-		list(, $user) = explode('/', $root);
211
-		list($owner, $ownerPath) = self::getUidAndFilename($file_path);
212
-
213
-		// if no owner found (ex: ext storage + share link), will use the current user's trashbin then
214
-		if (is_null($owner)) {
215
-			$owner = $user;
216
-			$ownerPath = $file_path;
217
-		}
218
-
219
-		$ownerView = new View('/' . $owner);
220
-		// file has been deleted in between
221
-		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
222
-			return true;
223
-		}
224
-
225
-		self::setUpTrash($user);
226
-		if ($owner !== $user) {
227
-			// also setup for owner
228
-			self::setUpTrash($owner);
229
-		}
230
-
231
-		$path_parts = pathinfo($ownerPath);
232
-
233
-		$filename = $path_parts['basename'];
234
-		$location = $path_parts['dirname'];
235
-		$timestamp = time();
236
-
237
-		// disable proxy to prevent recursive calls
238
-		$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
239
-
240
-		/** @var \OC\Files\Storage\Storage $trashStorage */
241
-		list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath);
242
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
243
-		list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath);
244
-		try {
245
-			$moveSuccessful = true;
246
-			if ($trashStorage->file_exists($trashInternalPath)) {
247
-				$trashStorage->unlink($trashInternalPath);
248
-			}
249
-			$trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
250
-		} catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
251
-			$moveSuccessful = false;
252
-			if ($trashStorage->file_exists($trashInternalPath)) {
253
-				$trashStorage->unlink($trashInternalPath);
254
-			}
255
-			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
256
-		}
257
-
258
-		if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
259
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
260
-				$sourceStorage->rmdir($sourceInternalPath);
261
-			} else {
262
-				$sourceStorage->unlink($sourceInternalPath);
263
-			}
264
-			return false;
265
-		}
266
-
267
-		$trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
268
-
269
-		if ($moveSuccessful) {
270
-			$query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
271
-			$result = $query->execute(array($filename, $timestamp, $location, $owner));
272
-			if (!$result) {
273
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
274
-			}
275
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path),
276
-				'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)));
277
-
278
-			self::retainVersions($filename, $owner, $ownerPath, $timestamp);
279
-
280
-			// if owner !== user we need to also add a copy to the users trash
281
-			if ($user !== $owner && $ownerOnly === false) {
282
-				self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
283
-			}
284
-		}
285
-
286
-		self::scheduleExpire($user);
287
-
288
-		// if owner !== user we also need to update the owners trash size
289
-		if ($owner !== $user) {
290
-			self::scheduleExpire($owner);
291
-		}
292
-
293
-		return $moveSuccessful;
294
-	}
295
-
296
-	/**
297
-	 * Move file versions to trash so that they can be restored later
298
-	 *
299
-	 * @param string $filename of deleted file
300
-	 * @param string $owner owner user id
301
-	 * @param string $ownerPath path relative to the owner's home storage
302
-	 * @param integer $timestamp when the file was deleted
303
-	 */
304
-	private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
305
-		if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) {
306
-
307
-			$user = User::getUser();
308
-			$rootView = new View('/');
309
-
310
-			if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
311
-				if ($owner !== $user) {
312
-					self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
313
-				}
314
-				self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
315
-			} else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
316
-
317
-				foreach ($versions as $v) {
318
-					if ($owner !== $user) {
319
-						self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
320
-					}
321
-					self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
322
-				}
323
-			}
324
-		}
325
-	}
326
-
327
-	/**
328
-	 * Move a file or folder on storage level
329
-	 *
330
-	 * @param View $view
331
-	 * @param string $source
332
-	 * @param string $target
333
-	 * @return bool
334
-	 */
335
-	private static function move(View $view, $source, $target) {
336
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
337
-		list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
338
-		/** @var \OC\Files\Storage\Storage $targetStorage */
339
-		list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
340
-		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
341
-
342
-		$result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
343
-		if ($result) {
344
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
345
-		}
346
-		return $result;
347
-	}
348
-
349
-	/**
350
-	 * Copy a file or folder on storage level
351
-	 *
352
-	 * @param View $view
353
-	 * @param string $source
354
-	 * @param string $target
355
-	 * @return bool
356
-	 */
357
-	private static function copy(View $view, $source, $target) {
358
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
359
-		list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
360
-		/** @var \OC\Files\Storage\Storage $targetStorage */
361
-		list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
362
-		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
363
-
364
-		$result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
365
-		if ($result) {
366
-			$targetStorage->getUpdater()->update($targetInternalPath);
367
-		}
368
-		return $result;
369
-	}
370
-
371
-	/**
372
-	 * Restore a file or folder from trash bin
373
-	 *
374
-	 * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
375
-	 * including the timestamp suffix ".d12345678"
376
-	 * @param string $filename name of the file/folder
377
-	 * @param int $timestamp time when the file/folder was deleted
378
-	 *
379
-	 * @return bool true on success, false otherwise
380
-	 */
381
-	public static function restore($file, $filename, $timestamp) {
382
-		$user = User::getUser();
383
-		$view = new View('/' . $user);
384
-
385
-		$location = '';
386
-		if ($timestamp) {
387
-			$location = self::getLocation($user, $filename, $timestamp);
388
-			if ($location === false) {
389
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent!', \OCP\Util::ERROR);
390
-			} else {
391
-				// if location no longer exists, restore file in the root directory
392
-				if ($location !== '/' &&
393
-					(!$view->is_dir('files/' . $location) ||
394
-						!$view->isCreatable('files/' . $location))
395
-				) {
396
-					$location = '';
397
-				}
398
-			}
399
-		}
400
-
401
-		// we need a  extension in case a file/dir with the same name already exists
402
-		$uniqueFilename = self::getUniqueFilename($location, $filename, $view);
403
-
404
-		$source = Filesystem::normalizePath('files_trashbin/files/' . $file);
405
-		$target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
406
-		if (!$view->file_exists($source)) {
407
-			return false;
408
-		}
409
-		$mtime = $view->filemtime($source);
410
-
411
-		// restore file
412
-		$restoreResult = $view->rename($source, $target);
413
-
414
-		// handle the restore result
415
-		if ($restoreResult) {
416
-			$fakeRoot = $view->getRoot();
417
-			$view->chroot('/' . $user . '/files');
418
-			$view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
419
-			$view->chroot($fakeRoot);
420
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
421
-				'trashPath' => Filesystem::normalizePath($file)));
422
-
423
-			self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
424
-
425
-			if ($timestamp) {
426
-				$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
427
-				$query->execute(array($user, $filename, $timestamp));
428
-			}
429
-
430
-			return true;
431
-		}
432
-
433
-		return false;
434
-	}
435
-
436
-	/**
437
-	 * restore versions from trash bin
438
-	 *
439
-	 * @param View $view file view
440
-	 * @param string $file complete path to file
441
-	 * @param string $filename name of file once it was deleted
442
-	 * @param string $uniqueFilename new file name to restore the file without overwriting existing files
443
-	 * @param string $location location if file
444
-	 * @param int $timestamp deletion time
445
-	 * @return false|null
446
-	 */
447
-	private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
448
-
449
-		if (\OCP\App::isEnabled('files_versions')) {
450
-
451
-			$user = User::getUser();
452
-			$rootView = new View('/');
453
-
454
-			$target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
455
-
456
-			list($owner, $ownerPath) = self::getUidAndFilename($target);
457
-
458
-			// file has been deleted in between
459
-			if (empty($ownerPath)) {
460
-				return false;
461
-			}
462
-
463
-			if ($timestamp) {
464
-				$versionedFile = $filename;
465
-			} else {
466
-				$versionedFile = $file;
467
-			}
468
-
469
-			if ($view->is_dir('/files_trashbin/versions/' . $file)) {
470
-				$rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
471
-			} else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
472
-				foreach ($versions as $v) {
473
-					if ($timestamp) {
474
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
475
-					} else {
476
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
477
-					}
478
-				}
479
-			}
480
-		}
481
-	}
482
-
483
-	/**
484
-	 * delete all files from the trash
485
-	 */
486
-	public static function deleteAll() {
487
-		$user = User::getUser();
488
-		$view = new View('/' . $user);
489
-		$fileInfos = $view->getDirectoryContent('files_trashbin/files');
490
-
491
-		// Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
492
-		$filePaths = array();
493
-		foreach($fileInfos as $fileInfo){
494
-			$filePaths[] = $view->getRelativePath($fileInfo->getPath());
495
-		}
496
-		unset($fileInfos); // save memory
497
-
498
-		// Bulk PreDelete-Hook
499
-		\OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths));
500
-
501
-		// Single-File Hooks
502
-		foreach($filePaths as $path){
503
-			self::emitTrashbinPreDelete($path);
504
-		}
505
-
506
-		// actual file deletion
507
-		$view->deleteAll('files_trashbin');
508
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
509
-		$query->execute(array($user));
510
-
511
-		// Bulk PostDelete-Hook
512
-		\OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths));
513
-
514
-		// Single-File Hooks
515
-		foreach($filePaths as $path){
516
-			self::emitTrashbinPostDelete($path);
517
-		}
518
-
519
-		$view->mkdir('files_trashbin');
520
-		$view->mkdir('files_trashbin/files');
521
-
522
-		return true;
523
-	}
524
-
525
-	/**
526
-	 * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
527
-	 * @param string $path
528
-	 */
529
-	protected static function emitTrashbinPreDelete($path){
530
-		\OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path));
531
-	}
532
-
533
-	/**
534
-	 * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
535
-	 * @param string $path
536
-	 */
537
-	protected static function emitTrashbinPostDelete($path){
538
-		\OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path));
539
-	}
540
-
541
-	/**
542
-	 * delete file from trash bin permanently
543
-	 *
544
-	 * @param string $filename path to the file
545
-	 * @param string $user
546
-	 * @param int $timestamp of deletion time
547
-	 *
548
-	 * @return int size of deleted files
549
-	 */
550
-	public static function delete($filename, $user, $timestamp = null) {
551
-		$view = new View('/' . $user);
552
-		$size = 0;
553
-
554
-		if ($timestamp) {
555
-			$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
556
-			$query->execute(array($user, $filename, $timestamp));
557
-			$file = $filename . '.d' . $timestamp;
558
-		} else {
559
-			$file = $filename;
560
-		}
561
-
562
-		$size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
563
-
564
-		if ($view->is_dir('/files_trashbin/files/' . $file)) {
565
-			$size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
566
-		} else {
567
-			$size += $view->filesize('/files_trashbin/files/' . $file);
568
-		}
569
-		self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
570
-		$view->unlink('/files_trashbin/files/' . $file);
571
-		self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
572
-
573
-		return $size;
574
-	}
575
-
576
-	/**
577
-	 * @param View $view
578
-	 * @param string $file
579
-	 * @param string $filename
580
-	 * @param integer|null $timestamp
581
-	 * @param string $user
582
-	 * @return int
583
-	 */
584
-	private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
585
-		$size = 0;
586
-		if (\OCP\App::isEnabled('files_versions')) {
587
-			if ($view->is_dir('files_trashbin/versions/' . $file)) {
588
-				$size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
589
-				$view->unlink('files_trashbin/versions/' . $file);
590
-			} else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
591
-				foreach ($versions as $v) {
592
-					if ($timestamp) {
593
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
594
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
595
-					} else {
596
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
597
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
598
-					}
599
-				}
600
-			}
601
-		}
602
-		return $size;
603
-	}
604
-
605
-	/**
606
-	 * check to see whether a file exists in trashbin
607
-	 *
608
-	 * @param string $filename path to the file
609
-	 * @param int $timestamp of deletion time
610
-	 * @return bool true if file exists, otherwise false
611
-	 */
612
-	public static function file_exists($filename, $timestamp = null) {
613
-		$user = User::getUser();
614
-		$view = new View('/' . $user);
615
-
616
-		if ($timestamp) {
617
-			$filename = $filename . '.d' . $timestamp;
618
-		} else {
619
-			$filename = $filename;
620
-		}
621
-
622
-		$target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
623
-		return $view->file_exists($target);
624
-	}
625
-
626
-	/**
627
-	 * deletes used space for trash bin in db if user was deleted
628
-	 *
629
-	 * @param string $uid id of deleted user
630
-	 * @return bool result of db delete operation
631
-	 */
632
-	public static function deleteUser($uid) {
633
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
634
-		return $query->execute(array($uid));
635
-	}
636
-
637
-	/**
638
-	 * calculate remaining free space for trash bin
639
-	 *
640
-	 * @param integer $trashbinSize current size of the trash bin
641
-	 * @param string $user
642
-	 * @return int available free space for trash bin
643
-	 */
644
-	private static function calculateFreeSpace($trashbinSize, $user) {
645
-		$softQuota = true;
646
-		$userObject = \OC::$server->getUserManager()->get($user);
647
-		if(is_null($userObject)) {
648
-			return 0;
649
-		}
650
-		$quota = $userObject->getQuota();
651
-		if ($quota === null || $quota === 'none') {
652
-			$quota = Filesystem::free_space('/');
653
-			$softQuota = false;
654
-			// inf or unknown free space
655
-			if ($quota < 0) {
656
-				$quota = PHP_INT_MAX;
657
-			}
658
-		} else {
659
-			$quota = \OCP\Util::computerFileSize($quota);
660
-		}
661
-
662
-		// calculate available space for trash bin
663
-		// subtract size of files and current trash bin size from quota
664
-		if ($softQuota) {
665
-			$userFolder = \OC::$server->getUserFolder($user);
666
-			if(is_null($userFolder)) {
667
-				return 0;
668
-			}
669
-			$free = $quota - $userFolder->getSize(); // remaining free space for user
670
-			if ($free > 0) {
671
-				$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
672
-			} else {
673
-				$availableSpace = $free - $trashbinSize;
674
-			}
675
-		} else {
676
-			$availableSpace = $quota;
677
-		}
678
-
679
-		return $availableSpace;
680
-	}
681
-
682
-	/**
683
-	 * resize trash bin if necessary after a new file was added to ownCloud
684
-	 *
685
-	 * @param string $user user id
686
-	 */
687
-	public static function resizeTrash($user) {
688
-
689
-		$size = self::getTrashbinSize($user);
690
-
691
-		$freeSpace = self::calculateFreeSpace($size, $user);
692
-
693
-		if ($freeSpace < 0) {
694
-			self::scheduleExpire($user);
695
-		}
696
-	}
697
-
698
-	/**
699
-	 * clean up the trash bin
700
-	 *
701
-	 * @param string $user
702
-	 */
703
-	public static function expire($user) {
704
-		$trashBinSize = self::getTrashbinSize($user);
705
-		$availableSpace = self::calculateFreeSpace($trashBinSize, $user);
706
-
707
-		$dirContent = Helper::getTrashFiles('/', $user, 'mtime');
708
-
709
-		// delete all files older then $retention_obligation
710
-		list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user);
711
-
712
-		$availableSpace += $delSize;
713
-
714
-		// delete files from trash until we meet the trash bin size limit again
715
-		self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
716
-	}
717
-
718
-	/**
719
-	 * @param string $user
720
-	 */
721
-	private static function scheduleExpire($user) {
722
-		// let the admin disable auto expire
723
-		$application = new Application();
724
-		$expiration = $application->getContainer()->query('Expiration');
725
-		if ($expiration->isEnabled()) {
726
-			\OC::$server->getCommandBus()->push(new Expire($user));
727
-		}
728
-	}
729
-
730
-	/**
731
-	 * if the size limit for the trash bin is reached, we delete the oldest
732
-	 * files in the trash bin until we meet the limit again
733
-	 *
734
-	 * @param array $files
735
-	 * @param string $user
736
-	 * @param int $availableSpace available disc space
737
-	 * @return int size of deleted files
738
-	 */
739
-	protected static function deleteFiles($files, $user, $availableSpace) {
740
-		$application = new Application();
741
-		$expiration = $application->getContainer()->query('Expiration');
742
-		$size = 0;
743
-
744
-		if ($availableSpace < 0) {
745
-			foreach ($files as $file) {
746
-				if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
747
-					$tmp = self::delete($file['name'], $user, $file['mtime']);
748
-					\OCP\Util::writeLog('files_trashbin', 'remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO);
749
-					$availableSpace += $tmp;
750
-					$size += $tmp;
751
-				} else {
752
-					break;
753
-				}
754
-			}
755
-		}
756
-		return $size;
757
-	}
758
-
759
-	/**
760
-	 * delete files older then max storage time
761
-	 *
762
-	 * @param array $files list of files sorted by mtime
763
-	 * @param string $user
764
-	 * @return integer[] size of deleted files and number of deleted files
765
-	 */
766
-	public static function deleteExpiredFiles($files, $user) {
767
-		$application = new Application();
768
-		$expiration = $application->getContainer()->query('Expiration');
769
-		$size = 0;
770
-		$count = 0;
771
-		foreach ($files as $file) {
772
-			$timestamp = $file['mtime'];
773
-			$filename = $file['name'];
774
-			if ($expiration->isExpired($timestamp)) {
775
-				$count++;
776
-				$size += self::delete($filename, $user, $timestamp);
777
-				\OC::$server->getLogger()->info(
778
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
779
-					['app' => 'files_trashbin']
780
-				);
781
-			} else {
782
-				break;
783
-			}
784
-		}
785
-
786
-		return array($size, $count);
787
-	}
788
-
789
-	/**
790
-	 * recursive copy to copy a whole directory
791
-	 *
792
-	 * @param string $source source path, relative to the users files directory
793
-	 * @param string $destination destination path relative to the users root directoy
794
-	 * @param View $view file view for the users root directory
795
-	 * @return int
796
-	 * @throws Exceptions\CopyRecursiveException
797
-	 */
798
-	private static function copy_recursive($source, $destination, View $view) {
799
-		$size = 0;
800
-		if ($view->is_dir($source)) {
801
-			$view->mkdir($destination);
802
-			$view->touch($destination, $view->filemtime($source));
803
-			foreach ($view->getDirectoryContent($source) as $i) {
804
-				$pathDir = $source . '/' . $i['name'];
805
-				if ($view->is_dir($pathDir)) {
806
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
807
-				} else {
808
-					$size += $view->filesize($pathDir);
809
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
810
-					if (!$result) {
811
-						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
812
-					}
813
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
814
-				}
815
-			}
816
-		} else {
817
-			$size += $view->filesize($source);
818
-			$result = $view->copy($source, $destination);
819
-			if (!$result) {
820
-				throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
821
-			}
822
-			$view->touch($destination, $view->filemtime($source));
823
-		}
824
-		return $size;
825
-	}
826
-
827
-	/**
828
-	 * find all versions which belong to the file we want to restore
829
-	 *
830
-	 * @param string $filename name of the file which should be restored
831
-	 * @param int $timestamp timestamp when the file was deleted
832
-	 * @return array
833
-	 */
834
-	private static function getVersionsFromTrash($filename, $timestamp, $user) {
835
-		$view = new View('/' . $user . '/files_trashbin/versions');
836
-		$versions = array();
837
-
838
-		//force rescan of versions, local storage may not have updated the cache
839
-		if (!self::$scannedVersions) {
840
-			/** @var \OC\Files\Storage\Storage $storage */
841
-			list($storage,) = $view->resolvePath('/');
842
-			$storage->getScanner()->scan('files_trashbin/versions');
843
-			self::$scannedVersions = true;
844
-		}
845
-
846
-		if ($timestamp) {
847
-			// fetch for old versions
848
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
849
-			$offset = -strlen($timestamp) - 2;
850
-		} else {
851
-			$matches = $view->searchRaw($filename . '.v%');
852
-		}
853
-
854
-		if (is_array($matches)) {
855
-			foreach ($matches as $ma) {
856
-				if ($timestamp) {
857
-					$parts = explode('.v', substr($ma['path'], 0, $offset));
858
-					$versions[] = (end($parts));
859
-				} else {
860
-					$parts = explode('.v', $ma);
861
-					$versions[] = (end($parts));
862
-				}
863
-			}
864
-		}
865
-		return $versions;
866
-	}
867
-
868
-	/**
869
-	 * find unique extension for restored file if a file with the same name already exists
870
-	 *
871
-	 * @param string $location where the file should be restored
872
-	 * @param string $filename name of the file
873
-	 * @param View $view filesystem view relative to users root directory
874
-	 * @return string with unique extension
875
-	 */
876
-	private static function getUniqueFilename($location, $filename, View $view) {
877
-		$ext = pathinfo($filename, PATHINFO_EXTENSION);
878
-		$name = pathinfo($filename, PATHINFO_FILENAME);
879
-		$l = \OC::$server->getL10N('files_trashbin');
880
-
881
-		$location = '/' . trim($location, '/');
882
-
883
-		// if extension is not empty we set a dot in front of it
884
-		if ($ext !== '') {
885
-			$ext = '.' . $ext;
886
-		}
887
-
888
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
889
-			$i = 2;
890
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
891
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
892
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
893
-				$i++;
894
-			}
895
-
896
-			return $uniqueName;
897
-		}
898
-
899
-		return $filename;
900
-	}
901
-
902
-	/**
903
-	 * get the size from a given root folder
904
-	 *
905
-	 * @param View $view file view on the root folder
906
-	 * @return integer size of the folder
907
-	 */
908
-	private static function calculateSize($view) {
909
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
910
-		if (!file_exists($root)) {
911
-			return 0;
912
-		}
913
-		$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
914
-		$size = 0;
915
-
916
-		/**
917
-		 * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
918
-		 * This bug is fixed in PHP 5.5.9 or before
919
-		 * See #8376
920
-		 */
921
-		$iterator->rewind();
922
-		while ($iterator->valid()) {
923
-			$path = $iterator->current();
924
-			$relpath = substr($path, strlen($root) - 1);
925
-			if (!$view->is_dir($relpath)) {
926
-				$size += $view->filesize($relpath);
927
-			}
928
-			$iterator->next();
929
-		}
930
-		return $size;
931
-	}
932
-
933
-	/**
934
-	 * get current size of trash bin from a given user
935
-	 *
936
-	 * @param string $user user who owns the trash bin
937
-	 * @return integer trash bin size
938
-	 */
939
-	private static function getTrashbinSize($user) {
940
-		$view = new View('/' . $user);
941
-		$fileInfo = $view->getFileInfo('/files_trashbin');
942
-		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
943
-	}
944
-
945
-	/**
946
-	 * register hooks
947
-	 */
948
-	public static function registerHooks() {
949
-		// create storage wrapper on setup
950
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
951
-		//Listen to delete user signal
952
-		\OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
953
-		//Listen to post write hook
954
-		\OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
955
-		// pre and post-rename, disable trash logic for the copy+unlink case
956
-		\OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
957
-		\OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook');
958
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook');
959
-	}
960
-
961
-	/**
962
-	 * check if trash bin is empty for a given user
963
-	 *
964
-	 * @param string $user
965
-	 * @return bool
966
-	 */
967
-	public static function isEmpty($user) {
968
-
969
-		$view = new View('/' . $user . '/files_trashbin');
970
-		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
971
-			while ($file = readdir($dh)) {
972
-				if (!Filesystem::isIgnoredDir($file)) {
973
-					return false;
974
-				}
975
-			}
976
-		}
977
-		return true;
978
-	}
979
-
980
-	/**
981
-	 * @param $path
982
-	 * @return string
983
-	 */
984
-	public static function preview_icon($path) {
985
-		return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path));
986
-	}
50
+    // unit: percentage; 50% of available disk space/quota
51
+    const DEFAULTMAXSIZE = 50;
52
+
53
+    /**
54
+     * Whether versions have already be rescanned during this PHP request
55
+     *
56
+     * @var bool
57
+     */
58
+    private static $scannedVersions = false;
59
+
60
+    /**
61
+     * Ensure we don't need to scan the file during the move to trash
62
+     * by triggering the scan in the pre-hook
63
+     *
64
+     * @param array $params
65
+     */
66
+    public static function ensureFileScannedHook($params) {
67
+        try {
68
+            self::getUidAndFilename($params['path']);
69
+        } catch (NotFoundException $e) {
70
+            // nothing to scan for non existing files
71
+        }
72
+    }
73
+
74
+    /**
75
+     * get the UID of the owner of the file and the path to the file relative to
76
+     * owners files folder
77
+     *
78
+     * @param string $filename
79
+     * @return array
80
+     * @throws \OC\User\NoUserException
81
+     */
82
+    public static function getUidAndFilename($filename) {
83
+        $uid = Filesystem::getOwner($filename);
84
+        $userManager = \OC::$server->getUserManager();
85
+        // if the user with the UID doesn't exists, e.g. because the UID points
86
+        // to a remote user with a federated cloud ID we use the current logged-in
87
+        // user. We need a valid local user to move the file to the right trash bin
88
+        if (!$userManager->userExists($uid)) {
89
+            $uid = User::getUser();
90
+        }
91
+        if (!$uid) {
92
+            // no owner, usually because of share link from ext storage
93
+            return [null, null];
94
+        }
95
+        Filesystem::initMountPoints($uid);
96
+        if ($uid != User::getUser()) {
97
+            $info = Filesystem::getFileInfo($filename);
98
+            $ownerView = new View('/' . $uid . '/files');
99
+            try {
100
+                $filename = $ownerView->getPath($info['fileid']);
101
+            } catch (NotFoundException $e) {
102
+                $filename = null;
103
+            }
104
+        }
105
+        return [$uid, $filename];
106
+    }
107
+
108
+    /**
109
+     * get original location of files for user
110
+     *
111
+     * @param string $user
112
+     * @return array (filename => array (timestamp => original location))
113
+     */
114
+    public static function getLocations($user) {
115
+        $query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`'
116
+            . ' FROM `*PREFIX*files_trash` WHERE `user`=?');
117
+        $result = $query->execute(array($user));
118
+        $array = array();
119
+        while ($row = $result->fetchRow()) {
120
+            if (isset($array[$row['id']])) {
121
+                $array[$row['id']][$row['timestamp']] = $row['location'];
122
+            } else {
123
+                $array[$row['id']] = array($row['timestamp'] => $row['location']);
124
+            }
125
+        }
126
+        return $array;
127
+    }
128
+
129
+    /**
130
+     * get original location of file
131
+     *
132
+     * @param string $user
133
+     * @param string $filename
134
+     * @param string $timestamp
135
+     * @return string original location
136
+     */
137
+    public static function getLocation($user, $filename, $timestamp) {
138
+        $query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`'
139
+            . ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
140
+        $result = $query->execute(array($user, $filename, $timestamp))->fetchAll();
141
+        if (isset($result[0]['location'])) {
142
+            return $result[0]['location'];
143
+        } else {
144
+            return false;
145
+        }
146
+    }
147
+
148
+    private static function setUpTrash($user) {
149
+        $view = new View('/' . $user);
150
+        if (!$view->is_dir('files_trashbin')) {
151
+            $view->mkdir('files_trashbin');
152
+        }
153
+        if (!$view->is_dir('files_trashbin/files')) {
154
+            $view->mkdir('files_trashbin/files');
155
+        }
156
+        if (!$view->is_dir('files_trashbin/versions')) {
157
+            $view->mkdir('files_trashbin/versions');
158
+        }
159
+        if (!$view->is_dir('files_trashbin/keys')) {
160
+            $view->mkdir('files_trashbin/keys');
161
+        }
162
+    }
163
+
164
+
165
+    /**
166
+     * copy file to owners trash
167
+     *
168
+     * @param string $sourcePath
169
+     * @param string $owner
170
+     * @param string $targetPath
171
+     * @param $user
172
+     * @param integer $timestamp
173
+     */
174
+    private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
175
+        self::setUpTrash($owner);
176
+
177
+        $targetFilename = basename($targetPath);
178
+        $targetLocation = dirname($targetPath);
179
+
180
+        $sourceFilename = basename($sourcePath);
181
+
182
+        $view = new View('/');
183
+
184
+        $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
185
+        $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
186
+        self::copy_recursive($source, $target, $view);
187
+
188
+
189
+        if ($view->file_exists($target)) {
190
+            $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
191
+            $result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user));
192
+            if (!$result) {
193
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR);
194
+            }
195
+        }
196
+    }
197
+
198
+
199
+    /**
200
+     * move file to the trash bin
201
+     *
202
+     * @param string $file_path path to the deleted file/directory relative to the files root directory
203
+     * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
204
+     *
205
+     * @return bool
206
+     */
207
+    public static function move2trash($file_path, $ownerOnly = false) {
208
+        // get the user for which the filesystem is setup
209
+        $root = Filesystem::getRoot();
210
+        list(, $user) = explode('/', $root);
211
+        list($owner, $ownerPath) = self::getUidAndFilename($file_path);
212
+
213
+        // if no owner found (ex: ext storage + share link), will use the current user's trashbin then
214
+        if (is_null($owner)) {
215
+            $owner = $user;
216
+            $ownerPath = $file_path;
217
+        }
218
+
219
+        $ownerView = new View('/' . $owner);
220
+        // file has been deleted in between
221
+        if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
222
+            return true;
223
+        }
224
+
225
+        self::setUpTrash($user);
226
+        if ($owner !== $user) {
227
+            // also setup for owner
228
+            self::setUpTrash($owner);
229
+        }
230
+
231
+        $path_parts = pathinfo($ownerPath);
232
+
233
+        $filename = $path_parts['basename'];
234
+        $location = $path_parts['dirname'];
235
+        $timestamp = time();
236
+
237
+        // disable proxy to prevent recursive calls
238
+        $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
239
+
240
+        /** @var \OC\Files\Storage\Storage $trashStorage */
241
+        list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath);
242
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
243
+        list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath);
244
+        try {
245
+            $moveSuccessful = true;
246
+            if ($trashStorage->file_exists($trashInternalPath)) {
247
+                $trashStorage->unlink($trashInternalPath);
248
+            }
249
+            $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
250
+        } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
251
+            $moveSuccessful = false;
252
+            if ($trashStorage->file_exists($trashInternalPath)) {
253
+                $trashStorage->unlink($trashInternalPath);
254
+            }
255
+            \OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
256
+        }
257
+
258
+        if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
259
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
260
+                $sourceStorage->rmdir($sourceInternalPath);
261
+            } else {
262
+                $sourceStorage->unlink($sourceInternalPath);
263
+            }
264
+            return false;
265
+        }
266
+
267
+        $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
268
+
269
+        if ($moveSuccessful) {
270
+            $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
271
+            $result = $query->execute(array($filename, $timestamp, $location, $owner));
272
+            if (!$result) {
273
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
274
+            }
275
+            \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path),
276
+                'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)));
277
+
278
+            self::retainVersions($filename, $owner, $ownerPath, $timestamp);
279
+
280
+            // if owner !== user we need to also add a copy to the users trash
281
+            if ($user !== $owner && $ownerOnly === false) {
282
+                self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
283
+            }
284
+        }
285
+
286
+        self::scheduleExpire($user);
287
+
288
+        // if owner !== user we also need to update the owners trash size
289
+        if ($owner !== $user) {
290
+            self::scheduleExpire($owner);
291
+        }
292
+
293
+        return $moveSuccessful;
294
+    }
295
+
296
+    /**
297
+     * Move file versions to trash so that they can be restored later
298
+     *
299
+     * @param string $filename of deleted file
300
+     * @param string $owner owner user id
301
+     * @param string $ownerPath path relative to the owner's home storage
302
+     * @param integer $timestamp when the file was deleted
303
+     */
304
+    private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
305
+        if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) {
306
+
307
+            $user = User::getUser();
308
+            $rootView = new View('/');
309
+
310
+            if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
311
+                if ($owner !== $user) {
312
+                    self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
313
+                }
314
+                self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
315
+            } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
316
+
317
+                foreach ($versions as $v) {
318
+                    if ($owner !== $user) {
319
+                        self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
320
+                    }
321
+                    self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
322
+                }
323
+            }
324
+        }
325
+    }
326
+
327
+    /**
328
+     * Move a file or folder on storage level
329
+     *
330
+     * @param View $view
331
+     * @param string $source
332
+     * @param string $target
333
+     * @return bool
334
+     */
335
+    private static function move(View $view, $source, $target) {
336
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
337
+        list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
338
+        /** @var \OC\Files\Storage\Storage $targetStorage */
339
+        list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
340
+        /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
341
+
342
+        $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
343
+        if ($result) {
344
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
345
+        }
346
+        return $result;
347
+    }
348
+
349
+    /**
350
+     * Copy a file or folder on storage level
351
+     *
352
+     * @param View $view
353
+     * @param string $source
354
+     * @param string $target
355
+     * @return bool
356
+     */
357
+    private static function copy(View $view, $source, $target) {
358
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
359
+        list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
360
+        /** @var \OC\Files\Storage\Storage $targetStorage */
361
+        list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
362
+        /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
363
+
364
+        $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
365
+        if ($result) {
366
+            $targetStorage->getUpdater()->update($targetInternalPath);
367
+        }
368
+        return $result;
369
+    }
370
+
371
+    /**
372
+     * Restore a file or folder from trash bin
373
+     *
374
+     * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
375
+     * including the timestamp suffix ".d12345678"
376
+     * @param string $filename name of the file/folder
377
+     * @param int $timestamp time when the file/folder was deleted
378
+     *
379
+     * @return bool true on success, false otherwise
380
+     */
381
+    public static function restore($file, $filename, $timestamp) {
382
+        $user = User::getUser();
383
+        $view = new View('/' . $user);
384
+
385
+        $location = '';
386
+        if ($timestamp) {
387
+            $location = self::getLocation($user, $filename, $timestamp);
388
+            if ($location === false) {
389
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent!', \OCP\Util::ERROR);
390
+            } else {
391
+                // if location no longer exists, restore file in the root directory
392
+                if ($location !== '/' &&
393
+                    (!$view->is_dir('files/' . $location) ||
394
+                        !$view->isCreatable('files/' . $location))
395
+                ) {
396
+                    $location = '';
397
+                }
398
+            }
399
+        }
400
+
401
+        // we need a  extension in case a file/dir with the same name already exists
402
+        $uniqueFilename = self::getUniqueFilename($location, $filename, $view);
403
+
404
+        $source = Filesystem::normalizePath('files_trashbin/files/' . $file);
405
+        $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
406
+        if (!$view->file_exists($source)) {
407
+            return false;
408
+        }
409
+        $mtime = $view->filemtime($source);
410
+
411
+        // restore file
412
+        $restoreResult = $view->rename($source, $target);
413
+
414
+        // handle the restore result
415
+        if ($restoreResult) {
416
+            $fakeRoot = $view->getRoot();
417
+            $view->chroot('/' . $user . '/files');
418
+            $view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
419
+            $view->chroot($fakeRoot);
420
+            \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
421
+                'trashPath' => Filesystem::normalizePath($file)));
422
+
423
+            self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
424
+
425
+            if ($timestamp) {
426
+                $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
427
+                $query->execute(array($user, $filename, $timestamp));
428
+            }
429
+
430
+            return true;
431
+        }
432
+
433
+        return false;
434
+    }
435
+
436
+    /**
437
+     * restore versions from trash bin
438
+     *
439
+     * @param View $view file view
440
+     * @param string $file complete path to file
441
+     * @param string $filename name of file once it was deleted
442
+     * @param string $uniqueFilename new file name to restore the file without overwriting existing files
443
+     * @param string $location location if file
444
+     * @param int $timestamp deletion time
445
+     * @return false|null
446
+     */
447
+    private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
448
+
449
+        if (\OCP\App::isEnabled('files_versions')) {
450
+
451
+            $user = User::getUser();
452
+            $rootView = new View('/');
453
+
454
+            $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
455
+
456
+            list($owner, $ownerPath) = self::getUidAndFilename($target);
457
+
458
+            // file has been deleted in between
459
+            if (empty($ownerPath)) {
460
+                return false;
461
+            }
462
+
463
+            if ($timestamp) {
464
+                $versionedFile = $filename;
465
+            } else {
466
+                $versionedFile = $file;
467
+            }
468
+
469
+            if ($view->is_dir('/files_trashbin/versions/' . $file)) {
470
+                $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
471
+            } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
472
+                foreach ($versions as $v) {
473
+                    if ($timestamp) {
474
+                        $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
475
+                    } else {
476
+                        $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
477
+                    }
478
+                }
479
+            }
480
+        }
481
+    }
482
+
483
+    /**
484
+     * delete all files from the trash
485
+     */
486
+    public static function deleteAll() {
487
+        $user = User::getUser();
488
+        $view = new View('/' . $user);
489
+        $fileInfos = $view->getDirectoryContent('files_trashbin/files');
490
+
491
+        // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
492
+        $filePaths = array();
493
+        foreach($fileInfos as $fileInfo){
494
+            $filePaths[] = $view->getRelativePath($fileInfo->getPath());
495
+        }
496
+        unset($fileInfos); // save memory
497
+
498
+        // Bulk PreDelete-Hook
499
+        \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths));
500
+
501
+        // Single-File Hooks
502
+        foreach($filePaths as $path){
503
+            self::emitTrashbinPreDelete($path);
504
+        }
505
+
506
+        // actual file deletion
507
+        $view->deleteAll('files_trashbin');
508
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
509
+        $query->execute(array($user));
510
+
511
+        // Bulk PostDelete-Hook
512
+        \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths));
513
+
514
+        // Single-File Hooks
515
+        foreach($filePaths as $path){
516
+            self::emitTrashbinPostDelete($path);
517
+        }
518
+
519
+        $view->mkdir('files_trashbin');
520
+        $view->mkdir('files_trashbin/files');
521
+
522
+        return true;
523
+    }
524
+
525
+    /**
526
+     * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
527
+     * @param string $path
528
+     */
529
+    protected static function emitTrashbinPreDelete($path){
530
+        \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path));
531
+    }
532
+
533
+    /**
534
+     * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
535
+     * @param string $path
536
+     */
537
+    protected static function emitTrashbinPostDelete($path){
538
+        \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path));
539
+    }
540
+
541
+    /**
542
+     * delete file from trash bin permanently
543
+     *
544
+     * @param string $filename path to the file
545
+     * @param string $user
546
+     * @param int $timestamp of deletion time
547
+     *
548
+     * @return int size of deleted files
549
+     */
550
+    public static function delete($filename, $user, $timestamp = null) {
551
+        $view = new View('/' . $user);
552
+        $size = 0;
553
+
554
+        if ($timestamp) {
555
+            $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
556
+            $query->execute(array($user, $filename, $timestamp));
557
+            $file = $filename . '.d' . $timestamp;
558
+        } else {
559
+            $file = $filename;
560
+        }
561
+
562
+        $size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
563
+
564
+        if ($view->is_dir('/files_trashbin/files/' . $file)) {
565
+            $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
566
+        } else {
567
+            $size += $view->filesize('/files_trashbin/files/' . $file);
568
+        }
569
+        self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
570
+        $view->unlink('/files_trashbin/files/' . $file);
571
+        self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
572
+
573
+        return $size;
574
+    }
575
+
576
+    /**
577
+     * @param View $view
578
+     * @param string $file
579
+     * @param string $filename
580
+     * @param integer|null $timestamp
581
+     * @param string $user
582
+     * @return int
583
+     */
584
+    private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
585
+        $size = 0;
586
+        if (\OCP\App::isEnabled('files_versions')) {
587
+            if ($view->is_dir('files_trashbin/versions/' . $file)) {
588
+                $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
589
+                $view->unlink('files_trashbin/versions/' . $file);
590
+            } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
591
+                foreach ($versions as $v) {
592
+                    if ($timestamp) {
593
+                        $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
594
+                        $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
595
+                    } else {
596
+                        $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
597
+                        $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
598
+                    }
599
+                }
600
+            }
601
+        }
602
+        return $size;
603
+    }
604
+
605
+    /**
606
+     * check to see whether a file exists in trashbin
607
+     *
608
+     * @param string $filename path to the file
609
+     * @param int $timestamp of deletion time
610
+     * @return bool true if file exists, otherwise false
611
+     */
612
+    public static function file_exists($filename, $timestamp = null) {
613
+        $user = User::getUser();
614
+        $view = new View('/' . $user);
615
+
616
+        if ($timestamp) {
617
+            $filename = $filename . '.d' . $timestamp;
618
+        } else {
619
+            $filename = $filename;
620
+        }
621
+
622
+        $target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
623
+        return $view->file_exists($target);
624
+    }
625
+
626
+    /**
627
+     * deletes used space for trash bin in db if user was deleted
628
+     *
629
+     * @param string $uid id of deleted user
630
+     * @return bool result of db delete operation
631
+     */
632
+    public static function deleteUser($uid) {
633
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
634
+        return $query->execute(array($uid));
635
+    }
636
+
637
+    /**
638
+     * calculate remaining free space for trash bin
639
+     *
640
+     * @param integer $trashbinSize current size of the trash bin
641
+     * @param string $user
642
+     * @return int available free space for trash bin
643
+     */
644
+    private static function calculateFreeSpace($trashbinSize, $user) {
645
+        $softQuota = true;
646
+        $userObject = \OC::$server->getUserManager()->get($user);
647
+        if(is_null($userObject)) {
648
+            return 0;
649
+        }
650
+        $quota = $userObject->getQuota();
651
+        if ($quota === null || $quota === 'none') {
652
+            $quota = Filesystem::free_space('/');
653
+            $softQuota = false;
654
+            // inf or unknown free space
655
+            if ($quota < 0) {
656
+                $quota = PHP_INT_MAX;
657
+            }
658
+        } else {
659
+            $quota = \OCP\Util::computerFileSize($quota);
660
+        }
661
+
662
+        // calculate available space for trash bin
663
+        // subtract size of files and current trash bin size from quota
664
+        if ($softQuota) {
665
+            $userFolder = \OC::$server->getUserFolder($user);
666
+            if(is_null($userFolder)) {
667
+                return 0;
668
+            }
669
+            $free = $quota - $userFolder->getSize(); // remaining free space for user
670
+            if ($free > 0) {
671
+                $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
672
+            } else {
673
+                $availableSpace = $free - $trashbinSize;
674
+            }
675
+        } else {
676
+            $availableSpace = $quota;
677
+        }
678
+
679
+        return $availableSpace;
680
+    }
681
+
682
+    /**
683
+     * resize trash bin if necessary after a new file was added to ownCloud
684
+     *
685
+     * @param string $user user id
686
+     */
687
+    public static function resizeTrash($user) {
688
+
689
+        $size = self::getTrashbinSize($user);
690
+
691
+        $freeSpace = self::calculateFreeSpace($size, $user);
692
+
693
+        if ($freeSpace < 0) {
694
+            self::scheduleExpire($user);
695
+        }
696
+    }
697
+
698
+    /**
699
+     * clean up the trash bin
700
+     *
701
+     * @param string $user
702
+     */
703
+    public static function expire($user) {
704
+        $trashBinSize = self::getTrashbinSize($user);
705
+        $availableSpace = self::calculateFreeSpace($trashBinSize, $user);
706
+
707
+        $dirContent = Helper::getTrashFiles('/', $user, 'mtime');
708
+
709
+        // delete all files older then $retention_obligation
710
+        list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user);
711
+
712
+        $availableSpace += $delSize;
713
+
714
+        // delete files from trash until we meet the trash bin size limit again
715
+        self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
716
+    }
717
+
718
+    /**
719
+     * @param string $user
720
+     */
721
+    private static function scheduleExpire($user) {
722
+        // let the admin disable auto expire
723
+        $application = new Application();
724
+        $expiration = $application->getContainer()->query('Expiration');
725
+        if ($expiration->isEnabled()) {
726
+            \OC::$server->getCommandBus()->push(new Expire($user));
727
+        }
728
+    }
729
+
730
+    /**
731
+     * if the size limit for the trash bin is reached, we delete the oldest
732
+     * files in the trash bin until we meet the limit again
733
+     *
734
+     * @param array $files
735
+     * @param string $user
736
+     * @param int $availableSpace available disc space
737
+     * @return int size of deleted files
738
+     */
739
+    protected static function deleteFiles($files, $user, $availableSpace) {
740
+        $application = new Application();
741
+        $expiration = $application->getContainer()->query('Expiration');
742
+        $size = 0;
743
+
744
+        if ($availableSpace < 0) {
745
+            foreach ($files as $file) {
746
+                if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
747
+                    $tmp = self::delete($file['name'], $user, $file['mtime']);
748
+                    \OCP\Util::writeLog('files_trashbin', 'remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO);
749
+                    $availableSpace += $tmp;
750
+                    $size += $tmp;
751
+                } else {
752
+                    break;
753
+                }
754
+            }
755
+        }
756
+        return $size;
757
+    }
758
+
759
+    /**
760
+     * delete files older then max storage time
761
+     *
762
+     * @param array $files list of files sorted by mtime
763
+     * @param string $user
764
+     * @return integer[] size of deleted files and number of deleted files
765
+     */
766
+    public static function deleteExpiredFiles($files, $user) {
767
+        $application = new Application();
768
+        $expiration = $application->getContainer()->query('Expiration');
769
+        $size = 0;
770
+        $count = 0;
771
+        foreach ($files as $file) {
772
+            $timestamp = $file['mtime'];
773
+            $filename = $file['name'];
774
+            if ($expiration->isExpired($timestamp)) {
775
+                $count++;
776
+                $size += self::delete($filename, $user, $timestamp);
777
+                \OC::$server->getLogger()->info(
778
+                    'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
779
+                    ['app' => 'files_trashbin']
780
+                );
781
+            } else {
782
+                break;
783
+            }
784
+        }
785
+
786
+        return array($size, $count);
787
+    }
788
+
789
+    /**
790
+     * recursive copy to copy a whole directory
791
+     *
792
+     * @param string $source source path, relative to the users files directory
793
+     * @param string $destination destination path relative to the users root directoy
794
+     * @param View $view file view for the users root directory
795
+     * @return int
796
+     * @throws Exceptions\CopyRecursiveException
797
+     */
798
+    private static function copy_recursive($source, $destination, View $view) {
799
+        $size = 0;
800
+        if ($view->is_dir($source)) {
801
+            $view->mkdir($destination);
802
+            $view->touch($destination, $view->filemtime($source));
803
+            foreach ($view->getDirectoryContent($source) as $i) {
804
+                $pathDir = $source . '/' . $i['name'];
805
+                if ($view->is_dir($pathDir)) {
806
+                    $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
807
+                } else {
808
+                    $size += $view->filesize($pathDir);
809
+                    $result = $view->copy($pathDir, $destination . '/' . $i['name']);
810
+                    if (!$result) {
811
+                        throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
812
+                    }
813
+                    $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
814
+                }
815
+            }
816
+        } else {
817
+            $size += $view->filesize($source);
818
+            $result = $view->copy($source, $destination);
819
+            if (!$result) {
820
+                throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
821
+            }
822
+            $view->touch($destination, $view->filemtime($source));
823
+        }
824
+        return $size;
825
+    }
826
+
827
+    /**
828
+     * find all versions which belong to the file we want to restore
829
+     *
830
+     * @param string $filename name of the file which should be restored
831
+     * @param int $timestamp timestamp when the file was deleted
832
+     * @return array
833
+     */
834
+    private static function getVersionsFromTrash($filename, $timestamp, $user) {
835
+        $view = new View('/' . $user . '/files_trashbin/versions');
836
+        $versions = array();
837
+
838
+        //force rescan of versions, local storage may not have updated the cache
839
+        if (!self::$scannedVersions) {
840
+            /** @var \OC\Files\Storage\Storage $storage */
841
+            list($storage,) = $view->resolvePath('/');
842
+            $storage->getScanner()->scan('files_trashbin/versions');
843
+            self::$scannedVersions = true;
844
+        }
845
+
846
+        if ($timestamp) {
847
+            // fetch for old versions
848
+            $matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
849
+            $offset = -strlen($timestamp) - 2;
850
+        } else {
851
+            $matches = $view->searchRaw($filename . '.v%');
852
+        }
853
+
854
+        if (is_array($matches)) {
855
+            foreach ($matches as $ma) {
856
+                if ($timestamp) {
857
+                    $parts = explode('.v', substr($ma['path'], 0, $offset));
858
+                    $versions[] = (end($parts));
859
+                } else {
860
+                    $parts = explode('.v', $ma);
861
+                    $versions[] = (end($parts));
862
+                }
863
+            }
864
+        }
865
+        return $versions;
866
+    }
867
+
868
+    /**
869
+     * find unique extension for restored file if a file with the same name already exists
870
+     *
871
+     * @param string $location where the file should be restored
872
+     * @param string $filename name of the file
873
+     * @param View $view filesystem view relative to users root directory
874
+     * @return string with unique extension
875
+     */
876
+    private static function getUniqueFilename($location, $filename, View $view) {
877
+        $ext = pathinfo($filename, PATHINFO_EXTENSION);
878
+        $name = pathinfo($filename, PATHINFO_FILENAME);
879
+        $l = \OC::$server->getL10N('files_trashbin');
880
+
881
+        $location = '/' . trim($location, '/');
882
+
883
+        // if extension is not empty we set a dot in front of it
884
+        if ($ext !== '') {
885
+            $ext = '.' . $ext;
886
+        }
887
+
888
+        if ($view->file_exists('files' . $location . '/' . $filename)) {
889
+            $i = 2;
890
+            $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
891
+            while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
892
+                $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
893
+                $i++;
894
+            }
895
+
896
+            return $uniqueName;
897
+        }
898
+
899
+        return $filename;
900
+    }
901
+
902
+    /**
903
+     * get the size from a given root folder
904
+     *
905
+     * @param View $view file view on the root folder
906
+     * @return integer size of the folder
907
+     */
908
+    private static function calculateSize($view) {
909
+        $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
910
+        if (!file_exists($root)) {
911
+            return 0;
912
+        }
913
+        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
914
+        $size = 0;
915
+
916
+        /**
917
+         * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
918
+         * This bug is fixed in PHP 5.5.9 or before
919
+         * See #8376
920
+         */
921
+        $iterator->rewind();
922
+        while ($iterator->valid()) {
923
+            $path = $iterator->current();
924
+            $relpath = substr($path, strlen($root) - 1);
925
+            if (!$view->is_dir($relpath)) {
926
+                $size += $view->filesize($relpath);
927
+            }
928
+            $iterator->next();
929
+        }
930
+        return $size;
931
+    }
932
+
933
+    /**
934
+     * get current size of trash bin from a given user
935
+     *
936
+     * @param string $user user who owns the trash bin
937
+     * @return integer trash bin size
938
+     */
939
+    private static function getTrashbinSize($user) {
940
+        $view = new View('/' . $user);
941
+        $fileInfo = $view->getFileInfo('/files_trashbin');
942
+        return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
943
+    }
944
+
945
+    /**
946
+     * register hooks
947
+     */
948
+    public static function registerHooks() {
949
+        // create storage wrapper on setup
950
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
951
+        //Listen to delete user signal
952
+        \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
953
+        //Listen to post write hook
954
+        \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
955
+        // pre and post-rename, disable trash logic for the copy+unlink case
956
+        \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
957
+        \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook');
958
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook');
959
+    }
960
+
961
+    /**
962
+     * check if trash bin is empty for a given user
963
+     *
964
+     * @param string $user
965
+     * @return bool
966
+     */
967
+    public static function isEmpty($user) {
968
+
969
+        $view = new View('/' . $user . '/files_trashbin');
970
+        if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
971
+            while ($file = readdir($dh)) {
972
+                if (!Filesystem::isIgnoredDir($file)) {
973
+                    return false;
974
+                }
975
+            }
976
+        }
977
+        return true;
978
+    }
979
+
980
+    /**
981
+     * @param $path
982
+     * @return string
983
+     */
984
+    public static function preview_icon($path) {
985
+        return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path));
986
+    }
987 987
 }
Please login to merge, or discard this patch.