Completed
Push — master ( c67736...97c216 )
by Morris
179:58 queued 161:40
created
lib/private/Files/ObjectStore/ObjectStoreStorage.php 2 patches
Indentation   +392 added lines, -392 removed lines patch added patch discarded remove patch
@@ -31,396 +31,396 @@
 block discarded – undo
31 31
 use OCP\Files\ObjectStore\IObjectStore;
32 32
 
33 33
 class ObjectStoreStorage extends \OC\Files\Storage\Common {
34
-	/**
35
-	 * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
-	 */
37
-	protected $objectStore;
38
-	/**
39
-	 * @var string $id
40
-	 */
41
-	protected $id;
42
-	/**
43
-	 * @var \OC\User\User $user
44
-	 */
45
-	protected $user;
46
-
47
-	private $objectPrefix = 'urn:oid:';
48
-
49
-	private $logger;
50
-
51
-	public function __construct($params) {
52
-		if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
-			$this->objectStore = $params['objectstore'];
54
-		} else {
55
-			throw new \Exception('missing IObjectStore instance');
56
-		}
57
-		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
59
-		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
61
-		}
62
-		if (isset($params['objectPrefix'])) {
63
-			$this->objectPrefix = $params['objectPrefix'];
64
-		}
65
-		//initialize cache with root directory in cache
66
-		if (!$this->is_dir('/')) {
67
-			$this->mkdir('/');
68
-		}
69
-
70
-		$this->logger = \OC::$server->getLogger();
71
-	}
72
-
73
-	public function mkdir($path) {
74
-		$path = $this->normalizePath($path);
75
-
76
-		if ($this->file_exists($path)) {
77
-			return false;
78
-		}
79
-
80
-		$mTime = time();
81
-		$data = [
82
-			'mimetype' => 'httpd/unix-directory',
83
-			'size' => 0,
84
-			'mtime' => $mTime,
85
-			'storage_mtime' => $mTime,
86
-			'permissions' => \OCP\Constants::PERMISSION_ALL,
87
-		];
88
-		if ($path === '') {
89
-			//create root on the fly
90
-			$data['etag'] = $this->getETag('');
91
-			$this->getCache()->put('', $data);
92
-			return true;
93
-		} else {
94
-			// if parent does not exist, create it
95
-			$parent = $this->normalizePath(dirname($path));
96
-			$parentType = $this->filetype($parent);
97
-			if ($parentType === false) {
98
-				if (!$this->mkdir($parent)) {
99
-					// something went wrong
100
-					return false;
101
-				}
102
-			} else if ($parentType === 'file') {
103
-				// parent is a file
104
-				return false;
105
-			}
106
-			// finally create the new dir
107
-			$mTime = time(); // update mtime
108
-			$data['mtime'] = $mTime;
109
-			$data['storage_mtime'] = $mTime;
110
-			$data['etag'] = $this->getETag($path);
111
-			$this->getCache()->put($path, $data);
112
-			return true;
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * @param string $path
118
-	 * @return string
119
-	 */
120
-	private function normalizePath($path) {
121
-		$path = trim($path, '/');
122
-		//FIXME why do we sometimes get a path like 'files//username'?
123
-		$path = str_replace('//', '/', $path);
124
-
125
-		// dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
-		if (!$path || $path === '.') {
127
-			$path = '';
128
-		}
129
-
130
-		return $path;
131
-	}
132
-
133
-	/**
134
-	 * Object Stores use a NoopScanner because metadata is directly stored in
135
-	 * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
-	 *
137
-	 * @param string $path
138
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
-	 * @return \OC\Files\ObjectStore\NoopScanner
140
-	 */
141
-	public function getScanner($path = '', $storage = null) {
142
-		if (!$storage) {
143
-			$storage = $this;
144
-		}
145
-		if (!isset($this->scanner)) {
146
-			$this->scanner = new NoopScanner($storage);
147
-		}
148
-		return $this->scanner;
149
-	}
150
-
151
-	public function getId() {
152
-		return $this->id;
153
-	}
154
-
155
-	public function rmdir($path) {
156
-		$path = $this->normalizePath($path);
157
-
158
-		if (!$this->is_dir($path)) {
159
-			return false;
160
-		}
161
-
162
-		$this->rmObjects($path);
163
-
164
-		$this->getCache()->remove($path);
165
-
166
-		return true;
167
-	}
168
-
169
-	private function rmObjects($path) {
170
-		$children = $this->getCache()->getFolderContents($path);
171
-		foreach ($children as $child) {
172
-			if ($child['mimetype'] === 'httpd/unix-directory') {
173
-				$this->rmObjects($child['path']);
174
-			} else {
175
-				$this->unlink($child['path']);
176
-			}
177
-		}
178
-	}
179
-
180
-	public function unlink($path) {
181
-		$path = $this->normalizePath($path);
182
-		$stat = $this->stat($path);
183
-
184
-		if ($stat && isset($stat['fileid'])) {
185
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
186
-				return $this->rmdir($path);
187
-			}
188
-			try {
189
-				$this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
-			} catch (\Exception $ex) {
191
-				if ($ex->getCode() !== 404) {
192
-					$this->logger->logException($ex, [
193
-						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
-					]);
196
-					return false;
197
-				}
198
-				//removing from cache is ok as it does not exist in the objectstore anyway
199
-			}
200
-			$this->getCache()->remove($path);
201
-			return true;
202
-		}
203
-		return false;
204
-	}
205
-
206
-	public function stat($path) {
207
-		$path = $this->normalizePath($path);
208
-		$cacheEntry = $this->getCache()->get($path);
209
-		if ($cacheEntry instanceof CacheEntry) {
210
-			return $cacheEntry->getData();
211
-		} else {
212
-			return false;
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * Override this method if you need a different unique resource identifier for your object storage implementation.
218
-	 * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
219
-	 * You may need a mapping table to store your URN if it cannot be generated from the fileid.
220
-	 *
221
-	 * @param int $fileId the fileid
222
-	 * @return null|string the unified resource name used to identify the object
223
-	 */
224
-	protected function getURN($fileId) {
225
-		if (is_numeric($fileId)) {
226
-			return $this->objectPrefix . $fileId;
227
-		}
228
-		return null;
229
-	}
230
-
231
-	public function opendir($path) {
232
-		$path = $this->normalizePath($path);
233
-
234
-		try {
235
-			$files = array();
236
-			$folderContents = $this->getCache()->getFolderContents($path);
237
-			foreach ($folderContents as $file) {
238
-				$files[] = $file['name'];
239
-			}
240
-
241
-			return IteratorDirectory::wrap($files);
242
-		} catch (\Exception $e) {
243
-			$this->logger->logException($e);
244
-			return false;
245
-		}
246
-	}
247
-
248
-	public function filetype($path) {
249
-		$path = $this->normalizePath($path);
250
-		$stat = $this->stat($path);
251
-		if ($stat) {
252
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
253
-				return 'dir';
254
-			}
255
-			return 'file';
256
-		} else {
257
-			return false;
258
-		}
259
-	}
260
-
261
-	public function fopen($path, $mode) {
262
-		$path = $this->normalizePath($path);
263
-
264
-		switch ($mode) {
265
-			case 'r':
266
-			case 'rb':
267
-				$stat = $this->stat($path);
268
-				if (is_array($stat)) {
269
-					try {
270
-						return $this->objectStore->readObject($this->getURN($stat['fileid']));
271
-					} catch (\Exception $ex) {
272
-						$this->logger->logException($ex, [
273
-							'app' => 'objectstore',
274
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
275
-						]);
276
-						return false;
277
-					}
278
-				} else {
279
-					return false;
280
-				}
281
-			case 'w':
282
-			case 'wb':
283
-			case 'a':
284
-			case 'ab':
285
-			case 'r+':
286
-			case 'w+':
287
-			case 'wb+':
288
-			case 'a+':
289
-			case 'x':
290
-			case 'x+':
291
-			case 'c':
292
-			case 'c+':
293
-				if (strrpos($path, '.') !== false) {
294
-					$ext = substr($path, strrpos($path, '.'));
295
-				} else {
296
-					$ext = '';
297
-				}
298
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
299
-				if ($this->file_exists($path)) {
300
-					$source = $this->fopen($path, 'r');
301
-					file_put_contents($tmpFile, $source);
302
-				}
303
-				$handle = fopen($tmpFile, $mode);
304
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
305
-					$this->writeBack($tmpFile, $path);
306
-				});
307
-		}
308
-		return false;
309
-	}
310
-
311
-	public function file_exists($path) {
312
-		$path = $this->normalizePath($path);
313
-		return (bool)$this->stat($path);
314
-	}
315
-
316
-	public function rename($source, $target) {
317
-		$source = $this->normalizePath($source);
318
-		$target = $this->normalizePath($target);
319
-		$this->remove($target);
320
-		$this->getCache()->move($source, $target);
321
-		$this->touch(dirname($target));
322
-		return true;
323
-	}
324
-
325
-	public function getMimeType($path) {
326
-		$path = $this->normalizePath($path);
327
-		$stat = $this->stat($path);
328
-		if (is_array($stat)) {
329
-			return $stat['mimetype'];
330
-		} else {
331
-			return false;
332
-		}
333
-	}
334
-
335
-	public function touch($path, $mtime = null) {
336
-		if (is_null($mtime)) {
337
-			$mtime = time();
338
-		}
339
-
340
-		$path = $this->normalizePath($path);
341
-		$dirName = dirname($path);
342
-		$parentExists = $this->is_dir($dirName);
343
-		if (!$parentExists) {
344
-			return false;
345
-		}
346
-
347
-		$stat = $this->stat($path);
348
-		if (is_array($stat)) {
349
-			// update existing mtime in db
350
-			$stat['mtime'] = $mtime;
351
-			$this->getCache()->update($stat['fileid'], $stat);
352
-		} else {
353
-			try {
354
-				//create a empty file, need to have at least on char to make it
355
-				// work with all object storage implementations
356
-				$this->file_put_contents($path, ' ');
357
-				$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
358
-				$stat = array(
359
-					'etag' => $this->getETag($path),
360
-					'mimetype' => $mimeType,
361
-					'size' => 0,
362
-					'mtime' => $mtime,
363
-					'storage_mtime' => $mtime,
364
-					'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
365
-				);
366
-				$this->getCache()->put($path, $stat);
367
-			} catch (\Exception $ex) {
368
-				$this->logger->logException($ex, [
369
-					'app' => 'objectstore',
370
-					'message' => 'Could not create object for ' . $path,
371
-				]);
372
-				return false;
373
-			}
374
-		}
375
-		return true;
376
-	}
377
-
378
-	public function writeBack($tmpFile, $path) {
379
-		$stat = $this->stat($path);
380
-		if (empty($stat)) {
381
-			// create new file
382
-			$stat = array(
383
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
384
-			);
385
-		}
386
-		// update stat with new data
387
-		$mTime = time();
388
-		$stat['size'] = filesize($tmpFile);
389
-		$stat['mtime'] = $mTime;
390
-		$stat['storage_mtime'] = $mTime;
391
-
392
-		// run path based detection first, to use file extension because $tmpFile is only a random string
393
-		$mimetypeDetector = \OC::$server->getMimeTypeDetector();
394
-		$mimetype = $mimetypeDetector->detectPath($path);
395
-		if ($mimetype === 'application/octet-stream') {
396
-			$mimetype = $mimetypeDetector->detect($tmpFile);
397
-		}
398
-
399
-		$stat['mimetype'] = $mimetype;
400
-		$stat['etag'] = $this->getETag($path);
401
-
402
-		$fileId = $this->getCache()->put($path, $stat);
403
-		try {
404
-			//upload to object storage
405
-			$this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
406
-		} catch (\Exception $ex) {
407
-			$this->getCache()->remove($path);
408
-			$this->logger->logException($ex, [
409
-				'app' => 'objectstore',
410
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
411
-			]);
412
-			throw $ex; // make this bubble up
413
-		}
414
-	}
415
-
416
-	/**
417
-	 * external changes are not supported, exclusive access to the object storage is assumed
418
-	 *
419
-	 * @param string $path
420
-	 * @param int $time
421
-	 * @return false
422
-	 */
423
-	public function hasUpdated($path, $time) {
424
-		return false;
425
-	}
34
+    /**
35
+     * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
+     */
37
+    protected $objectStore;
38
+    /**
39
+     * @var string $id
40
+     */
41
+    protected $id;
42
+    /**
43
+     * @var \OC\User\User $user
44
+     */
45
+    protected $user;
46
+
47
+    private $objectPrefix = 'urn:oid:';
48
+
49
+    private $logger;
50
+
51
+    public function __construct($params) {
52
+        if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
+            $this->objectStore = $params['objectstore'];
54
+        } else {
55
+            throw new \Exception('missing IObjectStore instance');
56
+        }
57
+        if (isset($params['storageid'])) {
58
+            $this->id = 'object::store:' . $params['storageid'];
59
+        } else {
60
+            $this->id = 'object::store:' . $this->objectStore->getStorageId();
61
+        }
62
+        if (isset($params['objectPrefix'])) {
63
+            $this->objectPrefix = $params['objectPrefix'];
64
+        }
65
+        //initialize cache with root directory in cache
66
+        if (!$this->is_dir('/')) {
67
+            $this->mkdir('/');
68
+        }
69
+
70
+        $this->logger = \OC::$server->getLogger();
71
+    }
72
+
73
+    public function mkdir($path) {
74
+        $path = $this->normalizePath($path);
75
+
76
+        if ($this->file_exists($path)) {
77
+            return false;
78
+        }
79
+
80
+        $mTime = time();
81
+        $data = [
82
+            'mimetype' => 'httpd/unix-directory',
83
+            'size' => 0,
84
+            'mtime' => $mTime,
85
+            'storage_mtime' => $mTime,
86
+            'permissions' => \OCP\Constants::PERMISSION_ALL,
87
+        ];
88
+        if ($path === '') {
89
+            //create root on the fly
90
+            $data['etag'] = $this->getETag('');
91
+            $this->getCache()->put('', $data);
92
+            return true;
93
+        } else {
94
+            // if parent does not exist, create it
95
+            $parent = $this->normalizePath(dirname($path));
96
+            $parentType = $this->filetype($parent);
97
+            if ($parentType === false) {
98
+                if (!$this->mkdir($parent)) {
99
+                    // something went wrong
100
+                    return false;
101
+                }
102
+            } else if ($parentType === 'file') {
103
+                // parent is a file
104
+                return false;
105
+            }
106
+            // finally create the new dir
107
+            $mTime = time(); // update mtime
108
+            $data['mtime'] = $mTime;
109
+            $data['storage_mtime'] = $mTime;
110
+            $data['etag'] = $this->getETag($path);
111
+            $this->getCache()->put($path, $data);
112
+            return true;
113
+        }
114
+    }
115
+
116
+    /**
117
+     * @param string $path
118
+     * @return string
119
+     */
120
+    private function normalizePath($path) {
121
+        $path = trim($path, '/');
122
+        //FIXME why do we sometimes get a path like 'files//username'?
123
+        $path = str_replace('//', '/', $path);
124
+
125
+        // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
+        if (!$path || $path === '.') {
127
+            $path = '';
128
+        }
129
+
130
+        return $path;
131
+    }
132
+
133
+    /**
134
+     * Object Stores use a NoopScanner because metadata is directly stored in
135
+     * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
+     *
137
+     * @param string $path
138
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
+     * @return \OC\Files\ObjectStore\NoopScanner
140
+     */
141
+    public function getScanner($path = '', $storage = null) {
142
+        if (!$storage) {
143
+            $storage = $this;
144
+        }
145
+        if (!isset($this->scanner)) {
146
+            $this->scanner = new NoopScanner($storage);
147
+        }
148
+        return $this->scanner;
149
+    }
150
+
151
+    public function getId() {
152
+        return $this->id;
153
+    }
154
+
155
+    public function rmdir($path) {
156
+        $path = $this->normalizePath($path);
157
+
158
+        if (!$this->is_dir($path)) {
159
+            return false;
160
+        }
161
+
162
+        $this->rmObjects($path);
163
+
164
+        $this->getCache()->remove($path);
165
+
166
+        return true;
167
+    }
168
+
169
+    private function rmObjects($path) {
170
+        $children = $this->getCache()->getFolderContents($path);
171
+        foreach ($children as $child) {
172
+            if ($child['mimetype'] === 'httpd/unix-directory') {
173
+                $this->rmObjects($child['path']);
174
+            } else {
175
+                $this->unlink($child['path']);
176
+            }
177
+        }
178
+    }
179
+
180
+    public function unlink($path) {
181
+        $path = $this->normalizePath($path);
182
+        $stat = $this->stat($path);
183
+
184
+        if ($stat && isset($stat['fileid'])) {
185
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
186
+                return $this->rmdir($path);
187
+            }
188
+            try {
189
+                $this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
+            } catch (\Exception $ex) {
191
+                if ($ex->getCode() !== 404) {
192
+                    $this->logger->logException($ex, [
193
+                        'app' => 'objectstore',
194
+                        'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
+                    ]);
196
+                    return false;
197
+                }
198
+                //removing from cache is ok as it does not exist in the objectstore anyway
199
+            }
200
+            $this->getCache()->remove($path);
201
+            return true;
202
+        }
203
+        return false;
204
+    }
205
+
206
+    public function stat($path) {
207
+        $path = $this->normalizePath($path);
208
+        $cacheEntry = $this->getCache()->get($path);
209
+        if ($cacheEntry instanceof CacheEntry) {
210
+            return $cacheEntry->getData();
211
+        } else {
212
+            return false;
213
+        }
214
+    }
215
+
216
+    /**
217
+     * Override this method if you need a different unique resource identifier for your object storage implementation.
218
+     * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
219
+     * You may need a mapping table to store your URN if it cannot be generated from the fileid.
220
+     *
221
+     * @param int $fileId the fileid
222
+     * @return null|string the unified resource name used to identify the object
223
+     */
224
+    protected function getURN($fileId) {
225
+        if (is_numeric($fileId)) {
226
+            return $this->objectPrefix . $fileId;
227
+        }
228
+        return null;
229
+    }
230
+
231
+    public function opendir($path) {
232
+        $path = $this->normalizePath($path);
233
+
234
+        try {
235
+            $files = array();
236
+            $folderContents = $this->getCache()->getFolderContents($path);
237
+            foreach ($folderContents as $file) {
238
+                $files[] = $file['name'];
239
+            }
240
+
241
+            return IteratorDirectory::wrap($files);
242
+        } catch (\Exception $e) {
243
+            $this->logger->logException($e);
244
+            return false;
245
+        }
246
+    }
247
+
248
+    public function filetype($path) {
249
+        $path = $this->normalizePath($path);
250
+        $stat = $this->stat($path);
251
+        if ($stat) {
252
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
253
+                return 'dir';
254
+            }
255
+            return 'file';
256
+        } else {
257
+            return false;
258
+        }
259
+    }
260
+
261
+    public function fopen($path, $mode) {
262
+        $path = $this->normalizePath($path);
263
+
264
+        switch ($mode) {
265
+            case 'r':
266
+            case 'rb':
267
+                $stat = $this->stat($path);
268
+                if (is_array($stat)) {
269
+                    try {
270
+                        return $this->objectStore->readObject($this->getURN($stat['fileid']));
271
+                    } catch (\Exception $ex) {
272
+                        $this->logger->logException($ex, [
273
+                            'app' => 'objectstore',
274
+                            'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
275
+                        ]);
276
+                        return false;
277
+                    }
278
+                } else {
279
+                    return false;
280
+                }
281
+            case 'w':
282
+            case 'wb':
283
+            case 'a':
284
+            case 'ab':
285
+            case 'r+':
286
+            case 'w+':
287
+            case 'wb+':
288
+            case 'a+':
289
+            case 'x':
290
+            case 'x+':
291
+            case 'c':
292
+            case 'c+':
293
+                if (strrpos($path, '.') !== false) {
294
+                    $ext = substr($path, strrpos($path, '.'));
295
+                } else {
296
+                    $ext = '';
297
+                }
298
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
299
+                if ($this->file_exists($path)) {
300
+                    $source = $this->fopen($path, 'r');
301
+                    file_put_contents($tmpFile, $source);
302
+                }
303
+                $handle = fopen($tmpFile, $mode);
304
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
305
+                    $this->writeBack($tmpFile, $path);
306
+                });
307
+        }
308
+        return false;
309
+    }
310
+
311
+    public function file_exists($path) {
312
+        $path = $this->normalizePath($path);
313
+        return (bool)$this->stat($path);
314
+    }
315
+
316
+    public function rename($source, $target) {
317
+        $source = $this->normalizePath($source);
318
+        $target = $this->normalizePath($target);
319
+        $this->remove($target);
320
+        $this->getCache()->move($source, $target);
321
+        $this->touch(dirname($target));
322
+        return true;
323
+    }
324
+
325
+    public function getMimeType($path) {
326
+        $path = $this->normalizePath($path);
327
+        $stat = $this->stat($path);
328
+        if (is_array($stat)) {
329
+            return $stat['mimetype'];
330
+        } else {
331
+            return false;
332
+        }
333
+    }
334
+
335
+    public function touch($path, $mtime = null) {
336
+        if (is_null($mtime)) {
337
+            $mtime = time();
338
+        }
339
+
340
+        $path = $this->normalizePath($path);
341
+        $dirName = dirname($path);
342
+        $parentExists = $this->is_dir($dirName);
343
+        if (!$parentExists) {
344
+            return false;
345
+        }
346
+
347
+        $stat = $this->stat($path);
348
+        if (is_array($stat)) {
349
+            // update existing mtime in db
350
+            $stat['mtime'] = $mtime;
351
+            $this->getCache()->update($stat['fileid'], $stat);
352
+        } else {
353
+            try {
354
+                //create a empty file, need to have at least on char to make it
355
+                // work with all object storage implementations
356
+                $this->file_put_contents($path, ' ');
357
+                $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
358
+                $stat = array(
359
+                    'etag' => $this->getETag($path),
360
+                    'mimetype' => $mimeType,
361
+                    'size' => 0,
362
+                    'mtime' => $mtime,
363
+                    'storage_mtime' => $mtime,
364
+                    'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
365
+                );
366
+                $this->getCache()->put($path, $stat);
367
+            } catch (\Exception $ex) {
368
+                $this->logger->logException($ex, [
369
+                    'app' => 'objectstore',
370
+                    'message' => 'Could not create object for ' . $path,
371
+                ]);
372
+                return false;
373
+            }
374
+        }
375
+        return true;
376
+    }
377
+
378
+    public function writeBack($tmpFile, $path) {
379
+        $stat = $this->stat($path);
380
+        if (empty($stat)) {
381
+            // create new file
382
+            $stat = array(
383
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
384
+            );
385
+        }
386
+        // update stat with new data
387
+        $mTime = time();
388
+        $stat['size'] = filesize($tmpFile);
389
+        $stat['mtime'] = $mTime;
390
+        $stat['storage_mtime'] = $mTime;
391
+
392
+        // run path based detection first, to use file extension because $tmpFile is only a random string
393
+        $mimetypeDetector = \OC::$server->getMimeTypeDetector();
394
+        $mimetype = $mimetypeDetector->detectPath($path);
395
+        if ($mimetype === 'application/octet-stream') {
396
+            $mimetype = $mimetypeDetector->detect($tmpFile);
397
+        }
398
+
399
+        $stat['mimetype'] = $mimetype;
400
+        $stat['etag'] = $this->getETag($path);
401
+
402
+        $fileId = $this->getCache()->put($path, $stat);
403
+        try {
404
+            //upload to object storage
405
+            $this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
406
+        } catch (\Exception $ex) {
407
+            $this->getCache()->remove($path);
408
+            $this->logger->logException($ex, [
409
+                'app' => 'objectstore',
410
+                'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
411
+            ]);
412
+            throw $ex; // make this bubble up
413
+        }
414
+    }
415
+
416
+    /**
417
+     * external changes are not supported, exclusive access to the object storage is assumed
418
+     *
419
+     * @param string $path
420
+     * @param int $time
421
+     * @return false
422
+     */
423
+    public function hasUpdated($path, $time) {
424
+        return false;
425
+    }
426 426
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -55,9 +55,9 @@  discard block
 block discarded – undo
55 55
 			throw new \Exception('missing IObjectStore instance');
56 56
 		}
57 57
 		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
58
+			$this->id = 'object::store:'.$params['storageid'];
59 59
 		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
60
+			$this->id = 'object::store:'.$this->objectStore->getStorageId();
61 61
 		}
62 62
 		if (isset($params['objectPrefix'])) {
63 63
 			$this->objectPrefix = $params['objectPrefix'];
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 				if ($ex->getCode() !== 404) {
192 192
 					$this->logger->logException($ex, [
193 193
 						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
194
+						'message' => 'Could not delete object '.$this->getURN($stat['fileid']).' for '.$path,
195 195
 					]);
196 196
 					return false;
197 197
 				}
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 	 */
224 224
 	protected function getURN($fileId) {
225 225
 		if (is_numeric($fileId)) {
226
-			return $this->objectPrefix . $fileId;
226
+			return $this->objectPrefix.$fileId;
227 227
 		}
228 228
 		return null;
229 229
 	}
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 					} catch (\Exception $ex) {
272 272
 						$this->logger->logException($ex, [
273 273
 							'app' => 'objectstore',
274
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
274
+							'message' => 'Count not get object '.$this->getURN($stat['fileid']).' for file '.$path,
275 275
 						]);
276 276
 						return false;
277 277
 					}
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 					file_put_contents($tmpFile, $source);
302 302
 				}
303 303
 				$handle = fopen($tmpFile, $mode);
304
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
304
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
305 305
 					$this->writeBack($tmpFile, $path);
306 306
 				});
307 307
 		}
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 
311 311
 	public function file_exists($path) {
312 312
 		$path = $this->normalizePath($path);
313
-		return (bool)$this->stat($path);
313
+		return (bool) $this->stat($path);
314 314
 	}
315 315
 
316 316
 	public function rename($source, $target) {
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 			} catch (\Exception $ex) {
368 368
 				$this->logger->logException($ex, [
369 369
 					'app' => 'objectstore',
370
-					'message' => 'Could not create object for ' . $path,
370
+					'message' => 'Could not create object for '.$path,
371 371
 				]);
372 372
 				return false;
373 373
 			}
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
 			$this->getCache()->remove($path);
408 408
 			$this->logger->logException($ex, [
409 409
 				'app' => 'objectstore',
410
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
410
+				'message' => 'Could not create object '.$this->getURN($fileId).' for '.$path,
411 411
 			]);
412 412
 			throw $ex; // make this bubble up
413 413
 		}
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/TagsPlugin.php 1 patch
Indentation   +217 added lines, -217 removed lines patch added patch discarded remove patch
@@ -51,246 +51,246 @@
 block discarded – undo
51 51
 class TagsPlugin extends \Sabre\DAV\ServerPlugin
52 52
 {
53 53
 
54
-	// namespace
55
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
56
-	const TAGS_PROPERTYNAME = '{http://owncloud.org/ns}tags';
57
-	const FAVORITE_PROPERTYNAME = '{http://owncloud.org/ns}favorite';
58
-	const TAG_FAVORITE = '_$!<Favorite>!$_';
54
+    // namespace
55
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
56
+    const TAGS_PROPERTYNAME = '{http://owncloud.org/ns}tags';
57
+    const FAVORITE_PROPERTYNAME = '{http://owncloud.org/ns}favorite';
58
+    const TAG_FAVORITE = '_$!<Favorite>!$_';
59 59
 
60
-	/**
61
-	 * Reference to main server object
62
-	 *
63
-	 * @var \Sabre\DAV\Server
64
-	 */
65
-	private $server;
60
+    /**
61
+     * Reference to main server object
62
+     *
63
+     * @var \Sabre\DAV\Server
64
+     */
65
+    private $server;
66 66
 
67
-	/**
68
-	 * @var \OCP\ITagManager
69
-	 */
70
-	private $tagManager;
67
+    /**
68
+     * @var \OCP\ITagManager
69
+     */
70
+    private $tagManager;
71 71
 
72
-	/**
73
-	 * @var \OCP\ITags
74
-	 */
75
-	private $tagger;
72
+    /**
73
+     * @var \OCP\ITags
74
+     */
75
+    private $tagger;
76 76
 
77
-	/**
78
-	 * Array of file id to tags array
79
-	 * The null value means the cache wasn't initialized.
80
-	 *
81
-	 * @var array
82
-	 */
83
-	private $cachedTags;
77
+    /**
78
+     * Array of file id to tags array
79
+     * The null value means the cache wasn't initialized.
80
+     *
81
+     * @var array
82
+     */
83
+    private $cachedTags;
84 84
 
85
-	/**
86
-	 * @var \Sabre\DAV\Tree
87
-	 */
88
-	private $tree;
85
+    /**
86
+     * @var \Sabre\DAV\Tree
87
+     */
88
+    private $tree;
89 89
 
90
-	/**
91
-	 * @param \Sabre\DAV\Tree $tree tree
92
-	 * @param \OCP\ITagManager $tagManager tag manager
93
-	 */
94
-	public function __construct(\Sabre\DAV\Tree $tree, \OCP\ITagManager $tagManager) {
95
-		$this->tree = $tree;
96
-		$this->tagManager = $tagManager;
97
-		$this->tagger = null;
98
-		$this->cachedTags = array();
99
-	}
90
+    /**
91
+     * @param \Sabre\DAV\Tree $tree tree
92
+     * @param \OCP\ITagManager $tagManager tag manager
93
+     */
94
+    public function __construct(\Sabre\DAV\Tree $tree, \OCP\ITagManager $tagManager) {
95
+        $this->tree = $tree;
96
+        $this->tagManager = $tagManager;
97
+        $this->tagger = null;
98
+        $this->cachedTags = array();
99
+    }
100 100
 
101
-	/**
102
-	 * This initializes the plugin.
103
-	 *
104
-	 * This function is called by \Sabre\DAV\Server, after
105
-	 * addPlugin is called.
106
-	 *
107
-	 * This method should set up the required event subscriptions.
108
-	 *
109
-	 * @param \Sabre\DAV\Server $server
110
-	 * @return void
111
-	 */
112
-	public function initialize(\Sabre\DAV\Server $server) {
101
+    /**
102
+     * This initializes the plugin.
103
+     *
104
+     * This function is called by \Sabre\DAV\Server, after
105
+     * addPlugin is called.
106
+     *
107
+     * This method should set up the required event subscriptions.
108
+     *
109
+     * @param \Sabre\DAV\Server $server
110
+     * @return void
111
+     */
112
+    public function initialize(\Sabre\DAV\Server $server) {
113 113
 
114
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
115
-		$server->xml->elementMap[self::TAGS_PROPERTYNAME] = 'OCA\\DAV\\Connector\\Sabre\\TagList';
114
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
115
+        $server->xml->elementMap[self::TAGS_PROPERTYNAME] = 'OCA\\DAV\\Connector\\Sabre\\TagList';
116 116
 
117
-		$this->server = $server;
118
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
119
-		$this->server->on('propPatch', array($this, 'handleUpdateProperties'));
120
-	}
117
+        $this->server = $server;
118
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
119
+        $this->server->on('propPatch', array($this, 'handleUpdateProperties'));
120
+    }
121 121
 
122
-	/**
123
-	 * Returns the tagger
124
-	 *
125
-	 * @return \OCP\ITags tagger
126
-	 */
127
-	private function getTagger() {
128
-		if (!$this->tagger) {
129
-			$this->tagger = $this->tagManager->load('files');
130
-		}
131
-		return $this->tagger;
132
-	}
122
+    /**
123
+     * Returns the tagger
124
+     *
125
+     * @return \OCP\ITags tagger
126
+     */
127
+    private function getTagger() {
128
+        if (!$this->tagger) {
129
+            $this->tagger = $this->tagManager->load('files');
130
+        }
131
+        return $this->tagger;
132
+    }
133 133
 
134
-	/**
135
-	 * Returns tags and favorites.
136
-	 *
137
-	 * @param integer $fileId file id
138
-	 * @return array list($tags, $favorite) with $tags as tag array
139
-	 * and $favorite is a boolean whether the file was favorited
140
-	 */
141
-	private function getTagsAndFav($fileId) {
142
-		$isFav = false;
143
-		$tags = $this->getTags($fileId);
144
-		if ($tags) {
145
-			$favPos = array_search(self::TAG_FAVORITE, $tags);
146
-			if ($favPos !== false) {
147
-				$isFav = true;
148
-				unset($tags[$favPos]);
149
-			}
150
-		}
151
-		return array($tags, $isFav);
152
-	}
134
+    /**
135
+     * Returns tags and favorites.
136
+     *
137
+     * @param integer $fileId file id
138
+     * @return array list($tags, $favorite) with $tags as tag array
139
+     * and $favorite is a boolean whether the file was favorited
140
+     */
141
+    private function getTagsAndFav($fileId) {
142
+        $isFav = false;
143
+        $tags = $this->getTags($fileId);
144
+        if ($tags) {
145
+            $favPos = array_search(self::TAG_FAVORITE, $tags);
146
+            if ($favPos !== false) {
147
+                $isFav = true;
148
+                unset($tags[$favPos]);
149
+            }
150
+        }
151
+        return array($tags, $isFav);
152
+    }
153 153
 
154
-	/**
155
-	 * Returns tags for the given file id
156
-	 *
157
-	 * @param integer $fileId file id
158
-	 * @return array list of tags for that file
159
-	 */
160
-	private function getTags($fileId) {
161
-		if (isset($this->cachedTags[$fileId])) {
162
-			return $this->cachedTags[$fileId];
163
-		} else {
164
-			$tags = $this->getTagger()->getTagsForObjects(array($fileId));
165
-			if ($tags !== false) {
166
-				if (empty($tags)) {
167
-					return array();
168
-				}
169
-				return current($tags);
170
-			}
171
-		}
172
-		return null;
173
-	}
154
+    /**
155
+     * Returns tags for the given file id
156
+     *
157
+     * @param integer $fileId file id
158
+     * @return array list of tags for that file
159
+     */
160
+    private function getTags($fileId) {
161
+        if (isset($this->cachedTags[$fileId])) {
162
+            return $this->cachedTags[$fileId];
163
+        } else {
164
+            $tags = $this->getTagger()->getTagsForObjects(array($fileId));
165
+            if ($tags !== false) {
166
+                if (empty($tags)) {
167
+                    return array();
168
+                }
169
+                return current($tags);
170
+            }
171
+        }
172
+        return null;
173
+    }
174 174
 
175
-	/**
176
-	 * Updates the tags of the given file id
177
-	 *
178
-	 * @param int $fileId
179
-	 * @param array $tags array of tag strings
180
-	 */
181
-	private function updateTags($fileId, $tags) {
182
-		$tagger = $this->getTagger();
183
-		$currentTags = $this->getTags($fileId);
175
+    /**
176
+     * Updates the tags of the given file id
177
+     *
178
+     * @param int $fileId
179
+     * @param array $tags array of tag strings
180
+     */
181
+    private function updateTags($fileId, $tags) {
182
+        $tagger = $this->getTagger();
183
+        $currentTags = $this->getTags($fileId);
184 184
 
185
-		$newTags = array_diff($tags, $currentTags);
186
-		foreach ($newTags as $tag) {
187
-			if ($tag === self::TAG_FAVORITE) {
188
-				continue;
189
-			}
190
-			$tagger->tagAs($fileId, $tag);
191
-		}
192
-		$deletedTags = array_diff($currentTags, $tags);
193
-		foreach ($deletedTags as $tag) {
194
-			if ($tag === self::TAG_FAVORITE) {
195
-				continue;
196
-			}
197
-			$tagger->unTag($fileId, $tag);
198
-		}
199
-	}
185
+        $newTags = array_diff($tags, $currentTags);
186
+        foreach ($newTags as $tag) {
187
+            if ($tag === self::TAG_FAVORITE) {
188
+                continue;
189
+            }
190
+            $tagger->tagAs($fileId, $tag);
191
+        }
192
+        $deletedTags = array_diff($currentTags, $tags);
193
+        foreach ($deletedTags as $tag) {
194
+            if ($tag === self::TAG_FAVORITE) {
195
+                continue;
196
+            }
197
+            $tagger->unTag($fileId, $tag);
198
+        }
199
+    }
200 200
 
201
-	/**
202
-	 * Adds tags and favorites properties to the response,
203
-	 * if requested.
204
-	 *
205
-	 * @param PropFind $propFind
206
-	 * @param \Sabre\DAV\INode $node
207
-	 * @return void
208
-	 */
209
-	public function handleGetProperties(
210
-		PropFind $propFind,
211
-		\Sabre\DAV\INode $node
212
-	) {
213
-		if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
214
-			return;
215
-		}
201
+    /**
202
+     * Adds tags and favorites properties to the response,
203
+     * if requested.
204
+     *
205
+     * @param PropFind $propFind
206
+     * @param \Sabre\DAV\INode $node
207
+     * @return void
208
+     */
209
+    public function handleGetProperties(
210
+        PropFind $propFind,
211
+        \Sabre\DAV\INode $node
212
+    ) {
213
+        if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
214
+            return;
215
+        }
216 216
 
217
-		// need prefetch ?
218
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Directory
219
-			&& $propFind->getDepth() !== 0
220
-			&& (!is_null($propFind->getStatus(self::TAGS_PROPERTYNAME))
221
-			|| !is_null($propFind->getStatus(self::FAVORITE_PROPERTYNAME))
222
-		)) {
223
-			// note: pre-fetching only supported for depth <= 1
224
-			$folderContent = $node->getChildren();
225
-			$fileIds[] = (int)$node->getId();
226
-			foreach ($folderContent as $info) {
227
-				$fileIds[] = (int)$info->getId();
228
-			}
229
-			$tags = $this->getTagger()->getTagsForObjects($fileIds);
230
-			if ($tags === false) {
231
-				// the tags API returns false on error...
232
-				$tags = array();
233
-			}
217
+        // need prefetch ?
218
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Directory
219
+            && $propFind->getDepth() !== 0
220
+            && (!is_null($propFind->getStatus(self::TAGS_PROPERTYNAME))
221
+            || !is_null($propFind->getStatus(self::FAVORITE_PROPERTYNAME))
222
+        )) {
223
+            // note: pre-fetching only supported for depth <= 1
224
+            $folderContent = $node->getChildren();
225
+            $fileIds[] = (int)$node->getId();
226
+            foreach ($folderContent as $info) {
227
+                $fileIds[] = (int)$info->getId();
228
+            }
229
+            $tags = $this->getTagger()->getTagsForObjects($fileIds);
230
+            if ($tags === false) {
231
+                // the tags API returns false on error...
232
+                $tags = array();
233
+            }
234 234
 
235
-			$this->cachedTags = $this->cachedTags + $tags;
236
-			$emptyFileIds = array_diff($fileIds, array_keys($tags));
237
-			// also cache the ones that were not found
238
-			foreach ($emptyFileIds as $fileId) {
239
-				$this->cachedTags[$fileId] = [];
240
-			}
241
-		}
235
+            $this->cachedTags = $this->cachedTags + $tags;
236
+            $emptyFileIds = array_diff($fileIds, array_keys($tags));
237
+            // also cache the ones that were not found
238
+            foreach ($emptyFileIds as $fileId) {
239
+                $this->cachedTags[$fileId] = [];
240
+            }
241
+        }
242 242
 
243
-		$isFav = null;
243
+        $isFav = null;
244 244
 
245
-		$propFind->handle(self::TAGS_PROPERTYNAME, function() use (&$isFav, $node) {
246
-			list($tags, $isFav) = $this->getTagsAndFav($node->getId());
247
-			return new TagList($tags);
248
-		});
245
+        $propFind->handle(self::TAGS_PROPERTYNAME, function() use (&$isFav, $node) {
246
+            list($tags, $isFav) = $this->getTagsAndFav($node->getId());
247
+            return new TagList($tags);
248
+        });
249 249
 
250
-		$propFind->handle(self::FAVORITE_PROPERTYNAME, function() use ($isFav, $node) {
251
-			if (is_null($isFav)) {
252
-				list(, $isFav) = $this->getTagsAndFav($node->getId());
253
-			}
254
-			if ($isFav) {
255
-				return 1;
256
-			} else {
257
-				return 0;
258
-			}
259
-		});
260
-	}
250
+        $propFind->handle(self::FAVORITE_PROPERTYNAME, function() use ($isFav, $node) {
251
+            if (is_null($isFav)) {
252
+                list(, $isFav) = $this->getTagsAndFav($node->getId());
253
+            }
254
+            if ($isFav) {
255
+                return 1;
256
+            } else {
257
+                return 0;
258
+            }
259
+        });
260
+    }
261 261
 
262
-	/**
263
-	 * Updates tags and favorites properties, if applicable.
264
-	 *
265
-	 * @param string $path
266
-	 * @param PropPatch $propPatch
267
-	 *
268
-	 * @return void
269
-	 */
270
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
271
-		$node = $this->tree->getNodeForPath($path);
272
-		if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
273
-			return;
274
-		}
262
+    /**
263
+     * Updates tags and favorites properties, if applicable.
264
+     *
265
+     * @param string $path
266
+     * @param PropPatch $propPatch
267
+     *
268
+     * @return void
269
+     */
270
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
271
+        $node = $this->tree->getNodeForPath($path);
272
+        if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
273
+            return;
274
+        }
275 275
 
276
-		$propPatch->handle(self::TAGS_PROPERTYNAME, function($tagList) use ($node) {
277
-			$this->updateTags($node->getId(), $tagList->getTags());
278
-			return true;
279
-		});
276
+        $propPatch->handle(self::TAGS_PROPERTYNAME, function($tagList) use ($node) {
277
+            $this->updateTags($node->getId(), $tagList->getTags());
278
+            return true;
279
+        });
280 280
 
281
-		$propPatch->handle(self::FAVORITE_PROPERTYNAME, function($favState) use ($node) {
282
-			if ((int)$favState === 1 || $favState === 'true') {
283
-				$this->getTagger()->tagAs($node->getId(), self::TAG_FAVORITE);
284
-			} else {
285
-				$this->getTagger()->unTag($node->getId(), self::TAG_FAVORITE);
286
-			}
281
+        $propPatch->handle(self::FAVORITE_PROPERTYNAME, function($favState) use ($node) {
282
+            if ((int)$favState === 1 || $favState === 'true') {
283
+                $this->getTagger()->tagAs($node->getId(), self::TAG_FAVORITE);
284
+            } else {
285
+                $this->getTagger()->unTag($node->getId(), self::TAG_FAVORITE);
286
+            }
287 287
 
288
-			if (is_null($favState)) {
289
-				// confirm deletion
290
-				return 204;
291
-			}
288
+            if (is_null($favState)) {
289
+                // confirm deletion
290
+                return 204;
291
+            }
292 292
 
293
-			return 200;
294
-		});
295
-	}
293
+            return 200;
294
+        });
295
+    }
296 296
 }
Please login to merge, or discard this patch.
apps/files_trashbin/lib/Trashbin.php 2 patches
Indentation   +950 added lines, -950 removed lines patch added patch discarded remove patch
@@ -52,954 +52,954 @@
 block discarded – undo
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
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR);
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
-			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
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
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
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
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', \OCP\Util::ERROR);
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
-					\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);
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
-				$count++;
794
-				$size += self::delete($filename, $user, $timestamp);
795
-				\OC::$server->getLogger()->info(
796
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
797
-					['app' => 'files_trashbin']
798
-				);
799
-			} else {
800
-				break;
801
-			}
802
-		}
803
-
804
-		return array($size, $count);
805
-	}
806
-
807
-	/**
808
-	 * recursive copy to copy a whole directory
809
-	 *
810
-	 * @param string $source source path, relative to the users files directory
811
-	 * @param string $destination destination path relative to the users root directoy
812
-	 * @param View $view file view for the users root directory
813
-	 * @return int
814
-	 * @throws Exceptions\CopyRecursiveException
815
-	 */
816
-	private static function copy_recursive($source, $destination, View $view) {
817
-		$size = 0;
818
-		if ($view->is_dir($source)) {
819
-			$view->mkdir($destination);
820
-			$view->touch($destination, $view->filemtime($source));
821
-			foreach ($view->getDirectoryContent($source) as $i) {
822
-				$pathDir = $source . '/' . $i['name'];
823
-				if ($view->is_dir($pathDir)) {
824
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
825
-				} else {
826
-					$size += $view->filesize($pathDir);
827
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
828
-					if (!$result) {
829
-						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
830
-					}
831
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
832
-				}
833
-			}
834
-		} else {
835
-			$size += $view->filesize($source);
836
-			$result = $view->copy($source, $destination);
837
-			if (!$result) {
838
-				throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
839
-			}
840
-			$view->touch($destination, $view->filemtime($source));
841
-		}
842
-		return $size;
843
-	}
844
-
845
-	/**
846
-	 * find all versions which belong to the file we want to restore
847
-	 *
848
-	 * @param string $filename name of the file which should be restored
849
-	 * @param int $timestamp timestamp when the file was deleted
850
-	 * @return array
851
-	 */
852
-	private static function getVersionsFromTrash($filename, $timestamp, $user) {
853
-		$view = new View('/' . $user . '/files_trashbin/versions');
854
-		$versions = array();
855
-
856
-		//force rescan of versions, local storage may not have updated the cache
857
-		if (!self::$scannedVersions) {
858
-			/** @var \OC\Files\Storage\Storage $storage */
859
-			list($storage,) = $view->resolvePath('/');
860
-			$storage->getScanner()->scan('files_trashbin/versions');
861
-			self::$scannedVersions = true;
862
-		}
863
-
864
-		if ($timestamp) {
865
-			// fetch for old versions
866
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
867
-			$offset = -strlen($timestamp) - 2;
868
-		} else {
869
-			$matches = $view->searchRaw($filename . '.v%');
870
-		}
871
-
872
-		if (is_array($matches)) {
873
-			foreach ($matches as $ma) {
874
-				if ($timestamp) {
875
-					$parts = explode('.v', substr($ma['path'], 0, $offset));
876
-					$versions[] = (end($parts));
877
-				} else {
878
-					$parts = explode('.v', $ma);
879
-					$versions[] = (end($parts));
880
-				}
881
-			}
882
-		}
883
-		return $versions;
884
-	}
885
-
886
-	/**
887
-	 * find unique extension for restored file if a file with the same name already exists
888
-	 *
889
-	 * @param string $location where the file should be restored
890
-	 * @param string $filename name of the file
891
-	 * @param View $view filesystem view relative to users root directory
892
-	 * @return string with unique extension
893
-	 */
894
-	private static function getUniqueFilename($location, $filename, View $view) {
895
-		$ext = pathinfo($filename, PATHINFO_EXTENSION);
896
-		$name = pathinfo($filename, PATHINFO_FILENAME);
897
-		$l = \OC::$server->getL10N('files_trashbin');
898
-
899
-		$location = '/' . trim($location, '/');
900
-
901
-		// if extension is not empty we set a dot in front of it
902
-		if ($ext !== '') {
903
-			$ext = '.' . $ext;
904
-		}
905
-
906
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
907
-			$i = 2;
908
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
909
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
910
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
911
-				$i++;
912
-			}
913
-
914
-			return $uniqueName;
915
-		}
916
-
917
-		return $filename;
918
-	}
919
-
920
-	/**
921
-	 * get the size from a given root folder
922
-	 *
923
-	 * @param View $view file view on the root folder
924
-	 * @return integer size of the folder
925
-	 */
926
-	private static function calculateSize($view) {
927
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
928
-		if (!file_exists($root)) {
929
-			return 0;
930
-		}
931
-		$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
932
-		$size = 0;
933
-
934
-		/**
935
-		 * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
936
-		 * This bug is fixed in PHP 5.5.9 or before
937
-		 * See #8376
938
-		 */
939
-		$iterator->rewind();
940
-		while ($iterator->valid()) {
941
-			$path = $iterator->current();
942
-			$relpath = substr($path, strlen($root) - 1);
943
-			if (!$view->is_dir($relpath)) {
944
-				$size += $view->filesize($relpath);
945
-			}
946
-			$iterator->next();
947
-		}
948
-		return $size;
949
-	}
950
-
951
-	/**
952
-	 * get current size of trash bin from a given user
953
-	 *
954
-	 * @param string $user user who owns the trash bin
955
-	 * @return integer trash bin size
956
-	 */
957
-	private static function getTrashbinSize($user) {
958
-		$view = new View('/' . $user);
959
-		$fileInfo = $view->getFileInfo('/files_trashbin');
960
-		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
961
-	}
962
-
963
-	/**
964
-	 * register hooks
965
-	 */
966
-	public static function registerHooks() {
967
-		// create storage wrapper on setup
968
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
969
-		//Listen to delete user signal
970
-		\OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
971
-		//Listen to post write hook
972
-		\OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
973
-		// pre and post-rename, disable trash logic for the copy+unlink case
974
-		\OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
975
-		\OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook');
976
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook');
977
-	}
978
-
979
-	/**
980
-	 * check if trash bin is empty for a given user
981
-	 *
982
-	 * @param string $user
983
-	 * @return bool
984
-	 */
985
-	public static function isEmpty($user) {
986
-
987
-		$view = new View('/' . $user . '/files_trashbin');
988
-		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
989
-			while ($file = readdir($dh)) {
990
-				if (!Filesystem::isIgnoredDir($file)) {
991
-					return false;
992
-				}
993
-			}
994
-		}
995
-		return true;
996
-	}
997
-
998
-	/**
999
-	 * @param $path
1000
-	 * @return string
1001
-	 */
1002
-	public static function preview_icon($path) {
1003
-		return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path));
1004
-	}
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
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR);
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
+            \OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
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
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
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
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', \OCP\Util::ERROR);
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
+                    \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);
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
+                $count++;
794
+                $size += self::delete($filename, $user, $timestamp);
795
+                \OC::$server->getLogger()->info(
796
+                    'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
797
+                    ['app' => 'files_trashbin']
798
+                );
799
+            } else {
800
+                break;
801
+            }
802
+        }
803
+
804
+        return array($size, $count);
805
+    }
806
+
807
+    /**
808
+     * recursive copy to copy a whole directory
809
+     *
810
+     * @param string $source source path, relative to the users files directory
811
+     * @param string $destination destination path relative to the users root directoy
812
+     * @param View $view file view for the users root directory
813
+     * @return int
814
+     * @throws Exceptions\CopyRecursiveException
815
+     */
816
+    private static function copy_recursive($source, $destination, View $view) {
817
+        $size = 0;
818
+        if ($view->is_dir($source)) {
819
+            $view->mkdir($destination);
820
+            $view->touch($destination, $view->filemtime($source));
821
+            foreach ($view->getDirectoryContent($source) as $i) {
822
+                $pathDir = $source . '/' . $i['name'];
823
+                if ($view->is_dir($pathDir)) {
824
+                    $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
825
+                } else {
826
+                    $size += $view->filesize($pathDir);
827
+                    $result = $view->copy($pathDir, $destination . '/' . $i['name']);
828
+                    if (!$result) {
829
+                        throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
830
+                    }
831
+                    $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
832
+                }
833
+            }
834
+        } else {
835
+            $size += $view->filesize($source);
836
+            $result = $view->copy($source, $destination);
837
+            if (!$result) {
838
+                throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
839
+            }
840
+            $view->touch($destination, $view->filemtime($source));
841
+        }
842
+        return $size;
843
+    }
844
+
845
+    /**
846
+     * find all versions which belong to the file we want to restore
847
+     *
848
+     * @param string $filename name of the file which should be restored
849
+     * @param int $timestamp timestamp when the file was deleted
850
+     * @return array
851
+     */
852
+    private static function getVersionsFromTrash($filename, $timestamp, $user) {
853
+        $view = new View('/' . $user . '/files_trashbin/versions');
854
+        $versions = array();
855
+
856
+        //force rescan of versions, local storage may not have updated the cache
857
+        if (!self::$scannedVersions) {
858
+            /** @var \OC\Files\Storage\Storage $storage */
859
+            list($storage,) = $view->resolvePath('/');
860
+            $storage->getScanner()->scan('files_trashbin/versions');
861
+            self::$scannedVersions = true;
862
+        }
863
+
864
+        if ($timestamp) {
865
+            // fetch for old versions
866
+            $matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
867
+            $offset = -strlen($timestamp) - 2;
868
+        } else {
869
+            $matches = $view->searchRaw($filename . '.v%');
870
+        }
871
+
872
+        if (is_array($matches)) {
873
+            foreach ($matches as $ma) {
874
+                if ($timestamp) {
875
+                    $parts = explode('.v', substr($ma['path'], 0, $offset));
876
+                    $versions[] = (end($parts));
877
+                } else {
878
+                    $parts = explode('.v', $ma);
879
+                    $versions[] = (end($parts));
880
+                }
881
+            }
882
+        }
883
+        return $versions;
884
+    }
885
+
886
+    /**
887
+     * find unique extension for restored file if a file with the same name already exists
888
+     *
889
+     * @param string $location where the file should be restored
890
+     * @param string $filename name of the file
891
+     * @param View $view filesystem view relative to users root directory
892
+     * @return string with unique extension
893
+     */
894
+    private static function getUniqueFilename($location, $filename, View $view) {
895
+        $ext = pathinfo($filename, PATHINFO_EXTENSION);
896
+        $name = pathinfo($filename, PATHINFO_FILENAME);
897
+        $l = \OC::$server->getL10N('files_trashbin');
898
+
899
+        $location = '/' . trim($location, '/');
900
+
901
+        // if extension is not empty we set a dot in front of it
902
+        if ($ext !== '') {
903
+            $ext = '.' . $ext;
904
+        }
905
+
906
+        if ($view->file_exists('files' . $location . '/' . $filename)) {
907
+            $i = 2;
908
+            $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
909
+            while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
910
+                $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
911
+                $i++;
912
+            }
913
+
914
+            return $uniqueName;
915
+        }
916
+
917
+        return $filename;
918
+    }
919
+
920
+    /**
921
+     * get the size from a given root folder
922
+     *
923
+     * @param View $view file view on the root folder
924
+     * @return integer size of the folder
925
+     */
926
+    private static function calculateSize($view) {
927
+        $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
928
+        if (!file_exists($root)) {
929
+            return 0;
930
+        }
931
+        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
932
+        $size = 0;
933
+
934
+        /**
935
+         * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
936
+         * This bug is fixed in PHP 5.5.9 or before
937
+         * See #8376
938
+         */
939
+        $iterator->rewind();
940
+        while ($iterator->valid()) {
941
+            $path = $iterator->current();
942
+            $relpath = substr($path, strlen($root) - 1);
943
+            if (!$view->is_dir($relpath)) {
944
+                $size += $view->filesize($relpath);
945
+            }
946
+            $iterator->next();
947
+        }
948
+        return $size;
949
+    }
950
+
951
+    /**
952
+     * get current size of trash bin from a given user
953
+     *
954
+     * @param string $user user who owns the trash bin
955
+     * @return integer trash bin size
956
+     */
957
+    private static function getTrashbinSize($user) {
958
+        $view = new View('/' . $user);
959
+        $fileInfo = $view->getFileInfo('/files_trashbin');
960
+        return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
961
+    }
962
+
963
+    /**
964
+     * register hooks
965
+     */
966
+    public static function registerHooks() {
967
+        // create storage wrapper on setup
968
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
969
+        //Listen to delete user signal
970
+        \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
971
+        //Listen to post write hook
972
+        \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
973
+        // pre and post-rename, disable trash logic for the copy+unlink case
974
+        \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
975
+        \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook');
976
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook');
977
+    }
978
+
979
+    /**
980
+     * check if trash bin is empty for a given user
981
+     *
982
+     * @param string $user
983
+     * @return bool
984
+     */
985
+    public static function isEmpty($user) {
986
+
987
+        $view = new View('/' . $user . '/files_trashbin');
988
+        if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
989
+            while ($file = readdir($dh)) {
990
+                if (!Filesystem::isIgnoredDir($file)) {
991
+                    return false;
992
+                }
993
+            }
994
+        }
995
+        return true;
996
+    }
997
+
998
+    /**
999
+     * @param $path
1000
+     * @return string
1001
+     */
1002
+    public static function preview_icon($path) {
1003
+        return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path));
1004
+    }
1005 1005
 }
Please login to merge, or discard this patch.
Spacing   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
257 257
 			if ($trashStorage->file_exists($trashInternalPath)) {
258 258
 				$trashStorage->unlink($trashInternalPath);
259 259
 			}
260
-			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
260
+			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move '.$file_path.' to the trash bin', \OCP\Util::ERROR);
261 261
 		}
262 262
 
263 263
 		if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
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
 block discarded – undo
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
 block discarded – undo
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
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', \OCP\Util::ERROR);
394
+				\OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: '.$user.' $filename: '.$filename.', $timestamp: '.$timestamp.')', \OCP\Util::ERROR);
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
-					\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);
766
+					\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);
767 767
 					$availableSpace += $tmp;
768 768
 					$size += $tmp;
769 769
 				} else {
@@ -793,7 +793,7 @@  discard block
 block discarded – undo
793 793
 				$count++;
794 794
 				$size += self::delete($filename, $user, $timestamp);
795 795
 				\OC::$server->getLogger()->info(
796
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
796
+					'Remove "'.$filename.'" from trashbin because it exceeds max retention obligation term.',
797 797
 					['app' => 'files_trashbin']
798 798
 				);
799 799
 			} else {
@@ -819,16 +819,16 @@  discard block
 block discarded – undo
819 819
 			$view->mkdir($destination);
820 820
 			$view->touch($destination, $view->filemtime($source));
821 821
 			foreach ($view->getDirectoryContent($source) as $i) {
822
-				$pathDir = $source . '/' . $i['name'];
822
+				$pathDir = $source.'/'.$i['name'];
823 823
 				if ($view->is_dir($pathDir)) {
824
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
824
+					$size += self::copy_recursive($pathDir, $destination.'/'.$i['name'], $view);
825 825
 				} else {
826 826
 					$size += $view->filesize($pathDir);
827
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
827
+					$result = $view->copy($pathDir, $destination.'/'.$i['name']);
828 828
 					if (!$result) {
829 829
 						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
830 830
 					}
831
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
831
+					$view->touch($destination.'/'.$i['name'], $view->filemtime($pathDir));
832 832
 				}
833 833
 			}
834 834
 		} else {
@@ -850,7 +850,7 @@  discard block
 block discarded – undo
850 850
 	 * @return array
851 851
 	 */
852 852
 	private static function getVersionsFromTrash($filename, $timestamp, $user) {
853
-		$view = new View('/' . $user . '/files_trashbin/versions');
853
+		$view = new View('/'.$user.'/files_trashbin/versions');
854 854
 		$versions = array();
855 855
 
856 856
 		//force rescan of versions, local storage may not have updated the cache
@@ -863,10 +863,10 @@  discard block
 block discarded – undo
863 863
 
864 864
 		if ($timestamp) {
865 865
 			// fetch for old versions
866
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
866
+			$matches = $view->searchRaw($filename.'.v%.d'.$timestamp);
867 867
 			$offset = -strlen($timestamp) - 2;
868 868
 		} else {
869
-			$matches = $view->searchRaw($filename . '.v%');
869
+			$matches = $view->searchRaw($filename.'.v%');
870 870
 		}
871 871
 
872 872
 		if (is_array($matches)) {
@@ -896,18 +896,18 @@  discard block
 block discarded – undo
896 896
 		$name = pathinfo($filename, PATHINFO_FILENAME);
897 897
 		$l = \OC::$server->getL10N('files_trashbin');
898 898
 
899
-		$location = '/' . trim($location, '/');
899
+		$location = '/'.trim($location, '/');
900 900
 
901 901
 		// if extension is not empty we set a dot in front of it
902 902
 		if ($ext !== '') {
903
-			$ext = '.' . $ext;
903
+			$ext = '.'.$ext;
904 904
 		}
905 905
 
906
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
906
+		if ($view->file_exists('files'.$location.'/'.$filename)) {
907 907
 			$i = 2;
908
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
909
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
910
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
908
+			$uniqueName = $name." (".$l->t("restored").")".$ext;
909
+			while ($view->file_exists('files'.$location.'/'.$uniqueName)) {
910
+				$uniqueName = $name." (".$l->t("restored")." ".$i.")".$ext;
911 911
 				$i++;
912 912
 			}
913 913
 
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
 	 * @return integer size of the folder
925 925
 	 */
926 926
 	private static function calculateSize($view) {
927
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
927
+		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').$view->getAbsolutePath('');
928 928
 		if (!file_exists($root)) {
929 929
 			return 0;
930 930
 		}
@@ -955,7 +955,7 @@  discard block
 block discarded – undo
955 955
 	 * @return integer trash bin size
956 956
 	 */
957 957
 	private static function getTrashbinSize($user) {
958
-		$view = new View('/' . $user);
958
+		$view = new View('/'.$user);
959 959
 		$fileInfo = $view->getFileInfo('/files_trashbin');
960 960
 		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
961 961
 	}
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 	 */
985 985
 	public static function isEmpty($user) {
986 986
 
987
-		$view = new View('/' . $user . '/files_trashbin');
987
+		$view = new View('/'.$user.'/files_trashbin');
988 988
 		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
989 989
 			while ($file = readdir($dh)) {
990 990
 				if (!Filesystem::isIgnoredDir($file)) {
Please login to merge, or discard this patch.