Completed
Pull Request — master (#3676)
by Individual IT
12:49
created
apps/federation/lib/Command/SyncFederationAddressBooks.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -22,7 +22,6 @@
 block discarded – undo
22 22
  */
23 23
 namespace OCA\Federation\Command;
24 24
 
25
-use OCA\Federation\DbHandler;
26 25
 use Symfony\Component\Console\Command\Command;
27 26
 use Symfony\Component\Console\Helper\ProgressBar;
28 27
 use Symfony\Component\Console\Input\InputInterface;
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -31,45 +31,45 @@
 block discarded – undo
31 31
 
32 32
 class SyncFederationAddressBooks extends Command {
33 33
 
34
-	/** @var \OCA\Federation\SyncFederationAddressBooks */
35
-	private $syncService;
34
+    /** @var \OCA\Federation\SyncFederationAddressBooks */
35
+    private $syncService;
36 36
 
37
-	/**
38
-	 * @param \OCA\Federation\SyncFederationAddressBooks $syncService
39
-	 */
40
-	function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
41
-		parent::__construct();
37
+    /**
38
+     * @param \OCA\Federation\SyncFederationAddressBooks $syncService
39
+     */
40
+    function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
41
+        parent::__construct();
42 42
 
43
-		$this->syncService = $syncService;
44
-	}
43
+        $this->syncService = $syncService;
44
+    }
45 45
 
46
-	protected function configure() {
47
-		$this
48
-			->setName('federation:sync-addressbooks')
49
-			->setDescription('Synchronizes addressbooks of all federated clouds');
50
-	}
46
+    protected function configure() {
47
+        $this
48
+            ->setName('federation:sync-addressbooks')
49
+            ->setDescription('Synchronizes addressbooks of all federated clouds');
50
+    }
51 51
 
52
-	/**
53
-	 * @param InputInterface $input
54
-	 * @param OutputInterface $output
55
-	 * @return int
56
-	 */
57
-	protected function execute(InputInterface $input, OutputInterface $output) {
52
+    /**
53
+     * @param InputInterface $input
54
+     * @param OutputInterface $output
55
+     * @return int
56
+     */
57
+    protected function execute(InputInterface $input, OutputInterface $output) {
58 58
 
59
-		$progress = new ProgressBar($output);
60
-		$progress->start();
61
-		$this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62
-			if ($ex instanceof \Exception) {
63
-				$output->writeln("Error while syncing $url : " . $ex->getMessage());
59
+        $progress = new ProgressBar($output);
60
+        $progress->start();
61
+        $this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62
+            if ($ex instanceof \Exception) {
63
+                $output->writeln("Error while syncing $url : " . $ex->getMessage());
64 64
 
65
-			} else {
66
-				$progress->advance();
67
-			}
68
-		});
65
+            } else {
66
+                $progress->advance();
67
+            }
68
+        });
69 69
 
70
-		$progress->finish();
71
-		$output->writeln('');
70
+        $progress->finish();
71
+        $output->writeln('');
72 72
 
73
-		return 0;
74
-	}
73
+        return 0;
74
+    }
75 75
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@
 block discarded – undo
60 60
 		$progress->start();
61 61
 		$this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62 62
 			if ($ex instanceof \Exception) {
63
-				$output->writeln("Error while syncing $url : " . $ex->getMessage());
63
+				$output->writeln("Error while syncing $url : ".$ex->getMessage());
64 64
 
65 65
 			} else {
66 66
 				$progress->advance();
Please login to merge, or discard this patch.
apps/federation/lib/SyncFederationAddressBooks.php 2 patches
Unused Use Statements   -4 removed lines patch added patch discarded remove patch
@@ -24,10 +24,6 @@
 block discarded – undo
24 24
 
25 25
 use OCA\DAV\CardDAV\SyncService;
26 26
 use OCP\AppFramework\Http;
27
-use Symfony\Component\Console\Command\Command;
28
-use Symfony\Component\Console\Helper\ProgressBar;
29
-use Symfony\Component\Console\Input\InputInterface;
30
-use Symfony\Component\Console\Output\OutputInterface;
31 27
 
32 28
 class SyncFederationAddressBooks {
33 29
 
Please login to merge, or discard this patch.
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -32,52 +32,52 @@
 block discarded – undo
32 32
 
33 33
 class SyncFederationAddressBooks {
34 34
 
35
-	/** @var DbHandler */
36
-	protected $dbHandler;
35
+    /** @var DbHandler */
36
+    protected $dbHandler;
37 37
 
38
-	/** @var SyncService */
39
-	private $syncService;
38
+    /** @var SyncService */
39
+    private $syncService;
40 40
 
41
-	/**
42
-	 * @param DbHandler $dbHandler
43
-	 * @param SyncService $syncService
44
-	 */
45
-	function __construct(DbHandler $dbHandler, SyncService $syncService) {
46
-		$this->syncService = $syncService;
47
-		$this->dbHandler = $dbHandler;
48
-	}
41
+    /**
42
+     * @param DbHandler $dbHandler
43
+     * @param SyncService $syncService
44
+     */
45
+    function __construct(DbHandler $dbHandler, SyncService $syncService) {
46
+        $this->syncService = $syncService;
47
+        $this->dbHandler = $dbHandler;
48
+    }
49 49
 
50
-	/**
51
-	 * @param \Closure $callback
52
-	 */
53
-	public function syncThemAll(\Closure $callback) {
50
+    /**
51
+     * @param \Closure $callback
52
+     */
53
+    public function syncThemAll(\Closure $callback) {
54 54
 
55
-		$trustedServers = $this->dbHandler->getAllServer();
56
-		foreach ($trustedServers as $trustedServer) {
57
-			$url = $trustedServer['url'];
58
-			$callback($url, null);
59
-			$sharedSecret = $trustedServer['shared_secret'];
60
-			$syncToken = $trustedServer['sync_token'];
55
+        $trustedServers = $this->dbHandler->getAllServer();
56
+        foreach ($trustedServers as $trustedServer) {
57
+            $url = $trustedServer['url'];
58
+            $callback($url, null);
59
+            $sharedSecret = $trustedServer['shared_secret'];
60
+            $syncToken = $trustedServer['sync_token'];
61 61
 
62
-			if (is_null($sharedSecret)) {
63
-				continue;
64
-			}
65
-			$targetBookId = $trustedServer['url_hash'];
66
-			$targetPrincipal = "principals/system/system";
67
-			$targetBookProperties = [
68
-					'{DAV:}displayname' => $url
69
-			];
70
-			try {
71
-				$newToken = $this->syncService->syncRemoteAddressBook($url, 'system', $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetBookProperties);
72
-				if ($newToken !== $syncToken) {
73
-					$this->dbHandler->setServerStatus($url, TrustedServers::STATUS_OK, $newToken);
74
-				}
75
-			} catch (\Exception $ex) {
76
-				if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
77
-					$this->dbHandler->setServerStatus($url, TrustedServers::STATUS_ACCESS_REVOKED);
78
-				}
79
-				$callback($url, $ex);
80
-			}
81
-		}
82
-	}
62
+            if (is_null($sharedSecret)) {
63
+                continue;
64
+            }
65
+            $targetBookId = $trustedServer['url_hash'];
66
+            $targetPrincipal = "principals/system/system";
67
+            $targetBookProperties = [
68
+                    '{DAV:}displayname' => $url
69
+            ];
70
+            try {
71
+                $newToken = $this->syncService->syncRemoteAddressBook($url, 'system', $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetBookProperties);
72
+                if ($newToken !== $syncToken) {
73
+                    $this->dbHandler->setServerStatus($url, TrustedServers::STATUS_OK, $newToken);
74
+                }
75
+            } catch (\Exception $ex) {
76
+                if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
77
+                    $this->dbHandler->setServerStatus($url, TrustedServers::STATUS_ACCESS_REVOKED);
78
+                }
79
+                $callback($url, $ex);
80
+            }
81
+        }
82
+    }
83 83
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/SFTP.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -32,7 +32,6 @@
 block discarded – undo
32 32
  */
33 33
 namespace OCA\Files_External\Lib\Storage;
34 34
 use Icewind\Streams\IteratorDirectory;
35
-
36 35
 use Icewind\Streams\RetryWrapper;
37 36
 use phpseclib\Net\SFTP\Stream;
38 37
 
Please login to merge, or discard this patch.
Indentation   +424 added lines, -424 removed lines patch added patch discarded remove patch
@@ -42,428 +42,428 @@
 block discarded – undo
42 42
 * provide access to SFTP servers.
43 43
 */
44 44
 class SFTP extends \OC\Files\Storage\Common {
45
-	private $host;
46
-	private $user;
47
-	private $root;
48
-	private $port = 22;
49
-
50
-	private $auth;
51
-
52
-	/**
53
-	 * @var \phpseclib\Net\SFTP
54
-	 */
55
-	protected $client;
56
-
57
-	/**
58
-	 * @param string $host protocol://server:port
59
-	 * @return array [$server, $port]
60
-	 */
61
-	private function splitHost($host) {
62
-		$input = $host;
63
-		if (strpos($host, '://') === false) {
64
-			// add a protocol to fix parse_url behavior with ipv6
65
-			$host = 'http://' . $host;
66
-		}
67
-
68
-		$parsed = parse_url($host);
69
-		if(is_array($parsed) && isset($parsed['port'])) {
70
-			return [$parsed['host'], $parsed['port']];
71
-		} else if (is_array($parsed)) {
72
-			return [$parsed['host'], 22];
73
-		} else {
74
-			return [$input, 22];
75
-		}
76
-	}
77
-
78
-	/**
79
-	 * {@inheritdoc}
80
-	 */
81
-	public function __construct($params) {
82
-		// Register sftp://
83
-		Stream::register();
84
-
85
-		$parsedHost =  $this->splitHost($params['host']);
86
-
87
-		$this->host = $parsedHost[0];
88
-		$this->port = $parsedHost[1];
89
-
90
-		if (!isset($params['user'])) {
91
-			throw new \UnexpectedValueException('no authentication parameters specified');
92
-		}
93
-		$this->user = $params['user'];
94
-
95
-		if (isset($params['public_key_auth'])) {
96
-			$this->auth = $params['public_key_auth'];
97
-		} elseif (isset($params['password'])) {
98
-			$this->auth = $params['password'];
99
-		} else {
100
-			throw new \UnexpectedValueException('no authentication parameters specified');
101
-		}
102
-
103
-		$this->root
104
-			= isset($params['root']) ? $this->cleanPath($params['root']) : '/';
105
-
106
-		if ($this->root[0] != '/') {
107
-			 $this->root = '/' . $this->root;
108
-		}
109
-
110
-		if (substr($this->root, -1, 1) != '/') {
111
-			$this->root .= '/';
112
-		}
113
-	}
114
-
115
-	/**
116
-	 * Returns the connection.
117
-	 *
118
-	 * @return \phpseclib\Net\SFTP connected client instance
119
-	 * @throws \Exception when the connection failed
120
-	 */
121
-	public function getConnection() {
122
-		if (!is_null($this->client)) {
123
-			return $this->client;
124
-		}
125
-
126
-		$hostKeys = $this->readHostKeys();
127
-		$this->client = new \phpseclib\Net\SFTP($this->host, $this->port);
128
-
129
-		// The SSH Host Key MUST be verified before login().
130
-		$currentHostKey = $this->client->getServerPublicHostKey();
131
-		if (array_key_exists($this->host, $hostKeys)) {
132
-			if ($hostKeys[$this->host] != $currentHostKey) {
133
-				throw new \Exception('Host public key does not match known key');
134
-			}
135
-		} else {
136
-			$hostKeys[$this->host] = $currentHostKey;
137
-			$this->writeHostKeys($hostKeys);
138
-		}
139
-
140
-		if (!$this->client->login($this->user, $this->auth)) {
141
-			throw new \Exception('Login failed');
142
-		}
143
-		return $this->client;
144
-	}
145
-
146
-	/**
147
-	 * {@inheritdoc}
148
-	 */
149
-	public function test() {
150
-		if (
151
-			!isset($this->host)
152
-			|| !isset($this->user)
153
-		) {
154
-			return false;
155
-		}
156
-		return $this->getConnection()->nlist() !== false;
157
-	}
158
-
159
-	/**
160
-	 * {@inheritdoc}
161
-	 */
162
-	public function getId(){
163
-		$id = 'sftp::' . $this->user . '@' . $this->host;
164
-		if ($this->port !== 22) {
165
-			$id .= ':' . $this->port;
166
-		}
167
-		// note: this will double the root slash,
168
-		// we should not change it to keep compatible with
169
-		// old storage ids
170
-		$id .= '/' . $this->root;
171
-		return $id;
172
-	}
173
-
174
-	/**
175
-	 * @return string
176
-	 */
177
-	public function getHost() {
178
-		return $this->host;
179
-	}
180
-
181
-	/**
182
-	 * @return string
183
-	 */
184
-	public function getRoot() {
185
-		return $this->root;
186
-	}
187
-
188
-	/**
189
-	 * @return mixed
190
-	 */
191
-	public function getUser() {
192
-		return $this->user;
193
-	}
194
-
195
-	/**
196
-	 * @param string $path
197
-	 * @return string
198
-	 */
199
-	private function absPath($path) {
200
-		return $this->root . $this->cleanPath($path);
201
-	}
202
-
203
-	/**
204
-	 * @return string|false
205
-	 */
206
-	private function hostKeysPath() {
207
-		try {
208
-			$storage_view = \OCP\Files::getStorage('files_external');
209
-			if ($storage_view) {
210
-				return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') .
211
-					$storage_view->getAbsolutePath('') .
212
-					'ssh_hostKeys';
213
-			}
214
-		} catch (\Exception $e) {
215
-		}
216
-		return false;
217
-	}
218
-
219
-	/**
220
-	 * @param $keys
221
-	 * @return bool
222
-	 */
223
-	protected function writeHostKeys($keys) {
224
-		try {
225
-			$keyPath = $this->hostKeysPath();
226
-			if ($keyPath && file_exists($keyPath)) {
227
-				$fp = fopen($keyPath, 'w');
228
-				foreach ($keys as $host => $key) {
229
-					fwrite($fp, $host . '::' . $key . "\n");
230
-				}
231
-				fclose($fp);
232
-				return true;
233
-			}
234
-		} catch (\Exception $e) {
235
-		}
236
-		return false;
237
-	}
238
-
239
-	/**
240
-	 * @return array
241
-	 */
242
-	protected function readHostKeys() {
243
-		try {
244
-			$keyPath = $this->hostKeysPath();
245
-			if (file_exists($keyPath)) {
246
-				$hosts = array();
247
-				$keys = array();
248
-				$lines = file($keyPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
249
-				if ($lines) {
250
-					foreach ($lines as $line) {
251
-						$hostKeyArray = explode("::", $line, 2);
252
-						if (count($hostKeyArray) == 2) {
253
-							$hosts[] = $hostKeyArray[0];
254
-							$keys[] = $hostKeyArray[1];
255
-						}
256
-					}
257
-					return array_combine($hosts, $keys);
258
-				}
259
-			}
260
-		} catch (\Exception $e) {
261
-		}
262
-		return array();
263
-	}
264
-
265
-	/**
266
-	 * {@inheritdoc}
267
-	 */
268
-	public function mkdir($path) {
269
-		try {
270
-			return $this->getConnection()->mkdir($this->absPath($path));
271
-		} catch (\Exception $e) {
272
-			return false;
273
-		}
274
-	}
275
-
276
-	/**
277
-	 * {@inheritdoc}
278
-	 */
279
-	public function rmdir($path) {
280
-		try {
281
-			$result = $this->getConnection()->delete($this->absPath($path), true);
282
-			// workaround: stray stat cache entry when deleting empty folders
283
-			// see https://github.com/phpseclib/phpseclib/issues/706
284
-			$this->getConnection()->clearStatCache();
285
-			return $result;
286
-		} catch (\Exception $e) {
287
-			return false;
288
-		}
289
-	}
290
-
291
-	/**
292
-	 * {@inheritdoc}
293
-	 */
294
-	public function opendir($path) {
295
-		try {
296
-			$list = $this->getConnection()->nlist($this->absPath($path));
297
-			if ($list === false) {
298
-				return false;
299
-			}
300
-
301
-			$id = md5('sftp:' . $path);
302
-			$dirStream = array();
303
-			foreach($list as $file) {
304
-				if ($file != '.' && $file != '..') {
305
-					$dirStream[] = $file;
306
-				}
307
-			}
308
-			return IteratorDirectory::wrap($dirStream);
309
-		} catch(\Exception $e) {
310
-			return false;
311
-		}
312
-	}
313
-
314
-	/**
315
-	 * {@inheritdoc}
316
-	 */
317
-	public function filetype($path) {
318
-		try {
319
-			$stat = $this->getConnection()->stat($this->absPath($path));
320
-			if ($stat['type'] == NET_SFTP_TYPE_REGULAR) {
321
-				return 'file';
322
-			}
323
-
324
-			if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
325
-				return 'dir';
326
-			}
327
-		} catch (\Exception $e) {
328
-
329
-		}
330
-		return false;
331
-	}
332
-
333
-	/**
334
-	 * {@inheritdoc}
335
-	 */
336
-	public function file_exists($path) {
337
-		try {
338
-			return $this->getConnection()->stat($this->absPath($path)) !== false;
339
-		} catch (\Exception $e) {
340
-			return false;
341
-		}
342
-	}
343
-
344
-	/**
345
-	 * {@inheritdoc}
346
-	 */
347
-	public function unlink($path) {
348
-		try {
349
-			return $this->getConnection()->delete($this->absPath($path), true);
350
-		} catch (\Exception $e) {
351
-			return false;
352
-		}
353
-	}
354
-
355
-	/**
356
-	 * {@inheritdoc}
357
-	 */
358
-	public function fopen($path, $mode) {
359
-		try {
360
-			$absPath = $this->absPath($path);
361
-			switch($mode) {
362
-				case 'r':
363
-				case 'rb':
364
-					if ( !$this->file_exists($path)) {
365
-						return false;
366
-					}
367
-				case 'w':
368
-				case 'wb':
369
-				case 'a':
370
-				case 'ab':
371
-				case 'r+':
372
-				case 'w+':
373
-				case 'wb+':
374
-				case 'a+':
375
-				case 'x':
376
-				case 'x+':
377
-				case 'c':
378
-				case 'c+':
379
-					$context = stream_context_create(array('sftp' => array('session' => $this->getConnection())));
380
-					$handle = fopen($this->constructUrl($path), $mode, false, $context);
381
-					return RetryWrapper::wrap($handle);
382
-			}
383
-		} catch (\Exception $e) {
384
-		}
385
-		return false;
386
-	}
387
-
388
-	/**
389
-	 * {@inheritdoc}
390
-	 */
391
-	public function touch($path, $mtime=null) {
392
-		try {
393
-			if (!is_null($mtime)) {
394
-				return false;
395
-			}
396
-			if (!$this->file_exists($path)) {
397
-				$this->getConnection()->put($this->absPath($path), '');
398
-			} else {
399
-				return false;
400
-			}
401
-		} catch (\Exception $e) {
402
-			return false;
403
-		}
404
-		return true;
405
-	}
406
-
407
-	/**
408
-	 * @param string $path
409
-	 * @param string $target
410
-	 * @throws \Exception
411
-	 */
412
-	public function getFile($path, $target) {
413
-		$this->getConnection()->get($path, $target);
414
-	}
415
-
416
-	/**
417
-	 * @param string $path
418
-	 * @param string $target
419
-	 * @throws \Exception
420
-	 */
421
-	public function uploadFile($path, $target) {
422
-		$this->getConnection()->put($target, $path, NET_SFTP_LOCAL_FILE);
423
-	}
424
-
425
-	/**
426
-	 * {@inheritdoc}
427
-	 */
428
-	public function rename($source, $target) {
429
-		try {
430
-			if ($this->file_exists($target)) {
431
-				$this->unlink($target);
432
-			}
433
-			return $this->getConnection()->rename(
434
-				$this->absPath($source),
435
-				$this->absPath($target)
436
-			);
437
-		} catch (\Exception $e) {
438
-			return false;
439
-		}
440
-	}
441
-
442
-	/**
443
-	 * {@inheritdoc}
444
-	 */
445
-	public function stat($path) {
446
-		try {
447
-			$stat = $this->getConnection()->stat($this->absPath($path));
448
-
449
-			$mtime = $stat ? $stat['mtime'] : -1;
450
-			$size = $stat ? $stat['size'] : 0;
451
-
452
-			return array('mtime' => $mtime, 'size' => $size, 'ctime' => -1);
453
-		} catch (\Exception $e) {
454
-			return false;
455
-		}
456
-	}
457
-
458
-	/**
459
-	 * @param string $path
460
-	 * @return string
461
-	 */
462
-	public function constructUrl($path) {
463
-		// Do not pass the password here. We want to use the Net_SFTP object
464
-		// supplied via stream context or fail. We only supply username and
465
-		// hostname because this might show up in logs (they are not used).
466
-		$url = 'sftp://' . urlencode($this->user) . '@' . $this->host . ':' . $this->port . $this->root . $path;
467
-		return $url;
468
-	}
45
+    private $host;
46
+    private $user;
47
+    private $root;
48
+    private $port = 22;
49
+
50
+    private $auth;
51
+
52
+    /**
53
+     * @var \phpseclib\Net\SFTP
54
+     */
55
+    protected $client;
56
+
57
+    /**
58
+     * @param string $host protocol://server:port
59
+     * @return array [$server, $port]
60
+     */
61
+    private function splitHost($host) {
62
+        $input = $host;
63
+        if (strpos($host, '://') === false) {
64
+            // add a protocol to fix parse_url behavior with ipv6
65
+            $host = 'http://' . $host;
66
+        }
67
+
68
+        $parsed = parse_url($host);
69
+        if(is_array($parsed) && isset($parsed['port'])) {
70
+            return [$parsed['host'], $parsed['port']];
71
+        } else if (is_array($parsed)) {
72
+            return [$parsed['host'], 22];
73
+        } else {
74
+            return [$input, 22];
75
+        }
76
+    }
77
+
78
+    /**
79
+     * {@inheritdoc}
80
+     */
81
+    public function __construct($params) {
82
+        // Register sftp://
83
+        Stream::register();
84
+
85
+        $parsedHost =  $this->splitHost($params['host']);
86
+
87
+        $this->host = $parsedHost[0];
88
+        $this->port = $parsedHost[1];
89
+
90
+        if (!isset($params['user'])) {
91
+            throw new \UnexpectedValueException('no authentication parameters specified');
92
+        }
93
+        $this->user = $params['user'];
94
+
95
+        if (isset($params['public_key_auth'])) {
96
+            $this->auth = $params['public_key_auth'];
97
+        } elseif (isset($params['password'])) {
98
+            $this->auth = $params['password'];
99
+        } else {
100
+            throw new \UnexpectedValueException('no authentication parameters specified');
101
+        }
102
+
103
+        $this->root
104
+            = isset($params['root']) ? $this->cleanPath($params['root']) : '/';
105
+
106
+        if ($this->root[0] != '/') {
107
+                $this->root = '/' . $this->root;
108
+        }
109
+
110
+        if (substr($this->root, -1, 1) != '/') {
111
+            $this->root .= '/';
112
+        }
113
+    }
114
+
115
+    /**
116
+     * Returns the connection.
117
+     *
118
+     * @return \phpseclib\Net\SFTP connected client instance
119
+     * @throws \Exception when the connection failed
120
+     */
121
+    public function getConnection() {
122
+        if (!is_null($this->client)) {
123
+            return $this->client;
124
+        }
125
+
126
+        $hostKeys = $this->readHostKeys();
127
+        $this->client = new \phpseclib\Net\SFTP($this->host, $this->port);
128
+
129
+        // The SSH Host Key MUST be verified before login().
130
+        $currentHostKey = $this->client->getServerPublicHostKey();
131
+        if (array_key_exists($this->host, $hostKeys)) {
132
+            if ($hostKeys[$this->host] != $currentHostKey) {
133
+                throw new \Exception('Host public key does not match known key');
134
+            }
135
+        } else {
136
+            $hostKeys[$this->host] = $currentHostKey;
137
+            $this->writeHostKeys($hostKeys);
138
+        }
139
+
140
+        if (!$this->client->login($this->user, $this->auth)) {
141
+            throw new \Exception('Login failed');
142
+        }
143
+        return $this->client;
144
+    }
145
+
146
+    /**
147
+     * {@inheritdoc}
148
+     */
149
+    public function test() {
150
+        if (
151
+            !isset($this->host)
152
+            || !isset($this->user)
153
+        ) {
154
+            return false;
155
+        }
156
+        return $this->getConnection()->nlist() !== false;
157
+    }
158
+
159
+    /**
160
+     * {@inheritdoc}
161
+     */
162
+    public function getId(){
163
+        $id = 'sftp::' . $this->user . '@' . $this->host;
164
+        if ($this->port !== 22) {
165
+            $id .= ':' . $this->port;
166
+        }
167
+        // note: this will double the root slash,
168
+        // we should not change it to keep compatible with
169
+        // old storage ids
170
+        $id .= '/' . $this->root;
171
+        return $id;
172
+    }
173
+
174
+    /**
175
+     * @return string
176
+     */
177
+    public function getHost() {
178
+        return $this->host;
179
+    }
180
+
181
+    /**
182
+     * @return string
183
+     */
184
+    public function getRoot() {
185
+        return $this->root;
186
+    }
187
+
188
+    /**
189
+     * @return mixed
190
+     */
191
+    public function getUser() {
192
+        return $this->user;
193
+    }
194
+
195
+    /**
196
+     * @param string $path
197
+     * @return string
198
+     */
199
+    private function absPath($path) {
200
+        return $this->root . $this->cleanPath($path);
201
+    }
202
+
203
+    /**
204
+     * @return string|false
205
+     */
206
+    private function hostKeysPath() {
207
+        try {
208
+            $storage_view = \OCP\Files::getStorage('files_external');
209
+            if ($storage_view) {
210
+                return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') .
211
+                    $storage_view->getAbsolutePath('') .
212
+                    'ssh_hostKeys';
213
+            }
214
+        } catch (\Exception $e) {
215
+        }
216
+        return false;
217
+    }
218
+
219
+    /**
220
+     * @param $keys
221
+     * @return bool
222
+     */
223
+    protected function writeHostKeys($keys) {
224
+        try {
225
+            $keyPath = $this->hostKeysPath();
226
+            if ($keyPath && file_exists($keyPath)) {
227
+                $fp = fopen($keyPath, 'w');
228
+                foreach ($keys as $host => $key) {
229
+                    fwrite($fp, $host . '::' . $key . "\n");
230
+                }
231
+                fclose($fp);
232
+                return true;
233
+            }
234
+        } catch (\Exception $e) {
235
+        }
236
+        return false;
237
+    }
238
+
239
+    /**
240
+     * @return array
241
+     */
242
+    protected function readHostKeys() {
243
+        try {
244
+            $keyPath = $this->hostKeysPath();
245
+            if (file_exists($keyPath)) {
246
+                $hosts = array();
247
+                $keys = array();
248
+                $lines = file($keyPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
249
+                if ($lines) {
250
+                    foreach ($lines as $line) {
251
+                        $hostKeyArray = explode("::", $line, 2);
252
+                        if (count($hostKeyArray) == 2) {
253
+                            $hosts[] = $hostKeyArray[0];
254
+                            $keys[] = $hostKeyArray[1];
255
+                        }
256
+                    }
257
+                    return array_combine($hosts, $keys);
258
+                }
259
+            }
260
+        } catch (\Exception $e) {
261
+        }
262
+        return array();
263
+    }
264
+
265
+    /**
266
+     * {@inheritdoc}
267
+     */
268
+    public function mkdir($path) {
269
+        try {
270
+            return $this->getConnection()->mkdir($this->absPath($path));
271
+        } catch (\Exception $e) {
272
+            return false;
273
+        }
274
+    }
275
+
276
+    /**
277
+     * {@inheritdoc}
278
+     */
279
+    public function rmdir($path) {
280
+        try {
281
+            $result = $this->getConnection()->delete($this->absPath($path), true);
282
+            // workaround: stray stat cache entry when deleting empty folders
283
+            // see https://github.com/phpseclib/phpseclib/issues/706
284
+            $this->getConnection()->clearStatCache();
285
+            return $result;
286
+        } catch (\Exception $e) {
287
+            return false;
288
+        }
289
+    }
290
+
291
+    /**
292
+     * {@inheritdoc}
293
+     */
294
+    public function opendir($path) {
295
+        try {
296
+            $list = $this->getConnection()->nlist($this->absPath($path));
297
+            if ($list === false) {
298
+                return false;
299
+            }
300
+
301
+            $id = md5('sftp:' . $path);
302
+            $dirStream = array();
303
+            foreach($list as $file) {
304
+                if ($file != '.' && $file != '..') {
305
+                    $dirStream[] = $file;
306
+                }
307
+            }
308
+            return IteratorDirectory::wrap($dirStream);
309
+        } catch(\Exception $e) {
310
+            return false;
311
+        }
312
+    }
313
+
314
+    /**
315
+     * {@inheritdoc}
316
+     */
317
+    public function filetype($path) {
318
+        try {
319
+            $stat = $this->getConnection()->stat($this->absPath($path));
320
+            if ($stat['type'] == NET_SFTP_TYPE_REGULAR) {
321
+                return 'file';
322
+            }
323
+
324
+            if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
325
+                return 'dir';
326
+            }
327
+        } catch (\Exception $e) {
328
+
329
+        }
330
+        return false;
331
+    }
332
+
333
+    /**
334
+     * {@inheritdoc}
335
+     */
336
+    public function file_exists($path) {
337
+        try {
338
+            return $this->getConnection()->stat($this->absPath($path)) !== false;
339
+        } catch (\Exception $e) {
340
+            return false;
341
+        }
342
+    }
343
+
344
+    /**
345
+     * {@inheritdoc}
346
+     */
347
+    public function unlink($path) {
348
+        try {
349
+            return $this->getConnection()->delete($this->absPath($path), true);
350
+        } catch (\Exception $e) {
351
+            return false;
352
+        }
353
+    }
354
+
355
+    /**
356
+     * {@inheritdoc}
357
+     */
358
+    public function fopen($path, $mode) {
359
+        try {
360
+            $absPath = $this->absPath($path);
361
+            switch($mode) {
362
+                case 'r':
363
+                case 'rb':
364
+                    if ( !$this->file_exists($path)) {
365
+                        return false;
366
+                    }
367
+                case 'w':
368
+                case 'wb':
369
+                case 'a':
370
+                case 'ab':
371
+                case 'r+':
372
+                case 'w+':
373
+                case 'wb+':
374
+                case 'a+':
375
+                case 'x':
376
+                case 'x+':
377
+                case 'c':
378
+                case 'c+':
379
+                    $context = stream_context_create(array('sftp' => array('session' => $this->getConnection())));
380
+                    $handle = fopen($this->constructUrl($path), $mode, false, $context);
381
+                    return RetryWrapper::wrap($handle);
382
+            }
383
+        } catch (\Exception $e) {
384
+        }
385
+        return false;
386
+    }
387
+
388
+    /**
389
+     * {@inheritdoc}
390
+     */
391
+    public function touch($path, $mtime=null) {
392
+        try {
393
+            if (!is_null($mtime)) {
394
+                return false;
395
+            }
396
+            if (!$this->file_exists($path)) {
397
+                $this->getConnection()->put($this->absPath($path), '');
398
+            } else {
399
+                return false;
400
+            }
401
+        } catch (\Exception $e) {
402
+            return false;
403
+        }
404
+        return true;
405
+    }
406
+
407
+    /**
408
+     * @param string $path
409
+     * @param string $target
410
+     * @throws \Exception
411
+     */
412
+    public function getFile($path, $target) {
413
+        $this->getConnection()->get($path, $target);
414
+    }
415
+
416
+    /**
417
+     * @param string $path
418
+     * @param string $target
419
+     * @throws \Exception
420
+     */
421
+    public function uploadFile($path, $target) {
422
+        $this->getConnection()->put($target, $path, NET_SFTP_LOCAL_FILE);
423
+    }
424
+
425
+    /**
426
+     * {@inheritdoc}
427
+     */
428
+    public function rename($source, $target) {
429
+        try {
430
+            if ($this->file_exists($target)) {
431
+                $this->unlink($target);
432
+            }
433
+            return $this->getConnection()->rename(
434
+                $this->absPath($source),
435
+                $this->absPath($target)
436
+            );
437
+        } catch (\Exception $e) {
438
+            return false;
439
+        }
440
+    }
441
+
442
+    /**
443
+     * {@inheritdoc}
444
+     */
445
+    public function stat($path) {
446
+        try {
447
+            $stat = $this->getConnection()->stat($this->absPath($path));
448
+
449
+            $mtime = $stat ? $stat['mtime'] : -1;
450
+            $size = $stat ? $stat['size'] : 0;
451
+
452
+            return array('mtime' => $mtime, 'size' => $size, 'ctime' => -1);
453
+        } catch (\Exception $e) {
454
+            return false;
455
+        }
456
+    }
457
+
458
+    /**
459
+     * @param string $path
460
+     * @return string
461
+     */
462
+    public function constructUrl($path) {
463
+        // Do not pass the password here. We want to use the Net_SFTP object
464
+        // supplied via stream context or fail. We only supply username and
465
+        // hostname because this might show up in logs (they are not used).
466
+        $url = 'sftp://' . urlencode($this->user) . '@' . $this->host . ':' . $this->port . $this->root . $path;
467
+        return $url;
468
+    }
469 469
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -62,11 +62,11 @@  discard block
 block discarded – undo
62 62
 		$input = $host;
63 63
 		if (strpos($host, '://') === false) {
64 64
 			// add a protocol to fix parse_url behavior with ipv6
65
-			$host = 'http://' . $host;
65
+			$host = 'http://'.$host;
66 66
 		}
67 67
 
68 68
 		$parsed = parse_url($host);
69
-		if(is_array($parsed) && isset($parsed['port'])) {
69
+		if (is_array($parsed) && isset($parsed['port'])) {
70 70
 			return [$parsed['host'], $parsed['port']];
71 71
 		} else if (is_array($parsed)) {
72 72
 			return [$parsed['host'], 22];
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 		// Register sftp://
83 83
 		Stream::register();
84 84
 
85
-		$parsedHost =  $this->splitHost($params['host']);
85
+		$parsedHost = $this->splitHost($params['host']);
86 86
 
87 87
 		$this->host = $parsedHost[0];
88 88
 		$this->port = $parsedHost[1];
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 			= isset($params['root']) ? $this->cleanPath($params['root']) : '/';
105 105
 
106 106
 		if ($this->root[0] != '/') {
107
-			 $this->root = '/' . $this->root;
107
+			 $this->root = '/'.$this->root;
108 108
 		}
109 109
 
110 110
 		if (substr($this->root, -1, 1) != '/') {
@@ -159,15 +159,15 @@  discard block
 block discarded – undo
159 159
 	/**
160 160
 	 * {@inheritdoc}
161 161
 	 */
162
-	public function getId(){
163
-		$id = 'sftp::' . $this->user . '@' . $this->host;
162
+	public function getId() {
163
+		$id = 'sftp::'.$this->user.'@'.$this->host;
164 164
 		if ($this->port !== 22) {
165
-			$id .= ':' . $this->port;
165
+			$id .= ':'.$this->port;
166 166
 		}
167 167
 		// note: this will double the root slash,
168 168
 		// we should not change it to keep compatible with
169 169
 		// old storage ids
170
-		$id .= '/' . $this->root;
170
+		$id .= '/'.$this->root;
171 171
 		return $id;
172 172
 	}
173 173
 
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 	 * @return string
198 198
 	 */
199 199
 	private function absPath($path) {
200
-		return $this->root . $this->cleanPath($path);
200
+		return $this->root.$this->cleanPath($path);
201 201
 	}
202 202
 
203 203
 	/**
@@ -207,8 +207,8 @@  discard block
 block discarded – undo
207 207
 		try {
208 208
 			$storage_view = \OCP\Files::getStorage('files_external');
209 209
 			if ($storage_view) {
210
-				return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') .
211
-					$storage_view->getAbsolutePath('') .
210
+				return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').
211
+					$storage_view->getAbsolutePath('').
212 212
 					'ssh_hostKeys';
213 213
 			}
214 214
 		} catch (\Exception $e) {
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 			if ($keyPath && file_exists($keyPath)) {
227 227
 				$fp = fopen($keyPath, 'w');
228 228
 				foreach ($keys as $host => $key) {
229
-					fwrite($fp, $host . '::' . $key . "\n");
229
+					fwrite($fp, $host.'::'.$key."\n");
230 230
 				}
231 231
 				fclose($fp);
232 232
 				return true;
@@ -298,15 +298,15 @@  discard block
 block discarded – undo
298 298
 				return false;
299 299
 			}
300 300
 
301
-			$id = md5('sftp:' . $path);
301
+			$id = md5('sftp:'.$path);
302 302
 			$dirStream = array();
303
-			foreach($list as $file) {
303
+			foreach ($list as $file) {
304 304
 				if ($file != '.' && $file != '..') {
305 305
 					$dirStream[] = $file;
306 306
 				}
307 307
 			}
308 308
 			return IteratorDirectory::wrap($dirStream);
309
-		} catch(\Exception $e) {
309
+		} catch (\Exception $e) {
310 310
 			return false;
311 311
 		}
312 312
 	}
@@ -358,10 +358,10 @@  discard block
 block discarded – undo
358 358
 	public function fopen($path, $mode) {
359 359
 		try {
360 360
 			$absPath = $this->absPath($path);
361
-			switch($mode) {
361
+			switch ($mode) {
362 362
 				case 'r':
363 363
 				case 'rb':
364
-					if ( !$this->file_exists($path)) {
364
+					if (!$this->file_exists($path)) {
365 365
 						return false;
366 366
 					}
367 367
 				case 'w':
@@ -388,7 +388,7 @@  discard block
 block discarded – undo
388 388
 	/**
389 389
 	 * {@inheritdoc}
390 390
 	 */
391
-	public function touch($path, $mtime=null) {
391
+	public function touch($path, $mtime = null) {
392 392
 		try {
393 393
 			if (!is_null($mtime)) {
394 394
 				return false;
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 		// Do not pass the password here. We want to use the Net_SFTP object
464 464
 		// supplied via stream context or fail. We only supply username and
465 465
 		// hostname because this might show up in logs (they are not used).
466
-		$url = 'sftp://' . urlencode($this->user) . '@' . $this->host . ':' . $this->port . $this->root . $path;
466
+		$url = 'sftp://'.urlencode($this->user).'@'.$this->host.':'.$this->port.$this->root.$path;
467 467
 		return $url;
468 468
 	}
469 469
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Migration.php 3 patches
Doc Comments   -1 removed lines patch added patch discarded remove patch
@@ -130,7 +130,6 @@
 block discarded – undo
130 130
 	/**
131 131
 	 * Get $n re-shares from the database
132 132
 	 *
133
-	 * @param int $n The max number of shares to fetch
134 133
 	 * @return \Doctrine\DBAL\Driver\Statement
135 134
 	 */
136 135
 	private function getReShares() {
Please login to merge, or discard this patch.
Indentation   +247 added lines, -247 removed lines patch added patch discarded remove patch
@@ -39,252 +39,252 @@
 block discarded – undo
39 39
  */
40 40
 class Migration {
41 41
 
42
-	/** @var IDBConnection */
43
-	private $connection;
44
-
45
-	/** @var  IConfig */
46
-	private $config;
47
-
48
-	/** @var  ICache with all shares we already saw */
49
-	private $shareCache;
50
-
51
-	/** @var string */
52
-	private $table = 'share';
53
-
54
-	public function __construct(IDBConnection $connection, IConfig $config) {
55
-		$this->connection = $connection;
56
-		$this->config = $config;
57
-
58
-		// We cache up to 10k share items (~20MB)
59
-		$this->shareCache = new CappedMemoryCache(10000);
60
-	}
61
-
62
-	/**
63
-	 * move all re-shares to the owner in order to have a flat list of shares
64
-	 * upgrade from oC 8.2 to 9.0 with the new sharing
65
-	 */
66
-	public function removeReShares() {
67
-
68
-		$stmt = $this->getReShares();
69
-
70
-		$owners = [];
71
-		while($share = $stmt->fetch()) {
72
-
73
-			$this->shareCache[$share['id']] = $share;
74
-
75
-			$owners[$share['id']] = [
76
-					'owner' => $this->findOwner($share),
77
-					'initiator' => $share['uid_owner'],
78
-					'type' => $share['share_type'],
79
-			];
80
-
81
-			if (count($owners) === 1000) {
82
-				$this->updateOwners($owners);
83
-				$owners = [];
84
-			}
85
-		}
86
-
87
-		$stmt->closeCursor();
88
-
89
-		if (count($owners)) {
90
-			$this->updateOwners($owners);
91
-		}
92
-	}
93
-
94
-	/**
95
-	 * update all owner information so that all shares have an owner
96
-	 * and an initiator for the upgrade from oC 8.2 to 9.0 with the new sharing
97
-	 */
98
-	public function updateInitiatorInfo() {
99
-		while (true) {
100
-			$shares = $this->getMissingInitiator(1000);
101
-
102
-			if (empty($shares)) {
103
-				break;
104
-			}
105
-
106
-			$owners = [];
107
-			foreach ($shares as $share) {
108
-				$owners[$share['id']] = [
109
-					'owner' => $share['uid_owner'],
110
-					'initiator' => $share['uid_owner'],
111
-					'type' => $share['share_type'],
112
-				];
113
-			}
114
-			$this->updateOwners($owners);
115
-		}
116
-	}
117
-
118
-	/**
119
-	 * this was dropped for Nextcloud 11 in favour of share by mail
120
-	 */
121
-	public function removeSendMailOption() {
122
-		$this->config->deleteAppValue('core', 'shareapi_allow_mail_notification');
123
-		$this->config->deleteAppValue('core', 'shareapi_allow_public_notification');
124
-	}
125
-
126
-	/**
127
-	 * find the owner of a re-shared file/folder
128
-	 *
129
-	 * @param array $share
130
-	 * @return array
131
-	 */
132
-	private function findOwner($share) {
133
-		$currentShare = $share;
134
-		while(!is_null($currentShare['parent'])) {
135
-			if (isset($this->shareCache[$currentShare['parent']])) {
136
-				$currentShare = $this->shareCache[$currentShare['parent']];
137
-			} else {
138
-				$currentShare = $this->getShare((int)$currentShare['parent']);
139
-				$this->shareCache[$currentShare['id']] = $currentShare;
140
-			}
141
-		}
142
-
143
-		return $currentShare['uid_owner'];
144
-	}
145
-
146
-	/**
147
-	 * Get $n re-shares from the database
148
-	 *
149
-	 * @param int $n The max number of shares to fetch
150
-	 * @return \Doctrine\DBAL\Driver\Statement
151
-	 */
152
-	private function getReShares() {
153
-		$query = $this->connection->getQueryBuilder();
154
-		$query->select(['id', 'parent', 'uid_owner', 'share_type'])
155
-			->from($this->table)
156
-			->where($query->expr()->in(
157
-				'share_type',
158
-				$query->createNamedParameter(
159
-					[
160
-						\OCP\Share::SHARE_TYPE_USER,
161
-						\OCP\Share::SHARE_TYPE_GROUP,
162
-						\OCP\Share::SHARE_TYPE_LINK,
163
-						\OCP\Share::SHARE_TYPE_REMOTE,
164
-					],
165
-					Connection::PARAM_INT_ARRAY
166
-				)
167
-			))
168
-			->andWhere($query->expr()->in(
169
-				'item_type',
170
-				$query->createNamedParameter(
171
-					['file', 'folder'],
172
-					Connection::PARAM_STR_ARRAY
173
-				)
174
-			))
175
-			->andWhere($query->expr()->isNotNull('parent'))
176
-			->orderBy('id', 'asc');
177
-		return $query->execute();
178
-
179
-
180
-		$shares = $result->fetchAll();
181
-		$result->closeCursor();
182
-
183
-		$ordered = [];
184
-		foreach ($shares as $share) {
185
-			$ordered[(int)$share['id']] = $share;
186
-		}
187
-
188
-		return $ordered;
189
-	}
190
-
191
-	/**
192
-	 * Get $n re-shares from the database
193
-	 *
194
-	 * @param int $n The max number of shares to fetch
195
-	 * @return array
196
-	 */
197
-	private function getMissingInitiator($n = 1000) {
198
-		$query = $this->connection->getQueryBuilder();
199
-		$query->select(['id', 'uid_owner', 'share_type'])
200
-			->from($this->table)
201
-			->where($query->expr()->in(
202
-				'share_type',
203
-				$query->createNamedParameter(
204
-					[
205
-						\OCP\Share::SHARE_TYPE_USER,
206
-						\OCP\Share::SHARE_TYPE_GROUP,
207
-						\OCP\Share::SHARE_TYPE_LINK,
208
-						\OCP\Share::SHARE_TYPE_REMOTE,
209
-					],
210
-					Connection::PARAM_INT_ARRAY
211
-				)
212
-			))
213
-			->andWhere($query->expr()->in(
214
-				'item_type',
215
-				$query->createNamedParameter(
216
-					['file', 'folder'],
217
-					Connection::PARAM_STR_ARRAY
218
-				)
219
-			))
220
-			->andWhere($query->expr()->isNull('uid_initiator'))
221
-			->orderBy('id', 'asc')
222
-			->setMaxResults($n);
223
-		$result = $query->execute();
224
-		$shares = $result->fetchAll();
225
-		$result->closeCursor();
226
-
227
-		$ordered = [];
228
-		foreach ($shares as $share) {
229
-			$ordered[(int)$share['id']] = $share;
230
-		}
231
-
232
-		return $ordered;
233
-	}
234
-
235
-	/**
236
-	 * get a specific share
237
-	 *
238
-	 * @param int $id
239
-	 * @return array
240
-	 */
241
-	private function getShare($id) {
242
-		$query = $this->connection->getQueryBuilder();
243
-		$query->select(['id', 'parent', 'uid_owner'])
244
-			->from($this->table)
245
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)));
246
-		$result = $query->execute();
247
-		$share = $result->fetchAll();
248
-		$result->closeCursor();
249
-
250
-		return $share[0];
251
-	}
252
-
253
-	/**
254
-	 * update database with the new owners
255
-	 *
256
-	 * @param array $owners
257
-	 * @throws \Exception
258
-	 */
259
-	private function updateOwners($owners) {
260
-
261
-		$this->connection->beginTransaction();
262
-
263
-		try {
264
-
265
-			foreach ($owners as $id => $owner) {
266
-				$query = $this->connection->getQueryBuilder();
267
-				$query->update($this->table)
268
-					->set('uid_owner', $query->createNamedParameter($owner['owner']))
269
-					->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
270
-
271
-
272
-				if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
273
-					$query->set('parent', $query->createNamedParameter(null));
274
-				}
275
-
276
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($id)));
277
-
278
-				$query->execute();
279
-			}
280
-
281
-			$this->connection->commit();
282
-
283
-		} catch (\Exception $e) {
284
-			$this->connection->rollBack();
285
-			throw $e;
286
-		}
287
-
288
-	}
42
+    /** @var IDBConnection */
43
+    private $connection;
44
+
45
+    /** @var  IConfig */
46
+    private $config;
47
+
48
+    /** @var  ICache with all shares we already saw */
49
+    private $shareCache;
50
+
51
+    /** @var string */
52
+    private $table = 'share';
53
+
54
+    public function __construct(IDBConnection $connection, IConfig $config) {
55
+        $this->connection = $connection;
56
+        $this->config = $config;
57
+
58
+        // We cache up to 10k share items (~20MB)
59
+        $this->shareCache = new CappedMemoryCache(10000);
60
+    }
61
+
62
+    /**
63
+     * move all re-shares to the owner in order to have a flat list of shares
64
+     * upgrade from oC 8.2 to 9.0 with the new sharing
65
+     */
66
+    public function removeReShares() {
67
+
68
+        $stmt = $this->getReShares();
69
+
70
+        $owners = [];
71
+        while($share = $stmt->fetch()) {
72
+
73
+            $this->shareCache[$share['id']] = $share;
74
+
75
+            $owners[$share['id']] = [
76
+                    'owner' => $this->findOwner($share),
77
+                    'initiator' => $share['uid_owner'],
78
+                    'type' => $share['share_type'],
79
+            ];
80
+
81
+            if (count($owners) === 1000) {
82
+                $this->updateOwners($owners);
83
+                $owners = [];
84
+            }
85
+        }
86
+
87
+        $stmt->closeCursor();
88
+
89
+        if (count($owners)) {
90
+            $this->updateOwners($owners);
91
+        }
92
+    }
93
+
94
+    /**
95
+     * update all owner information so that all shares have an owner
96
+     * and an initiator for the upgrade from oC 8.2 to 9.0 with the new sharing
97
+     */
98
+    public function updateInitiatorInfo() {
99
+        while (true) {
100
+            $shares = $this->getMissingInitiator(1000);
101
+
102
+            if (empty($shares)) {
103
+                break;
104
+            }
105
+
106
+            $owners = [];
107
+            foreach ($shares as $share) {
108
+                $owners[$share['id']] = [
109
+                    'owner' => $share['uid_owner'],
110
+                    'initiator' => $share['uid_owner'],
111
+                    'type' => $share['share_type'],
112
+                ];
113
+            }
114
+            $this->updateOwners($owners);
115
+        }
116
+    }
117
+
118
+    /**
119
+     * this was dropped for Nextcloud 11 in favour of share by mail
120
+     */
121
+    public function removeSendMailOption() {
122
+        $this->config->deleteAppValue('core', 'shareapi_allow_mail_notification');
123
+        $this->config->deleteAppValue('core', 'shareapi_allow_public_notification');
124
+    }
125
+
126
+    /**
127
+     * find the owner of a re-shared file/folder
128
+     *
129
+     * @param array $share
130
+     * @return array
131
+     */
132
+    private function findOwner($share) {
133
+        $currentShare = $share;
134
+        while(!is_null($currentShare['parent'])) {
135
+            if (isset($this->shareCache[$currentShare['parent']])) {
136
+                $currentShare = $this->shareCache[$currentShare['parent']];
137
+            } else {
138
+                $currentShare = $this->getShare((int)$currentShare['parent']);
139
+                $this->shareCache[$currentShare['id']] = $currentShare;
140
+            }
141
+        }
142
+
143
+        return $currentShare['uid_owner'];
144
+    }
145
+
146
+    /**
147
+     * Get $n re-shares from the database
148
+     *
149
+     * @param int $n The max number of shares to fetch
150
+     * @return \Doctrine\DBAL\Driver\Statement
151
+     */
152
+    private function getReShares() {
153
+        $query = $this->connection->getQueryBuilder();
154
+        $query->select(['id', 'parent', 'uid_owner', 'share_type'])
155
+            ->from($this->table)
156
+            ->where($query->expr()->in(
157
+                'share_type',
158
+                $query->createNamedParameter(
159
+                    [
160
+                        \OCP\Share::SHARE_TYPE_USER,
161
+                        \OCP\Share::SHARE_TYPE_GROUP,
162
+                        \OCP\Share::SHARE_TYPE_LINK,
163
+                        \OCP\Share::SHARE_TYPE_REMOTE,
164
+                    ],
165
+                    Connection::PARAM_INT_ARRAY
166
+                )
167
+            ))
168
+            ->andWhere($query->expr()->in(
169
+                'item_type',
170
+                $query->createNamedParameter(
171
+                    ['file', 'folder'],
172
+                    Connection::PARAM_STR_ARRAY
173
+                )
174
+            ))
175
+            ->andWhere($query->expr()->isNotNull('parent'))
176
+            ->orderBy('id', 'asc');
177
+        return $query->execute();
178
+
179
+
180
+        $shares = $result->fetchAll();
181
+        $result->closeCursor();
182
+
183
+        $ordered = [];
184
+        foreach ($shares as $share) {
185
+            $ordered[(int)$share['id']] = $share;
186
+        }
187
+
188
+        return $ordered;
189
+    }
190
+
191
+    /**
192
+     * Get $n re-shares from the database
193
+     *
194
+     * @param int $n The max number of shares to fetch
195
+     * @return array
196
+     */
197
+    private function getMissingInitiator($n = 1000) {
198
+        $query = $this->connection->getQueryBuilder();
199
+        $query->select(['id', 'uid_owner', 'share_type'])
200
+            ->from($this->table)
201
+            ->where($query->expr()->in(
202
+                'share_type',
203
+                $query->createNamedParameter(
204
+                    [
205
+                        \OCP\Share::SHARE_TYPE_USER,
206
+                        \OCP\Share::SHARE_TYPE_GROUP,
207
+                        \OCP\Share::SHARE_TYPE_LINK,
208
+                        \OCP\Share::SHARE_TYPE_REMOTE,
209
+                    ],
210
+                    Connection::PARAM_INT_ARRAY
211
+                )
212
+            ))
213
+            ->andWhere($query->expr()->in(
214
+                'item_type',
215
+                $query->createNamedParameter(
216
+                    ['file', 'folder'],
217
+                    Connection::PARAM_STR_ARRAY
218
+                )
219
+            ))
220
+            ->andWhere($query->expr()->isNull('uid_initiator'))
221
+            ->orderBy('id', 'asc')
222
+            ->setMaxResults($n);
223
+        $result = $query->execute();
224
+        $shares = $result->fetchAll();
225
+        $result->closeCursor();
226
+
227
+        $ordered = [];
228
+        foreach ($shares as $share) {
229
+            $ordered[(int)$share['id']] = $share;
230
+        }
231
+
232
+        return $ordered;
233
+    }
234
+
235
+    /**
236
+     * get a specific share
237
+     *
238
+     * @param int $id
239
+     * @return array
240
+     */
241
+    private function getShare($id) {
242
+        $query = $this->connection->getQueryBuilder();
243
+        $query->select(['id', 'parent', 'uid_owner'])
244
+            ->from($this->table)
245
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
246
+        $result = $query->execute();
247
+        $share = $result->fetchAll();
248
+        $result->closeCursor();
249
+
250
+        return $share[0];
251
+    }
252
+
253
+    /**
254
+     * update database with the new owners
255
+     *
256
+     * @param array $owners
257
+     * @throws \Exception
258
+     */
259
+    private function updateOwners($owners) {
260
+
261
+        $this->connection->beginTransaction();
262
+
263
+        try {
264
+
265
+            foreach ($owners as $id => $owner) {
266
+                $query = $this->connection->getQueryBuilder();
267
+                $query->update($this->table)
268
+                    ->set('uid_owner', $query->createNamedParameter($owner['owner']))
269
+                    ->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
270
+
271
+
272
+                if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
273
+                    $query->set('parent', $query->createNamedParameter(null));
274
+                }
275
+
276
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($id)));
277
+
278
+                $query->execute();
279
+            }
280
+
281
+            $this->connection->commit();
282
+
283
+        } catch (\Exception $e) {
284
+            $this->connection->rollBack();
285
+            throw $e;
286
+        }
287
+
288
+    }
289 289
 
290 290
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		$stmt = $this->getReShares();
69 69
 
70 70
 		$owners = [];
71
-		while($share = $stmt->fetch()) {
71
+		while ($share = $stmt->fetch()) {
72 72
 
73 73
 			$this->shareCache[$share['id']] = $share;
74 74
 
@@ -131,11 +131,11 @@  discard block
 block discarded – undo
131 131
 	 */
132 132
 	private function findOwner($share) {
133 133
 		$currentShare = $share;
134
-		while(!is_null($currentShare['parent'])) {
134
+		while (!is_null($currentShare['parent'])) {
135 135
 			if (isset($this->shareCache[$currentShare['parent']])) {
136 136
 				$currentShare = $this->shareCache[$currentShare['parent']];
137 137
 			} else {
138
-				$currentShare = $this->getShare((int)$currentShare['parent']);
138
+				$currentShare = $this->getShare((int) $currentShare['parent']);
139 139
 				$this->shareCache[$currentShare['id']] = $currentShare;
140 140
 			}
141 141
 		}
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 
183 183
 		$ordered = [];
184 184
 		foreach ($shares as $share) {
185
-			$ordered[(int)$share['id']] = $share;
185
+			$ordered[(int) $share['id']] = $share;
186 186
 		}
187 187
 
188 188
 		return $ordered;
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 
227 227
 		$ordered = [];
228 228
 		foreach ($shares as $share) {
229
-			$ordered[(int)$share['id']] = $share;
229
+			$ordered[(int) $share['id']] = $share;
230 230
 		}
231 231
 
232 232
 		return $ordered;
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 					->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
270 270
 
271 271
 
272
-				if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
272
+				if ((int) $owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
273 273
 					$query->set('parent', $query->createNamedParameter(null));
274 274
 				}
275 275
 
Please login to merge, or discard this patch.
apps/files_trashbin/lib/BackgroundJob/ExpireTrash.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -23,7 +23,6 @@
 block discarded – undo
23 23
 
24 24
 namespace OCA\Files_Trashbin\BackgroundJob;
25 25
 
26
-use OCP\IConfig;
27 26
 use OCP\IUser;
28 27
 use OCP\IUserManager;
29 28
 use OCA\Files_Trashbin\AppInfo\Application;
Please login to merge, or discard this patch.
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -34,76 +34,76 @@
 block discarded – undo
34 34
 
35 35
 class ExpireTrash extends \OC\BackgroundJob\TimedJob {
36 36
 
37
-	/**
38
-	 * @var Expiration
39
-	 */
40
-	private $expiration;
37
+    /**
38
+     * @var Expiration
39
+     */
40
+    private $expiration;
41 41
 	
42
-	/**
43
-	 * @var IUserManager
44
-	 */
45
-	private $userManager;
42
+    /**
43
+     * @var IUserManager
44
+     */
45
+    private $userManager;
46 46
 
47
-	/**
48
-	 * @param IUserManager|null $userManager
49
-	 * @param Expiration|null $expiration
50
-	 */
51
-	public function __construct(IUserManager $userManager = null,
52
-								Expiration $expiration = null) {
53
-		// Run once per 30 minutes
54
-		$this->setInterval(60 * 30);
47
+    /**
48
+     * @param IUserManager|null $userManager
49
+     * @param Expiration|null $expiration
50
+     */
51
+    public function __construct(IUserManager $userManager = null,
52
+                                Expiration $expiration = null) {
53
+        // Run once per 30 minutes
54
+        $this->setInterval(60 * 30);
55 55
 
56
-		if (is_null($expiration) || is_null($userManager)) {
57
-			$this->fixDIForJobs();
58
-		} else {
59
-			$this->userManager = $userManager;
60
-			$this->expiration = $expiration;
61
-		}
62
-	}
56
+        if (is_null($expiration) || is_null($userManager)) {
57
+            $this->fixDIForJobs();
58
+        } else {
59
+            $this->userManager = $userManager;
60
+            $this->expiration = $expiration;
61
+        }
62
+    }
63 63
 
64
-	protected function fixDIForJobs() {
65
-		$application = new Application();
66
-		$this->userManager = \OC::$server->getUserManager();
67
-		$this->expiration = $application->getContainer()->query('Expiration');
68
-	}
64
+    protected function fixDIForJobs() {
65
+        $application = new Application();
66
+        $this->userManager = \OC::$server->getUserManager();
67
+        $this->expiration = $application->getContainer()->query('Expiration');
68
+    }
69 69
 
70
-	/**
71
-	 * @param $argument
72
-	 * @throws \Exception
73
-	 */
74
-	protected function run($argument) {
75
-		$maxAge = $this->expiration->getMaxAgeAsTimestamp();
76
-		if (!$maxAge) {
77
-			return;
78
-		}
70
+    /**
71
+     * @param $argument
72
+     * @throws \Exception
73
+     */
74
+    protected function run($argument) {
75
+        $maxAge = $this->expiration->getMaxAgeAsTimestamp();
76
+        if (!$maxAge) {
77
+            return;
78
+        }
79 79
 
80
-		$this->userManager->callForSeenUsers(function(IUser $user) {
81
-			$uid = $user->getUID();
82
-			if (!$this->setupFS($uid)) {
83
-				return;
84
-			}
85
-			$dirContent = Helper::getTrashFiles('/', $uid, 'mtime');
86
-			Trashbin::deleteExpiredFiles($dirContent, $uid);
87
-		});
80
+        $this->userManager->callForSeenUsers(function(IUser $user) {
81
+            $uid = $user->getUID();
82
+            if (!$this->setupFS($uid)) {
83
+                return;
84
+            }
85
+            $dirContent = Helper::getTrashFiles('/', $uid, 'mtime');
86
+            Trashbin::deleteExpiredFiles($dirContent, $uid);
87
+        });
88 88
 		
89
-		\OC_Util::tearDownFS();
90
-	}
89
+        \OC_Util::tearDownFS();
90
+    }
91 91
 
92
-	/**
93
-	 * Act on behalf on trash item owner
94
-	 * @param string $user
95
-	 * @return boolean
96
-	 */
97
-	protected function setupFS($user) {
98
-		\OC_Util::tearDownFS();
99
-		\OC_Util::setupFS($user);
92
+    /**
93
+     * Act on behalf on trash item owner
94
+     * @param string $user
95
+     * @return boolean
96
+     */
97
+    protected function setupFS($user) {
98
+        \OC_Util::tearDownFS();
99
+        \OC_Util::setupFS($user);
100 100
 
101
-		// Check if this user has a trashbin directory
102
-		$view = new \OC\Files\View('/' . $user);
103
-		if (!$view->is_dir('/files_trashbin/files')) {
104
-			return false;
105
-		}
101
+        // Check if this user has a trashbin directory
102
+        $view = new \OC\Files\View('/' . $user);
103
+        if (!$view->is_dir('/files_trashbin/files')) {
104
+            return false;
105
+        }
106 106
 
107
-		return true;
108
-	}
107
+        return true;
108
+    }
109 109
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@
 block discarded – undo
117 117
 		\OC_Util::setupFS($user);
118 118
 
119 119
 		// Check if this user has a trashbin directory
120
-		$view = new \OC\Files\View('/' . $user);
120
+		$view = new \OC\Files\View('/'.$user);
121 121
 		if (!$view->is_dir('/files_trashbin/files')) {
122 122
 			return false;
123 123
 		}
Please login to merge, or discard this patch.
apps/files_trashbin/lib/Storage.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@
 block discarded – undo
110 110
 	 * check if it is a file located in data/user/files only files in the
111 111
 	 * 'files' directory should be moved to the trash
112 112
 	 *
113
-	 * @param $path
113
+	 * @param string $path
114 114
 	 * @return bool
115 115
 	 */
116 116
 	protected function shouldMoveToTrash($path){
Please login to merge, or discard this patch.
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -32,228 +32,228 @@
 block discarded – undo
32 32
 
33 33
 class Storage extends Wrapper {
34 34
 
35
-	private $mountPoint;
36
-	// remember already deleted files to avoid infinite loops if the trash bin
37
-	// move files across storages
38
-	private $deletedFiles = array();
35
+    private $mountPoint;
36
+    // remember already deleted files to avoid infinite loops if the trash bin
37
+    // move files across storages
38
+    private $deletedFiles = array();
39 39
 
40
-	/**
41
-	 * Disable trash logic
42
-	 *
43
-	 * @var bool
44
-	 */
45
-	private static $disableTrash = false;
40
+    /**
41
+     * Disable trash logic
42
+     *
43
+     * @var bool
44
+     */
45
+    private static $disableTrash = false;
46 46
 
47
-	/**
48
-	 * remember which file/folder was moved out of s shared folder
49
-	 * in this case we want to add a copy to the owners trash bin
50
-	 *
51
-	 * @var array
52
-	 */
53
-	private static $moveOutOfSharedFolder = [];
47
+    /**
48
+     * remember which file/folder was moved out of s shared folder
49
+     * in this case we want to add a copy to the owners trash bin
50
+     *
51
+     * @var array
52
+     */
53
+    private static $moveOutOfSharedFolder = [];
54 54
 
55
-	/** @var  IUserManager */
56
-	private $userManager;
55
+    /** @var  IUserManager */
56
+    private $userManager;
57 57
 
58
-	/**
59
-	 * Storage constructor.
60
-	 *
61
-	 * @param array $parameters
62
-	 * @param IUserManager|null $userManager
63
-	 */
64
-	public function __construct($parameters, IUserManager $userManager = null) {
65
-		$this->mountPoint = $parameters['mountPoint'];
66
-		$this->userManager = $userManager;
67
-		parent::__construct($parameters);
68
-	}
58
+    /**
59
+     * Storage constructor.
60
+     *
61
+     * @param array $parameters
62
+     * @param IUserManager|null $userManager
63
+     */
64
+    public function __construct($parameters, IUserManager $userManager = null) {
65
+        $this->mountPoint = $parameters['mountPoint'];
66
+        $this->userManager = $userManager;
67
+        parent::__construct($parameters);
68
+    }
69 69
 
70
-	/**
71
-	 * @internal
72
-	 */
73
-	public static function preRenameHook($params) {
74
-		// in cross-storage cases, a rename is a copy + unlink,
75
-		// that last unlink must not go to trash, only exception:
76
-		// if the file was moved from a shared storage to a local folder,
77
-		// in this case the owner should get a copy in his trash bin so that
78
-		// they can restore the files again
70
+    /**
71
+     * @internal
72
+     */
73
+    public static function preRenameHook($params) {
74
+        // in cross-storage cases, a rename is a copy + unlink,
75
+        // that last unlink must not go to trash, only exception:
76
+        // if the file was moved from a shared storage to a local folder,
77
+        // in this case the owner should get a copy in his trash bin so that
78
+        // they can restore the files again
79 79
 
80
-		$oldPath = $params['oldpath'];
81
-		$newPath = dirname($params['newpath']);
82
-		$currentUser = \OC::$server->getUserSession()->getUser();
80
+        $oldPath = $params['oldpath'];
81
+        $newPath = dirname($params['newpath']);
82
+        $currentUser = \OC::$server->getUserSession()->getUser();
83 83
 
84
-		$fileMovedOutOfSharedFolder = false;
84
+        $fileMovedOutOfSharedFolder = false;
85 85
 
86
-		try {
87
-			if ($currentUser) {
88
-				$currentUserId = $currentUser->getUID();
86
+        try {
87
+            if ($currentUser) {
88
+                $currentUserId = $currentUser->getUID();
89 89
 
90
-				$view = new View($currentUserId . '/files');
91
-				$fileInfo = $view->getFileInfo($oldPath);
92
-				if ($fileInfo) {
93
-					$sourceStorage = $fileInfo->getStorage();
94
-					$sourceOwner = $view->getOwner($oldPath);
95
-					$targetOwner = $view->getOwner($newPath);
90
+                $view = new View($currentUserId . '/files');
91
+                $fileInfo = $view->getFileInfo($oldPath);
92
+                if ($fileInfo) {
93
+                    $sourceStorage = $fileInfo->getStorage();
94
+                    $sourceOwner = $view->getOwner($oldPath);
95
+                    $targetOwner = $view->getOwner($newPath);
96 96
 
97
-					if ($sourceOwner !== $targetOwner
98
-						&& $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
99
-					) {
100
-						$fileMovedOutOfSharedFolder = true;
101
-					}
102
-				}
103
-			}
104
-		} catch (\Exception $e) {
105
-			// do nothing, in this case we just disable the trashbin and continue
106
-			$logger = \OC::$server->getLogger();
107
-			$logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: ' . $e->getMessage());
108
-		}
97
+                    if ($sourceOwner !== $targetOwner
98
+                        && $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
99
+                    ) {
100
+                        $fileMovedOutOfSharedFolder = true;
101
+                    }
102
+                }
103
+            }
104
+        } catch (\Exception $e) {
105
+            // do nothing, in this case we just disable the trashbin and continue
106
+            $logger = \OC::$server->getLogger();
107
+            $logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: ' . $e->getMessage());
108
+        }
109 109
 
110
-		if($fileMovedOutOfSharedFolder) {
111
-			self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
112
-		} else {
113
-			self::$disableTrash = true;
114
-		}
110
+        if($fileMovedOutOfSharedFolder) {
111
+            self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
112
+        } else {
113
+            self::$disableTrash = true;
114
+        }
115 115
 
116
-	}
116
+    }
117 117
 
118
-	/**
119
-	 * @internal
120
-	 */
121
-	public static function postRenameHook($params) {
122
-		self::$disableTrash = false;
123
-	}
118
+    /**
119
+     * @internal
120
+     */
121
+    public static function postRenameHook($params) {
122
+        self::$disableTrash = false;
123
+    }
124 124
 
125
-	/**
126
-	 * Rename path1 to path2 by calling the wrapped storage.
127
-	 *
128
-	 * @param string $path1 first path
129
-	 * @param string $path2 second path
130
-	 * @return bool
131
-	 */
132
-	public function rename($path1, $path2) {
133
-		$result = $this->storage->rename($path1, $path2);
134
-		if ($result === false) {
135
-			// when rename failed, the post_rename hook isn't triggered,
136
-			// but we still want to reenable the trash logic
137
-			self::$disableTrash = false;
138
-		}
139
-		return $result;
140
-	}
125
+    /**
126
+     * Rename path1 to path2 by calling the wrapped storage.
127
+     *
128
+     * @param string $path1 first path
129
+     * @param string $path2 second path
130
+     * @return bool
131
+     */
132
+    public function rename($path1, $path2) {
133
+        $result = $this->storage->rename($path1, $path2);
134
+        if ($result === false) {
135
+            // when rename failed, the post_rename hook isn't triggered,
136
+            // but we still want to reenable the trash logic
137
+            self::$disableTrash = false;
138
+        }
139
+        return $result;
140
+    }
141 141
 
142
-	/**
143
-	 * Deletes the given file by moving it into the trashbin.
144
-	 *
145
-	 * @param string $path path of file or folder to delete
146
-	 *
147
-	 * @return bool true if the operation succeeded, false otherwise
148
-	 */
149
-	public function unlink($path) {
150
-		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
151
-			$result = $this->doDelete($path, 'unlink', true);
152
-			unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
153
-		} else {
154
-			$result = $this->doDelete($path, 'unlink');
155
-		}
142
+    /**
143
+     * Deletes the given file by moving it into the trashbin.
144
+     *
145
+     * @param string $path path of file or folder to delete
146
+     *
147
+     * @return bool true if the operation succeeded, false otherwise
148
+     */
149
+    public function unlink($path) {
150
+        if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
151
+            $result = $this->doDelete($path, 'unlink', true);
152
+            unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
153
+        } else {
154
+            $result = $this->doDelete($path, 'unlink');
155
+        }
156 156
 
157
-		return $result;
158
-	}
157
+        return $result;
158
+    }
159 159
 
160
-	/**
161
-	 * Deletes the given folder by moving it into the trashbin.
162
-	 *
163
-	 * @param string $path path of folder to delete
164
-	 *
165
-	 * @return bool true if the operation succeeded, false otherwise
166
-	 */
167
-	public function rmdir($path) {
168
-		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
169
-			$result = $this->doDelete($path, 'rmdir', true);
170
-			unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
171
-		} else {
172
-			$result = $this->doDelete($path, 'rmdir');
173
-		}
160
+    /**
161
+     * Deletes the given folder by moving it into the trashbin.
162
+     *
163
+     * @param string $path path of folder to delete
164
+     *
165
+     * @return bool true if the operation succeeded, false otherwise
166
+     */
167
+    public function rmdir($path) {
168
+        if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
169
+            $result = $this->doDelete($path, 'rmdir', true);
170
+            unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
171
+        } else {
172
+            $result = $this->doDelete($path, 'rmdir');
173
+        }
174 174
 
175
-		return $result;
176
-	}
175
+        return $result;
176
+    }
177 177
 
178
-	/**
179
-	 * check if it is a file located in data/user/files only files in the
180
-	 * 'files' directory should be moved to the trash
181
-	 *
182
-	 * @param $path
183
-	 * @return bool
184
-	 */
185
-	protected function shouldMoveToTrash($path){
186
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
187
-		$parts = explode('/', $normalized);
188
-		if (count($parts) < 4) {
189
-			return false;
190
-		}
178
+    /**
179
+     * check if it is a file located in data/user/files only files in the
180
+     * 'files' directory should be moved to the trash
181
+     *
182
+     * @param $path
183
+     * @return bool
184
+     */
185
+    protected function shouldMoveToTrash($path){
186
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
187
+        $parts = explode('/', $normalized);
188
+        if (count($parts) < 4) {
189
+            return false;
190
+        }
191 191
 
192
-		if ($this->userManager->userExists($parts[1]) && $parts[2] == 'files') {
193
-			return true;
194
-		}
192
+        if ($this->userManager->userExists($parts[1]) && $parts[2] == 'files') {
193
+            return true;
194
+        }
195 195
 
196
-		return false;
197
-	}
196
+        return false;
197
+    }
198 198
 
199
-	/**
200
-	 * Run the delete operation with the given method
201
-	 *
202
-	 * @param string $path path of file or folder to delete
203
-	 * @param string $method either "unlink" or "rmdir"
204
-	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
205
-	 *
206
-	 * @return bool true if the operation succeeded, false otherwise
207
-	 */
208
-	private function doDelete($path, $method, $ownerOnly = false) {
209
-		if (self::$disableTrash
210
-			|| !\OC_App::isEnabled('files_trashbin')
211
-			|| (pathinfo($path, PATHINFO_EXTENSION) === 'part')
212
-			|| $this->shouldMoveToTrash($path) === false
213
-		) {
214
-			return call_user_func_array([$this->storage, $method], [$path]);
215
-		}
199
+    /**
200
+     * Run the delete operation with the given method
201
+     *
202
+     * @param string $path path of file or folder to delete
203
+     * @param string $method either "unlink" or "rmdir"
204
+     * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
205
+     *
206
+     * @return bool true if the operation succeeded, false otherwise
207
+     */
208
+    private function doDelete($path, $method, $ownerOnly = false) {
209
+        if (self::$disableTrash
210
+            || !\OC_App::isEnabled('files_trashbin')
211
+            || (pathinfo($path, PATHINFO_EXTENSION) === 'part')
212
+            || $this->shouldMoveToTrash($path) === false
213
+        ) {
214
+            return call_user_func_array([$this->storage, $method], [$path]);
215
+        }
216 216
 
217
-		// check permissions before we continue, this is especially important for
218
-		// shared files
219
-		if (!$this->isDeletable($path)) {
220
-			return false;
221
-		}
217
+        // check permissions before we continue, this is especially important for
218
+        // shared files
219
+        if (!$this->isDeletable($path)) {
220
+            return false;
221
+        }
222 222
 
223
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
224
-		$result = true;
225
-		$view = Filesystem::getView();
226
-		if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
227
-			$this->deletedFiles[$normalized] = $normalized;
228
-			if ($filesPath = $view->getRelativePath($normalized)) {
229
-				$filesPath = trim($filesPath, '/');
230
-				$result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
231
-				// in cross-storage cases the file will be copied
232
-				// but not deleted, so we delete it here
233
-				if ($result) {
234
-					call_user_func_array([$this->storage, $method], [$path]);
235
-				}
236
-			} else {
237
-				$result = call_user_func_array([$this->storage, $method], [$path]);
238
-			}
239
-			unset($this->deletedFiles[$normalized]);
240
-		} else if ($this->storage->file_exists($path)) {
241
-			$result = call_user_func_array([$this->storage, $method], [$path]);
242
-		}
223
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
224
+        $result = true;
225
+        $view = Filesystem::getView();
226
+        if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
227
+            $this->deletedFiles[$normalized] = $normalized;
228
+            if ($filesPath = $view->getRelativePath($normalized)) {
229
+                $filesPath = trim($filesPath, '/');
230
+                $result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
231
+                // in cross-storage cases the file will be copied
232
+                // but not deleted, so we delete it here
233
+                if ($result) {
234
+                    call_user_func_array([$this->storage, $method], [$path]);
235
+                }
236
+            } else {
237
+                $result = call_user_func_array([$this->storage, $method], [$path]);
238
+            }
239
+            unset($this->deletedFiles[$normalized]);
240
+        } else if ($this->storage->file_exists($path)) {
241
+            $result = call_user_func_array([$this->storage, $method], [$path]);
242
+        }
243 243
 
244
-		return $result;
245
-	}
244
+        return $result;
245
+    }
246 246
 
247
-	/**
248
-	 * Setup the storate wrapper callback
249
-	 */
250
-	public static function setupStorage() {
251
-		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
252
-			return new \OCA\Files_Trashbin\Storage(
253
-				array('storage' => $storage, 'mountPoint' => $mountPoint),
254
-				\OC::$server->getUserManager()
255
-			);
256
-		}, 1);
257
-	}
247
+    /**
248
+     * Setup the storate wrapper callback
249
+     */
250
+    public static function setupStorage() {
251
+        \OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
252
+            return new \OCA\Files_Trashbin\Storage(
253
+                array('storage' => $storage, 'mountPoint' => $mountPoint),
254
+                \OC::$server->getUserManager()
255
+            );
256
+        }, 1);
257
+    }
258 258
 
259 259
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 			if ($currentUser) {
88 88
 				$currentUserId = $currentUser->getUID();
89 89
 
90
-				$view = new View($currentUserId . '/files');
90
+				$view = new View($currentUserId.'/files');
91 91
 				$fileInfo = $view->getFileInfo($oldPath);
92 92
 				if ($fileInfo) {
93 93
 					$sourceStorage = $fileInfo->getStorage();
@@ -104,11 +104,11 @@  discard block
 block discarded – undo
104 104
 		} catch (\Exception $e) {
105 105
 			// do nothing, in this case we just disable the trashbin and continue
106 106
 			$logger = \OC::$server->getLogger();
107
-			$logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: ' . $e->getMessage());
107
+			$logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: '.$e->getMessage());
108 108
 		}
109 109
 
110
-		if($fileMovedOutOfSharedFolder) {
111
-			self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
110
+		if ($fileMovedOutOfSharedFolder) {
111
+			self::$moveOutOfSharedFolder['/'.$currentUserId.'/files'.$oldPath] = true;
112 112
 		} else {
113 113
 			self::$disableTrash = true;
114 114
 		}
@@ -147,9 +147,9 @@  discard block
 block discarded – undo
147 147
 	 * @return bool true if the operation succeeded, false otherwise
148 148
 	 */
149 149
 	public function unlink($path) {
150
-		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
150
+		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint.$path])) {
151 151
 			$result = $this->doDelete($path, 'unlink', true);
152
-			unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
152
+			unset(self::$moveOutOfSharedFolder[$this->mountPoint.$path]);
153 153
 		} else {
154 154
 			$result = $this->doDelete($path, 'unlink');
155 155
 		}
@@ -165,9 +165,9 @@  discard block
 block discarded – undo
165 165
 	 * @return bool true if the operation succeeded, false otherwise
166 166
 	 */
167 167
 	public function rmdir($path) {
168
-		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
168
+		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint.$path])) {
169 169
 			$result = $this->doDelete($path, 'rmdir', true);
170
-			unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
170
+			unset(self::$moveOutOfSharedFolder[$this->mountPoint.$path]);
171 171
 		} else {
172 172
 			$result = $this->doDelete($path, 'rmdir');
173 173
 		}
@@ -182,8 +182,8 @@  discard block
 block discarded – undo
182 182
 	 * @param $path
183 183
 	 * @return bool
184 184
 	 */
185
-	protected function shouldMoveToTrash($path){
186
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
185
+	protected function shouldMoveToTrash($path) {
186
+		$normalized = Filesystem::normalizePath($this->mountPoint.'/'.$path);
187 187
 		$parts = explode('/', $normalized);
188 188
 		if (count($parts) < 4) {
189 189
 			return false;
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 			return false;
221 221
 		}
222 222
 
223
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
223
+		$normalized = Filesystem::normalizePath($this->mountPoint.'/'.$path, true, false, true);
224 224
 		$result = true;
225 225
 		$view = Filesystem::getView();
226 226
 		if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 	 * Setup the storate wrapper callback
249 249
 	 */
250 250
 	public static function setupStorage() {
251
-		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
251
+		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function($mountPoint, $storage) {
252 252
 			return new \OCA\Files_Trashbin\Storage(
253 253
 				array('storage' => $storage, 'mountPoint' => $mountPoint),
254 254
 				\OC::$server->getUserManager()
Please login to merge, or discard this patch.
apps/files_trashbin/lib/Trashbin.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
 	 * if the size limit for the trash bin is reached, we delete the oldest
672 672
 	 * files in the trash bin until we meet the limit again
673 673
 	 *
674
-	 * @param array $files
674
+	 * @param \OCP\Files\FileInfo[] $files
675 675
 	 * @param string $user
676 676
 	 * @param int $availableSpace available disc space
677 677
 	 * @return int size of deleted files
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 	/**
700 700
 	 * delete files older then max storage time
701 701
 	 *
702
-	 * @param array $files list of files sorted by mtime
702
+	 * @param \OCP\Files\FileInfo[] $files list of files sorted by mtime
703 703
 	 * @param string $user
704 704
 	 * @return integer[] size of deleted files and number of deleted files
705 705
 	 */
Please login to merge, or discard this patch.
Indentation   +933 added lines, -933 removed lines patch added patch discarded remove patch
@@ -47,937 +47,937 @@
 block discarded – undo
47 47
 
48 48
 class Trashbin {
49 49
 
50
-	// unit: percentage; 50% of available disk space/quota
51
-	const DEFAULTMAXSIZE = 50;
52
-
53
-	/**
54
-	 * Whether versions have already be rescanned during this PHP request
55
-	 *
56
-	 * @var bool
57
-	 */
58
-	private static $scannedVersions = false;
59
-
60
-	/**
61
-	 * Ensure we don't need to scan the file during the move to trash
62
-	 * by triggering the scan in the pre-hook
63
-	 *
64
-	 * @param array $params
65
-	 */
66
-	public static function ensureFileScannedHook($params) {
67
-		try {
68
-			self::getUidAndFilename($params['path']);
69
-		} catch (NotFoundException $e) {
70
-			// nothing to scan for non existing files
71
-		}
72
-	}
73
-
74
-	/**
75
-	 * get the UID of the owner of the file and the path to the file relative to
76
-	 * owners files folder
77
-	 *
78
-	 * @param string $filename
79
-	 * @return array
80
-	 * @throws \OC\User\NoUserException
81
-	 */
82
-	public static function getUidAndFilename($filename) {
83
-		$uid = Filesystem::getOwner($filename);
84
-		$userManager = \OC::$server->getUserManager();
85
-		// if the user with the UID doesn't exists, e.g. because the UID points
86
-		// to a remote user with a federated cloud ID we use the current logged-in
87
-		// user. We need a valid local user to move the file to the right trash bin
88
-		if (!$userManager->userExists($uid)) {
89
-			$uid = User::getUser();
90
-		}
91
-		if (!$uid) {
92
-			// no owner, usually because of share link from ext storage
93
-			return [null, null];
94
-		}
95
-		Filesystem::initMountPoints($uid);
96
-		if ($uid != User::getUser()) {
97
-			$info = Filesystem::getFileInfo($filename);
98
-			$ownerView = new View('/' . $uid . '/files');
99
-			try {
100
-				$filename = $ownerView->getPath($info['fileid']);
101
-			} catch (NotFoundException $e) {
102
-				$filename = null;
103
-			}
104
-		}
105
-		return [$uid, $filename];
106
-	}
107
-
108
-	/**
109
-	 * get original location of files for user
110
-	 *
111
-	 * @param string $user
112
-	 * @return array (filename => array (timestamp => original location))
113
-	 */
114
-	public static function getLocations($user) {
115
-		$query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`'
116
-			. ' FROM `*PREFIX*files_trash` WHERE `user`=?');
117
-		$result = $query->execute(array($user));
118
-		$array = array();
119
-		while ($row = $result->fetchRow()) {
120
-			if (isset($array[$row['id']])) {
121
-				$array[$row['id']][$row['timestamp']] = $row['location'];
122
-			} else {
123
-				$array[$row['id']] = array($row['timestamp'] => $row['location']);
124
-			}
125
-		}
126
-		return $array;
127
-	}
128
-
129
-	/**
130
-	 * get original location of file
131
-	 *
132
-	 * @param string $user
133
-	 * @param string $filename
134
-	 * @param string $timestamp
135
-	 * @return string original location
136
-	 */
137
-	public static function getLocation($user, $filename, $timestamp) {
138
-		$query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`'
139
-			. ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
140
-		$result = $query->execute(array($user, $filename, $timestamp))->fetchAll();
141
-		if (isset($result[0]['location'])) {
142
-			return $result[0]['location'];
143
-		} else {
144
-			return false;
145
-		}
146
-	}
147
-
148
-	private static function setUpTrash($user) {
149
-		$view = new View('/' . $user);
150
-		if (!$view->is_dir('files_trashbin')) {
151
-			$view->mkdir('files_trashbin');
152
-		}
153
-		if (!$view->is_dir('files_trashbin/files')) {
154
-			$view->mkdir('files_trashbin/files');
155
-		}
156
-		if (!$view->is_dir('files_trashbin/versions')) {
157
-			$view->mkdir('files_trashbin/versions');
158
-		}
159
-		if (!$view->is_dir('files_trashbin/keys')) {
160
-			$view->mkdir('files_trashbin/keys');
161
-		}
162
-	}
163
-
164
-
165
-	/**
166
-	 * copy file to owners trash
167
-	 *
168
-	 * @param string $sourcePath
169
-	 * @param string $owner
170
-	 * @param string $targetPath
171
-	 * @param $user
172
-	 * @param integer $timestamp
173
-	 */
174
-	private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
175
-		self::setUpTrash($owner);
176
-
177
-		$targetFilename = basename($targetPath);
178
-		$targetLocation = dirname($targetPath);
179
-
180
-		$sourceFilename = basename($sourcePath);
181
-
182
-		$view = new View('/');
183
-
184
-		$target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
185
-		$source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
186
-		self::copy_recursive($source, $target, $view);
187
-
188
-
189
-		if ($view->file_exists($target)) {
190
-			$query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
191
-			$result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user));
192
-			if (!$result) {
193
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR);
194
-			}
195
-		}
196
-	}
197
-
198
-
199
-	/**
200
-	 * move file to the trash bin
201
-	 *
202
-	 * @param string $file_path path to the deleted file/directory relative to the files root directory
203
-	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
204
-	 *
205
-	 * @return bool
206
-	 */
207
-	public static function move2trash($file_path, $ownerOnly = false) {
208
-		// get the user for which the filesystem is setup
209
-		$root = Filesystem::getRoot();
210
-		list(, $user) = explode('/', $root);
211
-		list($owner, $ownerPath) = self::getUidAndFilename($file_path);
212
-
213
-		// if no owner found (ex: ext storage + share link), will use the current user's trashbin then
214
-		if (is_null($owner)) {
215
-			$owner = $user;
216
-			$ownerPath = $file_path;
217
-		}
218
-
219
-		$ownerView = new View('/' . $owner);
220
-		// file has been deleted in between
221
-		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
222
-			return true;
223
-		}
224
-
225
-		self::setUpTrash($user);
226
-		if ($owner !== $user) {
227
-			// also setup for owner
228
-			self::setUpTrash($owner);
229
-		}
230
-
231
-		$path_parts = pathinfo($ownerPath);
232
-
233
-		$filename = $path_parts['basename'];
234
-		$location = $path_parts['dirname'];
235
-		$timestamp = time();
236
-
237
-		// disable proxy to prevent recursive calls
238
-		$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
239
-
240
-		/** @var \OC\Files\Storage\Storage $trashStorage */
241
-		list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath);
242
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
243
-		list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath);
244
-		try {
245
-			$moveSuccessful = true;
246
-			if ($trashStorage->file_exists($trashInternalPath)) {
247
-				$trashStorage->unlink($trashInternalPath);
248
-			}
249
-			$trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
250
-		} catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
251
-			$moveSuccessful = false;
252
-			if ($trashStorage->file_exists($trashInternalPath)) {
253
-				$trashStorage->unlink($trashInternalPath);
254
-			}
255
-			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
256
-		}
257
-
258
-		if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
259
-			$sourceStorage->unlink($sourceInternalPath);
260
-			return false;
261
-		}
262
-
263
-		$trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
264
-
265
-		if ($moveSuccessful) {
266
-			$query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
267
-			$result = $query->execute(array($filename, $timestamp, $location, $owner));
268
-			if (!$result) {
269
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
270
-			}
271
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path),
272
-				'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)));
273
-
274
-			self::retainVersions($filename, $owner, $ownerPath, $timestamp);
275
-
276
-			// if owner !== user we need to also add a copy to the users trash
277
-			if ($user !== $owner && $ownerOnly === false) {
278
-				self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
279
-			}
280
-		}
281
-
282
-		self::scheduleExpire($user);
283
-
284
-		// if owner !== user we also need to update the owners trash size
285
-		if ($owner !== $user) {
286
-			self::scheduleExpire($owner);
287
-		}
288
-
289
-		return $moveSuccessful;
290
-	}
291
-
292
-	/**
293
-	 * Move file versions to trash so that they can be restored later
294
-	 *
295
-	 * @param string $filename of deleted file
296
-	 * @param string $owner owner user id
297
-	 * @param string $ownerPath path relative to the owner's home storage
298
-	 * @param integer $timestamp when the file was deleted
299
-	 */
300
-	private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
301
-		if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) {
302
-
303
-			$user = User::getUser();
304
-			$rootView = new View('/');
305
-
306
-			if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
307
-				if ($owner !== $user) {
308
-					self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
309
-				}
310
-				self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
311
-			} else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
312
-
313
-				foreach ($versions as $v) {
314
-					if ($owner !== $user) {
315
-						self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
316
-					}
317
-					self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
318
-				}
319
-			}
320
-		}
321
-	}
322
-
323
-	/**
324
-	 * Move a file or folder on storage level
325
-	 *
326
-	 * @param View $view
327
-	 * @param string $source
328
-	 * @param string $target
329
-	 * @return bool
330
-	 */
331
-	private static function move(View $view, $source, $target) {
332
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
333
-		list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
334
-		/** @var \OC\Files\Storage\Storage $targetStorage */
335
-		list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
336
-		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
337
-
338
-		$result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
339
-		if ($result) {
340
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
341
-		}
342
-		return $result;
343
-	}
344
-
345
-	/**
346
-	 * Copy a file or folder on storage level
347
-	 *
348
-	 * @param View $view
349
-	 * @param string $source
350
-	 * @param string $target
351
-	 * @return bool
352
-	 */
353
-	private static function copy(View $view, $source, $target) {
354
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
355
-		list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
356
-		/** @var \OC\Files\Storage\Storage $targetStorage */
357
-		list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
358
-		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
359
-
360
-		$result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
361
-		if ($result) {
362
-			$targetStorage->getUpdater()->update($targetInternalPath);
363
-		}
364
-		return $result;
365
-	}
366
-
367
-	/**
368
-	 * Restore a file or folder from trash bin
369
-	 *
370
-	 * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
371
-	 * including the timestamp suffix ".d12345678"
372
-	 * @param string $filename name of the file/folder
373
-	 * @param int $timestamp time when the file/folder was deleted
374
-	 *
375
-	 * @return bool true on success, false otherwise
376
-	 */
377
-	public static function restore($file, $filename, $timestamp) {
378
-		$user = User::getUser();
379
-		$view = new View('/' . $user);
380
-
381
-		$location = '';
382
-		if ($timestamp) {
383
-			$location = self::getLocation($user, $filename, $timestamp);
384
-			if ($location === false) {
385
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent!', \OCP\Util::ERROR);
386
-			} else {
387
-				// if location no longer exists, restore file in the root directory
388
-				if ($location !== '/' &&
389
-					(!$view->is_dir('files/' . $location) ||
390
-						!$view->isCreatable('files/' . $location))
391
-				) {
392
-					$location = '';
393
-				}
394
-			}
395
-		}
396
-
397
-		// we need a  extension in case a file/dir with the same name already exists
398
-		$uniqueFilename = self::getUniqueFilename($location, $filename, $view);
399
-
400
-		$source = Filesystem::normalizePath('files_trashbin/files/' . $file);
401
-		$target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
402
-		if (!$view->file_exists($source)) {
403
-			return false;
404
-		}
405
-		$mtime = $view->filemtime($source);
406
-
407
-		// restore file
408
-		$restoreResult = $view->rename($source, $target);
409
-
410
-		// handle the restore result
411
-		if ($restoreResult) {
412
-			$fakeRoot = $view->getRoot();
413
-			$view->chroot('/' . $user . '/files');
414
-			$view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
415
-			$view->chroot($fakeRoot);
416
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
417
-				'trashPath' => Filesystem::normalizePath($file)));
418
-
419
-			self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
420
-
421
-			if ($timestamp) {
422
-				$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
423
-				$query->execute(array($user, $filename, $timestamp));
424
-			}
425
-
426
-			return true;
427
-		}
428
-
429
-		return false;
430
-	}
431
-
432
-	/**
433
-	 * restore versions from trash bin
434
-	 *
435
-	 * @param View $view file view
436
-	 * @param string $file complete path to file
437
-	 * @param string $filename name of file once it was deleted
438
-	 * @param string $uniqueFilename new file name to restore the file without overwriting existing files
439
-	 * @param string $location location if file
440
-	 * @param int $timestamp deletion time
441
-	 * @return false|null
442
-	 */
443
-	private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
444
-
445
-		if (\OCP\App::isEnabled('files_versions')) {
446
-
447
-			$user = User::getUser();
448
-			$rootView = new View('/');
449
-
450
-			$target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
451
-
452
-			list($owner, $ownerPath) = self::getUidAndFilename($target);
453
-
454
-			// file has been deleted in between
455
-			if (empty($ownerPath)) {
456
-				return false;
457
-			}
458
-
459
-			if ($timestamp) {
460
-				$versionedFile = $filename;
461
-			} else {
462
-				$versionedFile = $file;
463
-			}
464
-
465
-			if ($view->is_dir('/files_trashbin/versions/' . $file)) {
466
-				$rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
467
-			} else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
468
-				foreach ($versions as $v) {
469
-					if ($timestamp) {
470
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
471
-					} else {
472
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
473
-					}
474
-				}
475
-			}
476
-		}
477
-	}
478
-
479
-	/**
480
-	 * delete all files from the trash
481
-	 */
482
-	public static function deleteAll() {
483
-		$user = User::getUser();
484
-		$view = new View('/' . $user);
485
-		$fileInfos = $view->getDirectoryContent('files_trashbin/files');
486
-
487
-		// Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
488
-		$filePaths = array();
489
-		foreach($fileInfos as $fileInfo){
490
-			$filePaths[] = $view->getRelativePath($fileInfo->getPath());
491
-		}
492
-		unset($fileInfos); // save memory
493
-
494
-		// Bulk PreDelete-Hook
495
-		\OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths));
496
-
497
-		// Single-File Hooks
498
-		foreach($filePaths as $path){
499
-			self::emitTrashbinPreDelete($path);
500
-		}
501
-
502
-		// actual file deletion
503
-		$view->deleteAll('files_trashbin');
504
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
505
-		$query->execute(array($user));
506
-
507
-		// Bulk PostDelete-Hook
508
-		\OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths));
509
-
510
-		// Single-File Hooks
511
-		foreach($filePaths as $path){
512
-			self::emitTrashbinPostDelete($path);
513
-		}
514
-
515
-		$view->mkdir('files_trashbin');
516
-		$view->mkdir('files_trashbin/files');
517
-
518
-		return true;
519
-	}
520
-
521
-	/**
522
-	 * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
523
-	 * @param string $path
524
-	 */
525
-	protected static function emitTrashbinPreDelete($path){
526
-		\OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path));
527
-	}
528
-
529
-	/**
530
-	 * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
531
-	 * @param string $path
532
-	 */
533
-	protected static function emitTrashbinPostDelete($path){
534
-		\OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path));
535
-	}
536
-
537
-	/**
538
-	 * delete file from trash bin permanently
539
-	 *
540
-	 * @param string $filename path to the file
541
-	 * @param string $user
542
-	 * @param int $timestamp of deletion time
543
-	 *
544
-	 * @return int size of deleted files
545
-	 */
546
-	public static function delete($filename, $user, $timestamp = null) {
547
-		$view = new View('/' . $user);
548
-		$size = 0;
549
-
550
-		if ($timestamp) {
551
-			$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
552
-			$query->execute(array($user, $filename, $timestamp));
553
-			$file = $filename . '.d' . $timestamp;
554
-		} else {
555
-			$file = $filename;
556
-		}
557
-
558
-		$size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
559
-
560
-		if ($view->is_dir('/files_trashbin/files/' . $file)) {
561
-			$size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
562
-		} else {
563
-			$size += $view->filesize('/files_trashbin/files/' . $file);
564
-		}
565
-		self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
566
-		$view->unlink('/files_trashbin/files/' . $file);
567
-		self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
568
-
569
-		return $size;
570
-	}
571
-
572
-	/**
573
-	 * @param View $view
574
-	 * @param string $file
575
-	 * @param string $filename
576
-	 * @param integer|null $timestamp
577
-	 * @param string $user
578
-	 * @return int
579
-	 */
580
-	private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
581
-		$size = 0;
582
-		if (\OCP\App::isEnabled('files_versions')) {
583
-			if ($view->is_dir('files_trashbin/versions/' . $file)) {
584
-				$size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
585
-				$view->unlink('files_trashbin/versions/' . $file);
586
-			} else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
587
-				foreach ($versions as $v) {
588
-					if ($timestamp) {
589
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
590
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
591
-					} else {
592
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
593
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
594
-					}
595
-				}
596
-			}
597
-		}
598
-		return $size;
599
-	}
600
-
601
-	/**
602
-	 * check to see whether a file exists in trashbin
603
-	 *
604
-	 * @param string $filename path to the file
605
-	 * @param int $timestamp of deletion time
606
-	 * @return bool true if file exists, otherwise false
607
-	 */
608
-	public static function file_exists($filename, $timestamp = null) {
609
-		$user = User::getUser();
610
-		$view = new View('/' . $user);
611
-
612
-		if ($timestamp) {
613
-			$filename = $filename . '.d' . $timestamp;
614
-		} else {
615
-			$filename = $filename;
616
-		}
617
-
618
-		$target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
619
-		return $view->file_exists($target);
620
-	}
621
-
622
-	/**
623
-	 * deletes used space for trash bin in db if user was deleted
624
-	 *
625
-	 * @param string $uid id of deleted user
626
-	 * @return bool result of db delete operation
627
-	 */
628
-	public static function deleteUser($uid) {
629
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
630
-		return $query->execute(array($uid));
631
-	}
632
-
633
-	/**
634
-	 * calculate remaining free space for trash bin
635
-	 *
636
-	 * @param integer $trashbinSize current size of the trash bin
637
-	 * @param string $user
638
-	 * @return int available free space for trash bin
639
-	 */
640
-	private static function calculateFreeSpace($trashbinSize, $user) {
641
-		$softQuota = true;
642
-		$userObject = \OC::$server->getUserManager()->get($user);
643
-		if(is_null($userObject)) {
644
-			return 0;
645
-		}
646
-		$quota = $userObject->getQuota();
647
-		if ($quota === null || $quota === 'none') {
648
-			$quota = Filesystem::free_space('/');
649
-			$softQuota = false;
650
-			// inf or unknown free space
651
-			if ($quota < 0) {
652
-				$quota = PHP_INT_MAX;
653
-			}
654
-		} else {
655
-			$quota = \OCP\Util::computerFileSize($quota);
656
-		}
657
-
658
-		// calculate available space for trash bin
659
-		// subtract size of files and current trash bin size from quota
660
-		if ($softQuota) {
661
-			$userFolder = \OC::$server->getUserFolder($user);
662
-			if(is_null($userFolder)) {
663
-				return 0;
664
-			}
665
-			$free = $quota - $userFolder->getSize(); // remaining free space for user
666
-			if ($free > 0) {
667
-				$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
668
-			} else {
669
-				$availableSpace = $free - $trashbinSize;
670
-			}
671
-		} else {
672
-			$availableSpace = $quota;
673
-		}
674
-
675
-		return $availableSpace;
676
-	}
677
-
678
-	/**
679
-	 * resize trash bin if necessary after a new file was added to ownCloud
680
-	 *
681
-	 * @param string $user user id
682
-	 */
683
-	public static function resizeTrash($user) {
684
-
685
-		$size = self::getTrashbinSize($user);
686
-
687
-		$freeSpace = self::calculateFreeSpace($size, $user);
688
-
689
-		if ($freeSpace < 0) {
690
-			self::scheduleExpire($user);
691
-		}
692
-	}
693
-
694
-	/**
695
-	 * clean up the trash bin
696
-	 *
697
-	 * @param string $user
698
-	 */
699
-	public static function expire($user) {
700
-		$trashBinSize = self::getTrashbinSize($user);
701
-		$availableSpace = self::calculateFreeSpace($trashBinSize, $user);
702
-
703
-		$dirContent = Helper::getTrashFiles('/', $user, 'mtime');
704
-
705
-		// delete all files older then $retention_obligation
706
-		list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user);
707
-
708
-		$availableSpace += $delSize;
709
-
710
-		// delete files from trash until we meet the trash bin size limit again
711
-		self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
712
-	}
713
-
714
-	/**
715
-	 * @param string $user
716
-	 */
717
-	private static function scheduleExpire($user) {
718
-		// let the admin disable auto expire
719
-		$application = new Application();
720
-		$expiration = $application->getContainer()->query('Expiration');
721
-		if ($expiration->isEnabled()) {
722
-			\OC::$server->getCommandBus()->push(new Expire($user));
723
-		}
724
-	}
725
-
726
-	/**
727
-	 * if the size limit for the trash bin is reached, we delete the oldest
728
-	 * files in the trash bin until we meet the limit again
729
-	 *
730
-	 * @param array $files
731
-	 * @param string $user
732
-	 * @param int $availableSpace available disc space
733
-	 * @return int size of deleted files
734
-	 */
735
-	protected static function deleteFiles($files, $user, $availableSpace) {
736
-		$application = new Application();
737
-		$expiration = $application->getContainer()->query('Expiration');
738
-		$size = 0;
739
-
740
-		if ($availableSpace < 0) {
741
-			foreach ($files as $file) {
742
-				if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
743
-					$tmp = self::delete($file['name'], $user, $file['mtime']);
744
-					\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);
745
-					$availableSpace += $tmp;
746
-					$size += $tmp;
747
-				} else {
748
-					break;
749
-				}
750
-			}
751
-		}
752
-		return $size;
753
-	}
754
-
755
-	/**
756
-	 * delete files older then max storage time
757
-	 *
758
-	 * @param array $files list of files sorted by mtime
759
-	 * @param string $user
760
-	 * @return integer[] size of deleted files and number of deleted files
761
-	 */
762
-	public static function deleteExpiredFiles($files, $user) {
763
-		$application = new Application();
764
-		$expiration = $application->getContainer()->query('Expiration');
765
-		$size = 0;
766
-		$count = 0;
767
-		foreach ($files as $file) {
768
-			$timestamp = $file['mtime'];
769
-			$filename = $file['name'];
770
-			if ($expiration->isExpired($timestamp)) {
771
-				$count++;
772
-				$size += self::delete($filename, $user, $timestamp);
773
-				\OC::$server->getLogger()->info(
774
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
775
-					['app' => 'files_trashbin']
776
-				);
777
-			} else {
778
-				break;
779
-			}
780
-		}
781
-
782
-		return array($size, $count);
783
-	}
784
-
785
-	/**
786
-	 * recursive copy to copy a whole directory
787
-	 *
788
-	 * @param string $source source path, relative to the users files directory
789
-	 * @param string $destination destination path relative to the users root directoy
790
-	 * @param View $view file view for the users root directory
791
-	 * @return int
792
-	 * @throws Exceptions\CopyRecursiveException
793
-	 */
794
-	private static function copy_recursive($source, $destination, View $view) {
795
-		$size = 0;
796
-		if ($view->is_dir($source)) {
797
-			$view->mkdir($destination);
798
-			$view->touch($destination, $view->filemtime($source));
799
-			foreach ($view->getDirectoryContent($source) as $i) {
800
-				$pathDir = $source . '/' . $i['name'];
801
-				if ($view->is_dir($pathDir)) {
802
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
803
-				} else {
804
-					$size += $view->filesize($pathDir);
805
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
806
-					if (!$result) {
807
-						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
808
-					}
809
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
810
-				}
811
-			}
812
-		} else {
813
-			$size += $view->filesize($source);
814
-			$result = $view->copy($source, $destination);
815
-			if (!$result) {
816
-				throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
817
-			}
818
-			$view->touch($destination, $view->filemtime($source));
819
-		}
820
-		return $size;
821
-	}
822
-
823
-	/**
824
-	 * find all versions which belong to the file we want to restore
825
-	 *
826
-	 * @param string $filename name of the file which should be restored
827
-	 * @param int $timestamp timestamp when the file was deleted
828
-	 * @return array
829
-	 */
830
-	private static function getVersionsFromTrash($filename, $timestamp, $user) {
831
-		$view = new View('/' . $user . '/files_trashbin/versions');
832
-		$versions = array();
833
-
834
-		//force rescan of versions, local storage may not have updated the cache
835
-		if (!self::$scannedVersions) {
836
-			/** @var \OC\Files\Storage\Storage $storage */
837
-			list($storage,) = $view->resolvePath('/');
838
-			$storage->getScanner()->scan('files_trashbin/versions');
839
-			self::$scannedVersions = true;
840
-		}
841
-
842
-		if ($timestamp) {
843
-			// fetch for old versions
844
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
845
-			$offset = -strlen($timestamp) - 2;
846
-		} else {
847
-			$matches = $view->searchRaw($filename . '.v%');
848
-		}
849
-
850
-		if (is_array($matches)) {
851
-			foreach ($matches as $ma) {
852
-				if ($timestamp) {
853
-					$parts = explode('.v', substr($ma['path'], 0, $offset));
854
-					$versions[] = (end($parts));
855
-				} else {
856
-					$parts = explode('.v', $ma);
857
-					$versions[] = (end($parts));
858
-				}
859
-			}
860
-		}
861
-		return $versions;
862
-	}
863
-
864
-	/**
865
-	 * find unique extension for restored file if a file with the same name already exists
866
-	 *
867
-	 * @param string $location where the file should be restored
868
-	 * @param string $filename name of the file
869
-	 * @param View $view filesystem view relative to users root directory
870
-	 * @return string with unique extension
871
-	 */
872
-	private static function getUniqueFilename($location, $filename, View $view) {
873
-		$ext = pathinfo($filename, PATHINFO_EXTENSION);
874
-		$name = pathinfo($filename, PATHINFO_FILENAME);
875
-		$l = \OC::$server->getL10N('files_trashbin');
876
-
877
-		$location = '/' . trim($location, '/');
878
-
879
-		// if extension is not empty we set a dot in front of it
880
-		if ($ext !== '') {
881
-			$ext = '.' . $ext;
882
-		}
883
-
884
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
885
-			$i = 2;
886
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
887
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
888
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
889
-				$i++;
890
-			}
891
-
892
-			return $uniqueName;
893
-		}
894
-
895
-		return $filename;
896
-	}
897
-
898
-	/**
899
-	 * get the size from a given root folder
900
-	 *
901
-	 * @param View $view file view on the root folder
902
-	 * @return integer size of the folder
903
-	 */
904
-	private static function calculateSize($view) {
905
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
906
-		if (!file_exists($root)) {
907
-			return 0;
908
-		}
909
-		$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
910
-		$size = 0;
911
-
912
-		/**
913
-		 * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
914
-		 * This bug is fixed in PHP 5.5.9 or before
915
-		 * See #8376
916
-		 */
917
-		$iterator->rewind();
918
-		while ($iterator->valid()) {
919
-			$path = $iterator->current();
920
-			$relpath = substr($path, strlen($root) - 1);
921
-			if (!$view->is_dir($relpath)) {
922
-				$size += $view->filesize($relpath);
923
-			}
924
-			$iterator->next();
925
-		}
926
-		return $size;
927
-	}
928
-
929
-	/**
930
-	 * get current size of trash bin from a given user
931
-	 *
932
-	 * @param string $user user who owns the trash bin
933
-	 * @return integer trash bin size
934
-	 */
935
-	private static function getTrashbinSize($user) {
936
-		$view = new View('/' . $user);
937
-		$fileInfo = $view->getFileInfo('/files_trashbin');
938
-		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
939
-	}
940
-
941
-	/**
942
-	 * register hooks
943
-	 */
944
-	public static function registerHooks() {
945
-		// create storage wrapper on setup
946
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
947
-		//Listen to delete user signal
948
-		\OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
949
-		//Listen to post write hook
950
-		\OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
951
-		// pre and post-rename, disable trash logic for the copy+unlink case
952
-		\OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
953
-		\OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook');
954
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook');
955
-	}
956
-
957
-	/**
958
-	 * check if trash bin is empty for a given user
959
-	 *
960
-	 * @param string $user
961
-	 * @return bool
962
-	 */
963
-	public static function isEmpty($user) {
964
-
965
-		$view = new View('/' . $user . '/files_trashbin');
966
-		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
967
-			while ($file = readdir($dh)) {
968
-				if (!Filesystem::isIgnoredDir($file)) {
969
-					return false;
970
-				}
971
-			}
972
-		}
973
-		return true;
974
-	}
975
-
976
-	/**
977
-	 * @param $path
978
-	 * @return string
979
-	 */
980
-	public static function preview_icon($path) {
981
-		return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path));
982
-	}
50
+    // unit: percentage; 50% of available disk space/quota
51
+    const DEFAULTMAXSIZE = 50;
52
+
53
+    /**
54
+     * Whether versions have already be rescanned during this PHP request
55
+     *
56
+     * @var bool
57
+     */
58
+    private static $scannedVersions = false;
59
+
60
+    /**
61
+     * Ensure we don't need to scan the file during the move to trash
62
+     * by triggering the scan in the pre-hook
63
+     *
64
+     * @param array $params
65
+     */
66
+    public static function ensureFileScannedHook($params) {
67
+        try {
68
+            self::getUidAndFilename($params['path']);
69
+        } catch (NotFoundException $e) {
70
+            // nothing to scan for non existing files
71
+        }
72
+    }
73
+
74
+    /**
75
+     * get the UID of the owner of the file and the path to the file relative to
76
+     * owners files folder
77
+     *
78
+     * @param string $filename
79
+     * @return array
80
+     * @throws \OC\User\NoUserException
81
+     */
82
+    public static function getUidAndFilename($filename) {
83
+        $uid = Filesystem::getOwner($filename);
84
+        $userManager = \OC::$server->getUserManager();
85
+        // if the user with the UID doesn't exists, e.g. because the UID points
86
+        // to a remote user with a federated cloud ID we use the current logged-in
87
+        // user. We need a valid local user to move the file to the right trash bin
88
+        if (!$userManager->userExists($uid)) {
89
+            $uid = User::getUser();
90
+        }
91
+        if (!$uid) {
92
+            // no owner, usually because of share link from ext storage
93
+            return [null, null];
94
+        }
95
+        Filesystem::initMountPoints($uid);
96
+        if ($uid != User::getUser()) {
97
+            $info = Filesystem::getFileInfo($filename);
98
+            $ownerView = new View('/' . $uid . '/files');
99
+            try {
100
+                $filename = $ownerView->getPath($info['fileid']);
101
+            } catch (NotFoundException $e) {
102
+                $filename = null;
103
+            }
104
+        }
105
+        return [$uid, $filename];
106
+    }
107
+
108
+    /**
109
+     * get original location of files for user
110
+     *
111
+     * @param string $user
112
+     * @return array (filename => array (timestamp => original location))
113
+     */
114
+    public static function getLocations($user) {
115
+        $query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`'
116
+            . ' FROM `*PREFIX*files_trash` WHERE `user`=?');
117
+        $result = $query->execute(array($user));
118
+        $array = array();
119
+        while ($row = $result->fetchRow()) {
120
+            if (isset($array[$row['id']])) {
121
+                $array[$row['id']][$row['timestamp']] = $row['location'];
122
+            } else {
123
+                $array[$row['id']] = array($row['timestamp'] => $row['location']);
124
+            }
125
+        }
126
+        return $array;
127
+    }
128
+
129
+    /**
130
+     * get original location of file
131
+     *
132
+     * @param string $user
133
+     * @param string $filename
134
+     * @param string $timestamp
135
+     * @return string original location
136
+     */
137
+    public static function getLocation($user, $filename, $timestamp) {
138
+        $query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`'
139
+            . ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
140
+        $result = $query->execute(array($user, $filename, $timestamp))->fetchAll();
141
+        if (isset($result[0]['location'])) {
142
+            return $result[0]['location'];
143
+        } else {
144
+            return false;
145
+        }
146
+    }
147
+
148
+    private static function setUpTrash($user) {
149
+        $view = new View('/' . $user);
150
+        if (!$view->is_dir('files_trashbin')) {
151
+            $view->mkdir('files_trashbin');
152
+        }
153
+        if (!$view->is_dir('files_trashbin/files')) {
154
+            $view->mkdir('files_trashbin/files');
155
+        }
156
+        if (!$view->is_dir('files_trashbin/versions')) {
157
+            $view->mkdir('files_trashbin/versions');
158
+        }
159
+        if (!$view->is_dir('files_trashbin/keys')) {
160
+            $view->mkdir('files_trashbin/keys');
161
+        }
162
+    }
163
+
164
+
165
+    /**
166
+     * copy file to owners trash
167
+     *
168
+     * @param string $sourcePath
169
+     * @param string $owner
170
+     * @param string $targetPath
171
+     * @param $user
172
+     * @param integer $timestamp
173
+     */
174
+    private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
175
+        self::setUpTrash($owner);
176
+
177
+        $targetFilename = basename($targetPath);
178
+        $targetLocation = dirname($targetPath);
179
+
180
+        $sourceFilename = basename($sourcePath);
181
+
182
+        $view = new View('/');
183
+
184
+        $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
185
+        $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
186
+        self::copy_recursive($source, $target, $view);
187
+
188
+
189
+        if ($view->file_exists($target)) {
190
+            $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
191
+            $result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user));
192
+            if (!$result) {
193
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR);
194
+            }
195
+        }
196
+    }
197
+
198
+
199
+    /**
200
+     * move file to the trash bin
201
+     *
202
+     * @param string $file_path path to the deleted file/directory relative to the files root directory
203
+     * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
204
+     *
205
+     * @return bool
206
+     */
207
+    public static function move2trash($file_path, $ownerOnly = false) {
208
+        // get the user for which the filesystem is setup
209
+        $root = Filesystem::getRoot();
210
+        list(, $user) = explode('/', $root);
211
+        list($owner, $ownerPath) = self::getUidAndFilename($file_path);
212
+
213
+        // if no owner found (ex: ext storage + share link), will use the current user's trashbin then
214
+        if (is_null($owner)) {
215
+            $owner = $user;
216
+            $ownerPath = $file_path;
217
+        }
218
+
219
+        $ownerView = new View('/' . $owner);
220
+        // file has been deleted in between
221
+        if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
222
+            return true;
223
+        }
224
+
225
+        self::setUpTrash($user);
226
+        if ($owner !== $user) {
227
+            // also setup for owner
228
+            self::setUpTrash($owner);
229
+        }
230
+
231
+        $path_parts = pathinfo($ownerPath);
232
+
233
+        $filename = $path_parts['basename'];
234
+        $location = $path_parts['dirname'];
235
+        $timestamp = time();
236
+
237
+        // disable proxy to prevent recursive calls
238
+        $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
239
+
240
+        /** @var \OC\Files\Storage\Storage $trashStorage */
241
+        list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath);
242
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
243
+        list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath);
244
+        try {
245
+            $moveSuccessful = true;
246
+            if ($trashStorage->file_exists($trashInternalPath)) {
247
+                $trashStorage->unlink($trashInternalPath);
248
+            }
249
+            $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
250
+        } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
251
+            $moveSuccessful = false;
252
+            if ($trashStorage->file_exists($trashInternalPath)) {
253
+                $trashStorage->unlink($trashInternalPath);
254
+            }
255
+            \OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
256
+        }
257
+
258
+        if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
259
+            $sourceStorage->unlink($sourceInternalPath);
260
+            return false;
261
+        }
262
+
263
+        $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
264
+
265
+        if ($moveSuccessful) {
266
+            $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
267
+            $result = $query->execute(array($filename, $timestamp, $location, $owner));
268
+            if (!$result) {
269
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
270
+            }
271
+            \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path),
272
+                'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)));
273
+
274
+            self::retainVersions($filename, $owner, $ownerPath, $timestamp);
275
+
276
+            // if owner !== user we need to also add a copy to the users trash
277
+            if ($user !== $owner && $ownerOnly === false) {
278
+                self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
279
+            }
280
+        }
281
+
282
+        self::scheduleExpire($user);
283
+
284
+        // if owner !== user we also need to update the owners trash size
285
+        if ($owner !== $user) {
286
+            self::scheduleExpire($owner);
287
+        }
288
+
289
+        return $moveSuccessful;
290
+    }
291
+
292
+    /**
293
+     * Move file versions to trash so that they can be restored later
294
+     *
295
+     * @param string $filename of deleted file
296
+     * @param string $owner owner user id
297
+     * @param string $ownerPath path relative to the owner's home storage
298
+     * @param integer $timestamp when the file was deleted
299
+     */
300
+    private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
301
+        if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) {
302
+
303
+            $user = User::getUser();
304
+            $rootView = new View('/');
305
+
306
+            if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
307
+                if ($owner !== $user) {
308
+                    self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
309
+                }
310
+                self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
311
+            } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
312
+
313
+                foreach ($versions as $v) {
314
+                    if ($owner !== $user) {
315
+                        self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
316
+                    }
317
+                    self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
318
+                }
319
+            }
320
+        }
321
+    }
322
+
323
+    /**
324
+     * Move a file or folder on storage level
325
+     *
326
+     * @param View $view
327
+     * @param string $source
328
+     * @param string $target
329
+     * @return bool
330
+     */
331
+    private static function move(View $view, $source, $target) {
332
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
333
+        list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
334
+        /** @var \OC\Files\Storage\Storage $targetStorage */
335
+        list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
336
+        /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
337
+
338
+        $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
339
+        if ($result) {
340
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
341
+        }
342
+        return $result;
343
+    }
344
+
345
+    /**
346
+     * Copy a file or folder on storage level
347
+     *
348
+     * @param View $view
349
+     * @param string $source
350
+     * @param string $target
351
+     * @return bool
352
+     */
353
+    private static function copy(View $view, $source, $target) {
354
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
355
+        list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
356
+        /** @var \OC\Files\Storage\Storage $targetStorage */
357
+        list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
358
+        /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
359
+
360
+        $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
361
+        if ($result) {
362
+            $targetStorage->getUpdater()->update($targetInternalPath);
363
+        }
364
+        return $result;
365
+    }
366
+
367
+    /**
368
+     * Restore a file or folder from trash bin
369
+     *
370
+     * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
371
+     * including the timestamp suffix ".d12345678"
372
+     * @param string $filename name of the file/folder
373
+     * @param int $timestamp time when the file/folder was deleted
374
+     *
375
+     * @return bool true on success, false otherwise
376
+     */
377
+    public static function restore($file, $filename, $timestamp) {
378
+        $user = User::getUser();
379
+        $view = new View('/' . $user);
380
+
381
+        $location = '';
382
+        if ($timestamp) {
383
+            $location = self::getLocation($user, $filename, $timestamp);
384
+            if ($location === false) {
385
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent!', \OCP\Util::ERROR);
386
+            } else {
387
+                // if location no longer exists, restore file in the root directory
388
+                if ($location !== '/' &&
389
+                    (!$view->is_dir('files/' . $location) ||
390
+                        !$view->isCreatable('files/' . $location))
391
+                ) {
392
+                    $location = '';
393
+                }
394
+            }
395
+        }
396
+
397
+        // we need a  extension in case a file/dir with the same name already exists
398
+        $uniqueFilename = self::getUniqueFilename($location, $filename, $view);
399
+
400
+        $source = Filesystem::normalizePath('files_trashbin/files/' . $file);
401
+        $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
402
+        if (!$view->file_exists($source)) {
403
+            return false;
404
+        }
405
+        $mtime = $view->filemtime($source);
406
+
407
+        // restore file
408
+        $restoreResult = $view->rename($source, $target);
409
+
410
+        // handle the restore result
411
+        if ($restoreResult) {
412
+            $fakeRoot = $view->getRoot();
413
+            $view->chroot('/' . $user . '/files');
414
+            $view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
415
+            $view->chroot($fakeRoot);
416
+            \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
417
+                'trashPath' => Filesystem::normalizePath($file)));
418
+
419
+            self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
420
+
421
+            if ($timestamp) {
422
+                $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
423
+                $query->execute(array($user, $filename, $timestamp));
424
+            }
425
+
426
+            return true;
427
+        }
428
+
429
+        return false;
430
+    }
431
+
432
+    /**
433
+     * restore versions from trash bin
434
+     *
435
+     * @param View $view file view
436
+     * @param string $file complete path to file
437
+     * @param string $filename name of file once it was deleted
438
+     * @param string $uniqueFilename new file name to restore the file without overwriting existing files
439
+     * @param string $location location if file
440
+     * @param int $timestamp deletion time
441
+     * @return false|null
442
+     */
443
+    private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
444
+
445
+        if (\OCP\App::isEnabled('files_versions')) {
446
+
447
+            $user = User::getUser();
448
+            $rootView = new View('/');
449
+
450
+            $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
451
+
452
+            list($owner, $ownerPath) = self::getUidAndFilename($target);
453
+
454
+            // file has been deleted in between
455
+            if (empty($ownerPath)) {
456
+                return false;
457
+            }
458
+
459
+            if ($timestamp) {
460
+                $versionedFile = $filename;
461
+            } else {
462
+                $versionedFile = $file;
463
+            }
464
+
465
+            if ($view->is_dir('/files_trashbin/versions/' . $file)) {
466
+                $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
467
+            } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
468
+                foreach ($versions as $v) {
469
+                    if ($timestamp) {
470
+                        $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
471
+                    } else {
472
+                        $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
473
+                    }
474
+                }
475
+            }
476
+        }
477
+    }
478
+
479
+    /**
480
+     * delete all files from the trash
481
+     */
482
+    public static function deleteAll() {
483
+        $user = User::getUser();
484
+        $view = new View('/' . $user);
485
+        $fileInfos = $view->getDirectoryContent('files_trashbin/files');
486
+
487
+        // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
488
+        $filePaths = array();
489
+        foreach($fileInfos as $fileInfo){
490
+            $filePaths[] = $view->getRelativePath($fileInfo->getPath());
491
+        }
492
+        unset($fileInfos); // save memory
493
+
494
+        // Bulk PreDelete-Hook
495
+        \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths));
496
+
497
+        // Single-File Hooks
498
+        foreach($filePaths as $path){
499
+            self::emitTrashbinPreDelete($path);
500
+        }
501
+
502
+        // actual file deletion
503
+        $view->deleteAll('files_trashbin');
504
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
505
+        $query->execute(array($user));
506
+
507
+        // Bulk PostDelete-Hook
508
+        \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths));
509
+
510
+        // Single-File Hooks
511
+        foreach($filePaths as $path){
512
+            self::emitTrashbinPostDelete($path);
513
+        }
514
+
515
+        $view->mkdir('files_trashbin');
516
+        $view->mkdir('files_trashbin/files');
517
+
518
+        return true;
519
+    }
520
+
521
+    /**
522
+     * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
523
+     * @param string $path
524
+     */
525
+    protected static function emitTrashbinPreDelete($path){
526
+        \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path));
527
+    }
528
+
529
+    /**
530
+     * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
531
+     * @param string $path
532
+     */
533
+    protected static function emitTrashbinPostDelete($path){
534
+        \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path));
535
+    }
536
+
537
+    /**
538
+     * delete file from trash bin permanently
539
+     *
540
+     * @param string $filename path to the file
541
+     * @param string $user
542
+     * @param int $timestamp of deletion time
543
+     *
544
+     * @return int size of deleted files
545
+     */
546
+    public static function delete($filename, $user, $timestamp = null) {
547
+        $view = new View('/' . $user);
548
+        $size = 0;
549
+
550
+        if ($timestamp) {
551
+            $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
552
+            $query->execute(array($user, $filename, $timestamp));
553
+            $file = $filename . '.d' . $timestamp;
554
+        } else {
555
+            $file = $filename;
556
+        }
557
+
558
+        $size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
559
+
560
+        if ($view->is_dir('/files_trashbin/files/' . $file)) {
561
+            $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
562
+        } else {
563
+            $size += $view->filesize('/files_trashbin/files/' . $file);
564
+        }
565
+        self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
566
+        $view->unlink('/files_trashbin/files/' . $file);
567
+        self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
568
+
569
+        return $size;
570
+    }
571
+
572
+    /**
573
+     * @param View $view
574
+     * @param string $file
575
+     * @param string $filename
576
+     * @param integer|null $timestamp
577
+     * @param string $user
578
+     * @return int
579
+     */
580
+    private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
581
+        $size = 0;
582
+        if (\OCP\App::isEnabled('files_versions')) {
583
+            if ($view->is_dir('files_trashbin/versions/' . $file)) {
584
+                $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
585
+                $view->unlink('files_trashbin/versions/' . $file);
586
+            } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
587
+                foreach ($versions as $v) {
588
+                    if ($timestamp) {
589
+                        $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
590
+                        $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
591
+                    } else {
592
+                        $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
593
+                        $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
594
+                    }
595
+                }
596
+            }
597
+        }
598
+        return $size;
599
+    }
600
+
601
+    /**
602
+     * check to see whether a file exists in trashbin
603
+     *
604
+     * @param string $filename path to the file
605
+     * @param int $timestamp of deletion time
606
+     * @return bool true if file exists, otherwise false
607
+     */
608
+    public static function file_exists($filename, $timestamp = null) {
609
+        $user = User::getUser();
610
+        $view = new View('/' . $user);
611
+
612
+        if ($timestamp) {
613
+            $filename = $filename . '.d' . $timestamp;
614
+        } else {
615
+            $filename = $filename;
616
+        }
617
+
618
+        $target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
619
+        return $view->file_exists($target);
620
+    }
621
+
622
+    /**
623
+     * deletes used space for trash bin in db if user was deleted
624
+     *
625
+     * @param string $uid id of deleted user
626
+     * @return bool result of db delete operation
627
+     */
628
+    public static function deleteUser($uid) {
629
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
630
+        return $query->execute(array($uid));
631
+    }
632
+
633
+    /**
634
+     * calculate remaining free space for trash bin
635
+     *
636
+     * @param integer $trashbinSize current size of the trash bin
637
+     * @param string $user
638
+     * @return int available free space for trash bin
639
+     */
640
+    private static function calculateFreeSpace($trashbinSize, $user) {
641
+        $softQuota = true;
642
+        $userObject = \OC::$server->getUserManager()->get($user);
643
+        if(is_null($userObject)) {
644
+            return 0;
645
+        }
646
+        $quota = $userObject->getQuota();
647
+        if ($quota === null || $quota === 'none') {
648
+            $quota = Filesystem::free_space('/');
649
+            $softQuota = false;
650
+            // inf or unknown free space
651
+            if ($quota < 0) {
652
+                $quota = PHP_INT_MAX;
653
+            }
654
+        } else {
655
+            $quota = \OCP\Util::computerFileSize($quota);
656
+        }
657
+
658
+        // calculate available space for trash bin
659
+        // subtract size of files and current trash bin size from quota
660
+        if ($softQuota) {
661
+            $userFolder = \OC::$server->getUserFolder($user);
662
+            if(is_null($userFolder)) {
663
+                return 0;
664
+            }
665
+            $free = $quota - $userFolder->getSize(); // remaining free space for user
666
+            if ($free > 0) {
667
+                $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
668
+            } else {
669
+                $availableSpace = $free - $trashbinSize;
670
+            }
671
+        } else {
672
+            $availableSpace = $quota;
673
+        }
674
+
675
+        return $availableSpace;
676
+    }
677
+
678
+    /**
679
+     * resize trash bin if necessary after a new file was added to ownCloud
680
+     *
681
+     * @param string $user user id
682
+     */
683
+    public static function resizeTrash($user) {
684
+
685
+        $size = self::getTrashbinSize($user);
686
+
687
+        $freeSpace = self::calculateFreeSpace($size, $user);
688
+
689
+        if ($freeSpace < 0) {
690
+            self::scheduleExpire($user);
691
+        }
692
+    }
693
+
694
+    /**
695
+     * clean up the trash bin
696
+     *
697
+     * @param string $user
698
+     */
699
+    public static function expire($user) {
700
+        $trashBinSize = self::getTrashbinSize($user);
701
+        $availableSpace = self::calculateFreeSpace($trashBinSize, $user);
702
+
703
+        $dirContent = Helper::getTrashFiles('/', $user, 'mtime');
704
+
705
+        // delete all files older then $retention_obligation
706
+        list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user);
707
+
708
+        $availableSpace += $delSize;
709
+
710
+        // delete files from trash until we meet the trash bin size limit again
711
+        self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
712
+    }
713
+
714
+    /**
715
+     * @param string $user
716
+     */
717
+    private static function scheduleExpire($user) {
718
+        // let the admin disable auto expire
719
+        $application = new Application();
720
+        $expiration = $application->getContainer()->query('Expiration');
721
+        if ($expiration->isEnabled()) {
722
+            \OC::$server->getCommandBus()->push(new Expire($user));
723
+        }
724
+    }
725
+
726
+    /**
727
+     * if the size limit for the trash bin is reached, we delete the oldest
728
+     * files in the trash bin until we meet the limit again
729
+     *
730
+     * @param array $files
731
+     * @param string $user
732
+     * @param int $availableSpace available disc space
733
+     * @return int size of deleted files
734
+     */
735
+    protected static function deleteFiles($files, $user, $availableSpace) {
736
+        $application = new Application();
737
+        $expiration = $application->getContainer()->query('Expiration');
738
+        $size = 0;
739
+
740
+        if ($availableSpace < 0) {
741
+            foreach ($files as $file) {
742
+                if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
743
+                    $tmp = self::delete($file['name'], $user, $file['mtime']);
744
+                    \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);
745
+                    $availableSpace += $tmp;
746
+                    $size += $tmp;
747
+                } else {
748
+                    break;
749
+                }
750
+            }
751
+        }
752
+        return $size;
753
+    }
754
+
755
+    /**
756
+     * delete files older then max storage time
757
+     *
758
+     * @param array $files list of files sorted by mtime
759
+     * @param string $user
760
+     * @return integer[] size of deleted files and number of deleted files
761
+     */
762
+    public static function deleteExpiredFiles($files, $user) {
763
+        $application = new Application();
764
+        $expiration = $application->getContainer()->query('Expiration');
765
+        $size = 0;
766
+        $count = 0;
767
+        foreach ($files as $file) {
768
+            $timestamp = $file['mtime'];
769
+            $filename = $file['name'];
770
+            if ($expiration->isExpired($timestamp)) {
771
+                $count++;
772
+                $size += self::delete($filename, $user, $timestamp);
773
+                \OC::$server->getLogger()->info(
774
+                    'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
775
+                    ['app' => 'files_trashbin']
776
+                );
777
+            } else {
778
+                break;
779
+            }
780
+        }
781
+
782
+        return array($size, $count);
783
+    }
784
+
785
+    /**
786
+     * recursive copy to copy a whole directory
787
+     *
788
+     * @param string $source source path, relative to the users files directory
789
+     * @param string $destination destination path relative to the users root directoy
790
+     * @param View $view file view for the users root directory
791
+     * @return int
792
+     * @throws Exceptions\CopyRecursiveException
793
+     */
794
+    private static function copy_recursive($source, $destination, View $view) {
795
+        $size = 0;
796
+        if ($view->is_dir($source)) {
797
+            $view->mkdir($destination);
798
+            $view->touch($destination, $view->filemtime($source));
799
+            foreach ($view->getDirectoryContent($source) as $i) {
800
+                $pathDir = $source . '/' . $i['name'];
801
+                if ($view->is_dir($pathDir)) {
802
+                    $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
803
+                } else {
804
+                    $size += $view->filesize($pathDir);
805
+                    $result = $view->copy($pathDir, $destination . '/' . $i['name']);
806
+                    if (!$result) {
807
+                        throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
808
+                    }
809
+                    $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
810
+                }
811
+            }
812
+        } else {
813
+            $size += $view->filesize($source);
814
+            $result = $view->copy($source, $destination);
815
+            if (!$result) {
816
+                throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
817
+            }
818
+            $view->touch($destination, $view->filemtime($source));
819
+        }
820
+        return $size;
821
+    }
822
+
823
+    /**
824
+     * find all versions which belong to the file we want to restore
825
+     *
826
+     * @param string $filename name of the file which should be restored
827
+     * @param int $timestamp timestamp when the file was deleted
828
+     * @return array
829
+     */
830
+    private static function getVersionsFromTrash($filename, $timestamp, $user) {
831
+        $view = new View('/' . $user . '/files_trashbin/versions');
832
+        $versions = array();
833
+
834
+        //force rescan of versions, local storage may not have updated the cache
835
+        if (!self::$scannedVersions) {
836
+            /** @var \OC\Files\Storage\Storage $storage */
837
+            list($storage,) = $view->resolvePath('/');
838
+            $storage->getScanner()->scan('files_trashbin/versions');
839
+            self::$scannedVersions = true;
840
+        }
841
+
842
+        if ($timestamp) {
843
+            // fetch for old versions
844
+            $matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
845
+            $offset = -strlen($timestamp) - 2;
846
+        } else {
847
+            $matches = $view->searchRaw($filename . '.v%');
848
+        }
849
+
850
+        if (is_array($matches)) {
851
+            foreach ($matches as $ma) {
852
+                if ($timestamp) {
853
+                    $parts = explode('.v', substr($ma['path'], 0, $offset));
854
+                    $versions[] = (end($parts));
855
+                } else {
856
+                    $parts = explode('.v', $ma);
857
+                    $versions[] = (end($parts));
858
+                }
859
+            }
860
+        }
861
+        return $versions;
862
+    }
863
+
864
+    /**
865
+     * find unique extension for restored file if a file with the same name already exists
866
+     *
867
+     * @param string $location where the file should be restored
868
+     * @param string $filename name of the file
869
+     * @param View $view filesystem view relative to users root directory
870
+     * @return string with unique extension
871
+     */
872
+    private static function getUniqueFilename($location, $filename, View $view) {
873
+        $ext = pathinfo($filename, PATHINFO_EXTENSION);
874
+        $name = pathinfo($filename, PATHINFO_FILENAME);
875
+        $l = \OC::$server->getL10N('files_trashbin');
876
+
877
+        $location = '/' . trim($location, '/');
878
+
879
+        // if extension is not empty we set a dot in front of it
880
+        if ($ext !== '') {
881
+            $ext = '.' . $ext;
882
+        }
883
+
884
+        if ($view->file_exists('files' . $location . '/' . $filename)) {
885
+            $i = 2;
886
+            $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
887
+            while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
888
+                $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
889
+                $i++;
890
+            }
891
+
892
+            return $uniqueName;
893
+        }
894
+
895
+        return $filename;
896
+    }
897
+
898
+    /**
899
+     * get the size from a given root folder
900
+     *
901
+     * @param View $view file view on the root folder
902
+     * @return integer size of the folder
903
+     */
904
+    private static function calculateSize($view) {
905
+        $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
906
+        if (!file_exists($root)) {
907
+            return 0;
908
+        }
909
+        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
910
+        $size = 0;
911
+
912
+        /**
913
+         * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
914
+         * This bug is fixed in PHP 5.5.9 or before
915
+         * See #8376
916
+         */
917
+        $iterator->rewind();
918
+        while ($iterator->valid()) {
919
+            $path = $iterator->current();
920
+            $relpath = substr($path, strlen($root) - 1);
921
+            if (!$view->is_dir($relpath)) {
922
+                $size += $view->filesize($relpath);
923
+            }
924
+            $iterator->next();
925
+        }
926
+        return $size;
927
+    }
928
+
929
+    /**
930
+     * get current size of trash bin from a given user
931
+     *
932
+     * @param string $user user who owns the trash bin
933
+     * @return integer trash bin size
934
+     */
935
+    private static function getTrashbinSize($user) {
936
+        $view = new View('/' . $user);
937
+        $fileInfo = $view->getFileInfo('/files_trashbin');
938
+        return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
939
+    }
940
+
941
+    /**
942
+     * register hooks
943
+     */
944
+    public static function registerHooks() {
945
+        // create storage wrapper on setup
946
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
947
+        //Listen to delete user signal
948
+        \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
949
+        //Listen to post write hook
950
+        \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
951
+        // pre and post-rename, disable trash logic for the copy+unlink case
952
+        \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
953
+        \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook');
954
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook');
955
+    }
956
+
957
+    /**
958
+     * check if trash bin is empty for a given user
959
+     *
960
+     * @param string $user
961
+     * @return bool
962
+     */
963
+    public static function isEmpty($user) {
964
+
965
+        $view = new View('/' . $user . '/files_trashbin');
966
+        if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
967
+            while ($file = readdir($dh)) {
968
+                if (!Filesystem::isIgnoredDir($file)) {
969
+                    return false;
970
+                }
971
+            }
972
+        }
973
+        return true;
974
+    }
975
+
976
+    /**
977
+     * @param $path
978
+     * @return string
979
+     */
980
+    public static function preview_icon($path) {
981
+        return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path));
982
+    }
983 983
 }
Please login to merge, or discard this patch.
Spacing   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		Filesystem::initMountPoints($uid);
96 96
 		if ($uid != User::getUser()) {
97 97
 			$info = Filesystem::getFileInfo($filename);
98
-			$ownerView = new View('/' . $uid . '/files');
98
+			$ownerView = new View('/'.$uid.'/files');
99 99
 			try {
100 100
 				$filename = $ownerView->getPath($info['fileid']);
101 101
 			} catch (NotFoundException $e) {
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 	}
147 147
 
148 148
 	private static function setUpTrash($user) {
149
-		$view = new View('/' . $user);
149
+		$view = new View('/'.$user);
150 150
 		if (!$view->is_dir('files_trashbin')) {
151 151
 			$view->mkdir('files_trashbin');
152 152
 		}
@@ -181,8 +181,8 @@  discard block
 block discarded – undo
181 181
 
182 182
 		$view = new View('/');
183 183
 
184
-		$target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
185
-		$source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
184
+		$target = $user.'/files_trashbin/files/'.$targetFilename.'.d'.$timestamp;
185
+		$source = $owner.'/files_trashbin/files/'.$sourceFilename.'.d'.$timestamp;
186 186
 		self::copy_recursive($source, $target, $view);
187 187
 
188 188
 
@@ -216,9 +216,9 @@  discard block
 block discarded – undo
216 216
 			$ownerPath = $file_path;
217 217
 		}
218 218
 
219
-		$ownerView = new View('/' . $owner);
219
+		$ownerView = new View('/'.$owner);
220 220
 		// file has been deleted in between
221
-		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
221
+		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/'.$ownerPath)) {
222 222
 			return true;
223 223
 		}
224 224
 
@@ -235,12 +235,12 @@  discard block
 block discarded – undo
235 235
 		$timestamp = time();
236 236
 
237 237
 		// disable proxy to prevent recursive calls
238
-		$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
238
+		$trashPath = '/files_trashbin/files/'.$filename.'.d'.$timestamp;
239 239
 
240 240
 		/** @var \OC\Files\Storage\Storage $trashStorage */
241 241
 		list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath);
242 242
 		/** @var \OC\Files\Storage\Storage $sourceStorage */
243
-		list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath);
243
+		list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/'.$ownerPath);
244 244
 		try {
245 245
 			$moveSuccessful = true;
246 246
 			if ($trashStorage->file_exists($trashInternalPath)) {
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 			if ($trashStorage->file_exists($trashInternalPath)) {
253 253
 				$trashStorage->unlink($trashInternalPath);
254 254
 			}
255
-			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
255
+			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move '.$file_path.' to the trash bin', \OCP\Util::ERROR);
256 256
 		}
257 257
 
258 258
 		if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
270 270
 			}
271 271
 			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path),
272
-				'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)));
272
+				'trashPath' => Filesystem::normalizePath($filename.'.d'.$timestamp)));
273 273
 
274 274
 			self::retainVersions($filename, $owner, $ownerPath, $timestamp);
275 275
 
@@ -303,18 +303,18 @@  discard block
 block discarded – undo
303 303
 			$user = User::getUser();
304 304
 			$rootView = new View('/');
305 305
 
306
-			if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
306
+			if ($rootView->is_dir($owner.'/files_versions/'.$ownerPath)) {
307 307
 				if ($owner !== $user) {
308
-					self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
308
+					self::copy_recursive($owner.'/files_versions/'.$ownerPath, $owner.'/files_trashbin/versions/'.basename($ownerPath).'.d'.$timestamp, $rootView);
309 309
 				}
310
-				self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
310
+				self::move($rootView, $owner.'/files_versions/'.$ownerPath, $user.'/files_trashbin/versions/'.$filename.'.d'.$timestamp);
311 311
 			} else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
312 312
 
313 313
 				foreach ($versions as $v) {
314 314
 					if ($owner !== $user) {
315
-						self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
315
+						self::copy($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $owner.'/files_trashbin/versions/'.$v['name'].'.v'.$v['version'].'.d'.$timestamp);
316 316
 					}
317
-					self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
317
+					self::move($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $user.'/files_trashbin/versions/'.$filename.'.v'.$v['version'].'.d'.$timestamp);
318 318
 				}
319 319
 			}
320 320
 		}
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 	 */
377 377
 	public static function restore($file, $filename, $timestamp) {
378 378
 		$user = User::getUser();
379
-		$view = new View('/' . $user);
379
+		$view = new View('/'.$user);
380 380
 
381 381
 		$location = '';
382 382
 		if ($timestamp) {
@@ -386,8 +386,8 @@  discard block
 block discarded – undo
386 386
 			} else {
387 387
 				// if location no longer exists, restore file in the root directory
388 388
 				if ($location !== '/' &&
389
-					(!$view->is_dir('files/' . $location) ||
390
-						!$view->isCreatable('files/' . $location))
389
+					(!$view->is_dir('files/'.$location) ||
390
+						!$view->isCreatable('files/'.$location))
391 391
 				) {
392 392
 					$location = '';
393 393
 				}
@@ -397,8 +397,8 @@  discard block
 block discarded – undo
397 397
 		// we need a  extension in case a file/dir with the same name already exists
398 398
 		$uniqueFilename = self::getUniqueFilename($location, $filename, $view);
399 399
 
400
-		$source = Filesystem::normalizePath('files_trashbin/files/' . $file);
401
-		$target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
400
+		$source = Filesystem::normalizePath('files_trashbin/files/'.$file);
401
+		$target = Filesystem::normalizePath('files/'.$location.'/'.$uniqueFilename);
402 402
 		if (!$view->file_exists($source)) {
403 403
 			return false;
404 404
 		}
@@ -410,10 +410,10 @@  discard block
 block discarded – undo
410 410
 		// handle the restore result
411 411
 		if ($restoreResult) {
412 412
 			$fakeRoot = $view->getRoot();
413
-			$view->chroot('/' . $user . '/files');
414
-			$view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
413
+			$view->chroot('/'.$user.'/files');
414
+			$view->touch('/'.$location.'/'.$uniqueFilename, $mtime);
415 415
 			$view->chroot($fakeRoot);
416
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
416
+			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename),
417 417
 				'trashPath' => Filesystem::normalizePath($file)));
418 418
 
419 419
 			self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
 			$user = User::getUser();
448 448
 			$rootView = new View('/');
449 449
 
450
-			$target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
450
+			$target = Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename);
451 451
 
452 452
 			list($owner, $ownerPath) = self::getUidAndFilename($target);
453 453
 
@@ -462,14 +462,14 @@  discard block
 block discarded – undo
462 462
 				$versionedFile = $file;
463 463
 			}
464 464
 
465
-			if ($view->is_dir('/files_trashbin/versions/' . $file)) {
466
-				$rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
465
+			if ($view->is_dir('/files_trashbin/versions/'.$file)) {
466
+				$rootView->rename(Filesystem::normalizePath($user.'/files_trashbin/versions/'.$file), Filesystem::normalizePath($owner.'/files_versions/'.$ownerPath));
467 467
 			} else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
468 468
 				foreach ($versions as $v) {
469 469
 					if ($timestamp) {
470
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
470
+						$rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v.'.d'.$timestamp, $owner.'/files_versions/'.$ownerPath.'.v'.$v);
471 471
 					} else {
472
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
472
+						$rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v, $owner.'/files_versions/'.$ownerPath.'.v'.$v);
473 473
 					}
474 474
 				}
475 475
 			}
@@ -481,12 +481,12 @@  discard block
 block discarded – undo
481 481
 	 */
482 482
 	public static function deleteAll() {
483 483
 		$user = User::getUser();
484
-		$view = new View('/' . $user);
484
+		$view = new View('/'.$user);
485 485
 		$fileInfos = $view->getDirectoryContent('files_trashbin/files');
486 486
 
487 487
 		// Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
488 488
 		$filePaths = array();
489
-		foreach($fileInfos as $fileInfo){
489
+		foreach ($fileInfos as $fileInfo) {
490 490
 			$filePaths[] = $view->getRelativePath($fileInfo->getPath());
491 491
 		}
492 492
 		unset($fileInfos); // save memory
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
 		\OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths));
496 496
 
497 497
 		// Single-File Hooks
498
-		foreach($filePaths as $path){
498
+		foreach ($filePaths as $path) {
499 499
 			self::emitTrashbinPreDelete($path);
500 500
 		}
501 501
 
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
 		\OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths));
509 509
 
510 510
 		// Single-File Hooks
511
-		foreach($filePaths as $path){
511
+		foreach ($filePaths as $path) {
512 512
 			self::emitTrashbinPostDelete($path);
513 513
 		}
514 514
 
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
 	 * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
523 523
 	 * @param string $path
524 524
 	 */
525
-	protected static function emitTrashbinPreDelete($path){
525
+	protected static function emitTrashbinPreDelete($path) {
526 526
 		\OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path));
527 527
 	}
528 528
 
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 	 * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
531 531
 	 * @param string $path
532 532
 	 */
533
-	protected static function emitTrashbinPostDelete($path){
533
+	protected static function emitTrashbinPostDelete($path) {
534 534
 		\OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path));
535 535
 	}
536 536
 
@@ -544,27 +544,27 @@  discard block
 block discarded – undo
544 544
 	 * @return int size of deleted files
545 545
 	 */
546 546
 	public static function delete($filename, $user, $timestamp = null) {
547
-		$view = new View('/' . $user);
547
+		$view = new View('/'.$user);
548 548
 		$size = 0;
549 549
 
550 550
 		if ($timestamp) {
551 551
 			$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
552 552
 			$query->execute(array($user, $filename, $timestamp));
553
-			$file = $filename . '.d' . $timestamp;
553
+			$file = $filename.'.d'.$timestamp;
554 554
 		} else {
555 555
 			$file = $filename;
556 556
 		}
557 557
 
558 558
 		$size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
559 559
 
560
-		if ($view->is_dir('/files_trashbin/files/' . $file)) {
561
-			$size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
560
+		if ($view->is_dir('/files_trashbin/files/'.$file)) {
561
+			$size += self::calculateSize(new View('/'.$user.'/files_trashbin/files/'.$file));
562 562
 		} else {
563
-			$size += $view->filesize('/files_trashbin/files/' . $file);
563
+			$size += $view->filesize('/files_trashbin/files/'.$file);
564 564
 		}
565
-		self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
566
-		$view->unlink('/files_trashbin/files/' . $file);
567
-		self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
565
+		self::emitTrashbinPreDelete('/files_trashbin/files/'.$file);
566
+		$view->unlink('/files_trashbin/files/'.$file);
567
+		self::emitTrashbinPostDelete('/files_trashbin/files/'.$file);
568 568
 
569 569
 		return $size;
570 570
 	}
@@ -580,17 +580,17 @@  discard block
 block discarded – undo
580 580
 	private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
581 581
 		$size = 0;
582 582
 		if (\OCP\App::isEnabled('files_versions')) {
583
-			if ($view->is_dir('files_trashbin/versions/' . $file)) {
584
-				$size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
585
-				$view->unlink('files_trashbin/versions/' . $file);
583
+			if ($view->is_dir('files_trashbin/versions/'.$file)) {
584
+				$size += self::calculateSize(new View('/'.$user.'/files_trashbin/versions/'.$file));
585
+				$view->unlink('files_trashbin/versions/'.$file);
586 586
 			} else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
587 587
 				foreach ($versions as $v) {
588 588
 					if ($timestamp) {
589
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
590
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
589
+						$size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp);
590
+						$view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp);
591 591
 					} else {
592
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
593
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
592
+						$size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v);
593
+						$view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v);
594 594
 					}
595 595
 				}
596 596
 			}
@@ -607,15 +607,15 @@  discard block
 block discarded – undo
607 607
 	 */
608 608
 	public static function file_exists($filename, $timestamp = null) {
609 609
 		$user = User::getUser();
610
-		$view = new View('/' . $user);
610
+		$view = new View('/'.$user);
611 611
 
612 612
 		if ($timestamp) {
613
-			$filename = $filename . '.d' . $timestamp;
613
+			$filename = $filename.'.d'.$timestamp;
614 614
 		} else {
615 615
 			$filename = $filename;
616 616
 		}
617 617
 
618
-		$target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
618
+		$target = Filesystem::normalizePath('files_trashbin/files/'.$filename);
619 619
 		return $view->file_exists($target);
620 620
 	}
621 621
 
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
 	private static function calculateFreeSpace($trashbinSize, $user) {
641 641
 		$softQuota = true;
642 642
 		$userObject = \OC::$server->getUserManager()->get($user);
643
-		if(is_null($userObject)) {
643
+		if (is_null($userObject)) {
644 644
 			return 0;
645 645
 		}
646 646
 		$quota = $userObject->getQuota();
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 		// subtract size of files and current trash bin size from quota
660 660
 		if ($softQuota) {
661 661
 			$userFolder = \OC::$server->getUserFolder($user);
662
-			if(is_null($userFolder)) {
662
+			if (is_null($userFolder)) {
663 663
 				return 0;
664 664
 			}
665 665
 			$free = $quota - $userFolder->getSize(); // remaining free space for user
@@ -741,7 +741,7 @@  discard block
 block discarded – undo
741 741
 			foreach ($files as $file) {
742 742
 				if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
743 743
 					$tmp = self::delete($file['name'], $user, $file['mtime']);
744
-					\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);
744
+					\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);
745 745
 					$availableSpace += $tmp;
746 746
 					$size += $tmp;
747 747
 				} else {
@@ -771,7 +771,7 @@  discard block
 block discarded – undo
771 771
 				$count++;
772 772
 				$size += self::delete($filename, $user, $timestamp);
773 773
 				\OC::$server->getLogger()->info(
774
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
774
+					'Remove "'.$filename.'" from trashbin because it exceeds max retention obligation term.',
775 775
 					['app' => 'files_trashbin']
776 776
 				);
777 777
 			} else {
@@ -797,16 +797,16 @@  discard block
 block discarded – undo
797 797
 			$view->mkdir($destination);
798 798
 			$view->touch($destination, $view->filemtime($source));
799 799
 			foreach ($view->getDirectoryContent($source) as $i) {
800
-				$pathDir = $source . '/' . $i['name'];
800
+				$pathDir = $source.'/'.$i['name'];
801 801
 				if ($view->is_dir($pathDir)) {
802
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
802
+					$size += self::copy_recursive($pathDir, $destination.'/'.$i['name'], $view);
803 803
 				} else {
804 804
 					$size += $view->filesize($pathDir);
805
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
805
+					$result = $view->copy($pathDir, $destination.'/'.$i['name']);
806 806
 					if (!$result) {
807 807
 						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
808 808
 					}
809
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
809
+					$view->touch($destination.'/'.$i['name'], $view->filemtime($pathDir));
810 810
 				}
811 811
 			}
812 812
 		} else {
@@ -828,7 +828,7 @@  discard block
 block discarded – undo
828 828
 	 * @return array
829 829
 	 */
830 830
 	private static function getVersionsFromTrash($filename, $timestamp, $user) {
831
-		$view = new View('/' . $user . '/files_trashbin/versions');
831
+		$view = new View('/'.$user.'/files_trashbin/versions');
832 832
 		$versions = array();
833 833
 
834 834
 		//force rescan of versions, local storage may not have updated the cache
@@ -841,10 +841,10 @@  discard block
 block discarded – undo
841 841
 
842 842
 		if ($timestamp) {
843 843
 			// fetch for old versions
844
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
844
+			$matches = $view->searchRaw($filename.'.v%.d'.$timestamp);
845 845
 			$offset = -strlen($timestamp) - 2;
846 846
 		} else {
847
-			$matches = $view->searchRaw($filename . '.v%');
847
+			$matches = $view->searchRaw($filename.'.v%');
848 848
 		}
849 849
 
850 850
 		if (is_array($matches)) {
@@ -874,18 +874,18 @@  discard block
 block discarded – undo
874 874
 		$name = pathinfo($filename, PATHINFO_FILENAME);
875 875
 		$l = \OC::$server->getL10N('files_trashbin');
876 876
 
877
-		$location = '/' . trim($location, '/');
877
+		$location = '/'.trim($location, '/');
878 878
 
879 879
 		// if extension is not empty we set a dot in front of it
880 880
 		if ($ext !== '') {
881
-			$ext = '.' . $ext;
881
+			$ext = '.'.$ext;
882 882
 		}
883 883
 
884
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
884
+		if ($view->file_exists('files'.$location.'/'.$filename)) {
885 885
 			$i = 2;
886
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
887
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
888
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
886
+			$uniqueName = $name." (".$l->t("restored").")".$ext;
887
+			while ($view->file_exists('files'.$location.'/'.$uniqueName)) {
888
+				$uniqueName = $name." (".$l->t("restored")." ".$i.")".$ext;
889 889
 				$i++;
890 890
 			}
891 891
 
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
 	 * @return integer size of the folder
903 903
 	 */
904 904
 	private static function calculateSize($view) {
905
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
905
+		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').$view->getAbsolutePath('');
906 906
 		if (!file_exists($root)) {
907 907
 			return 0;
908 908
 		}
@@ -933,7 +933,7 @@  discard block
 block discarded – undo
933 933
 	 * @return integer trash bin size
934 934
 	 */
935 935
 	private static function getTrashbinSize($user) {
936
-		$view = new View('/' . $user);
936
+		$view = new View('/'.$user);
937 937
 		$fileInfo = $view->getFileInfo('/files_trashbin');
938 938
 		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
939 939
 	}
@@ -962,7 +962,7 @@  discard block
 block discarded – undo
962 962
 	 */
963 963
 	public static function isEmpty($user) {
964 964
 
965
-		$view = new View('/' . $user . '/files_trashbin');
965
+		$view = new View('/'.$user.'/files_trashbin');
966 966
 		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
967 967
 			while ($file = readdir($dh)) {
968 968
 				if (!Filesystem::isIgnoredDir($file)) {
Please login to merge, or discard this patch.
apps/testing/locking/provisioning.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@
 block discarded – undo
80 80
 
81 81
 	/**
82 82
 	 * @param array $parameters
83
-	 * @return int
83
+	 * @return string
84 84
 	 */
85 85
 	protected function getPath($parameters) {
86 86
 		$node = \OC::$server->getRootFolder()
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -22,7 +22,6 @@
 block discarded – undo
22 22
 namespace OCA\Testing\Locking;
23 23
 
24 24
 use OC\Lock\DBLockingProvider;
25
-use OC\Lock\MemcacheLockingProvider;
26 25
 use OC\User\NoUserException;
27 26
 use OCP\AppFramework\Http;
28 27
 use OCP\Files\NotFoundException;
Please login to merge, or discard this patch.
Indentation   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -35,194 +35,194 @@
 block discarded – undo
35 35
 
36 36
 class Provisioning {
37 37
 
38
-	/** @var ILockingProvider */
39
-	protected $lockingProvider;
40
-
41
-	/** @var IDBConnection */
42
-	protected $connection;
43
-
44
-	/** @var IConfig */
45
-	protected $config;
46
-
47
-	/** @var IRequest */
48
-	protected $request;
49
-
50
-	/**
51
-	 * @param ILockingProvider $lockingProvider
52
-	 * @param IDBConnection $connection
53
-	 * @param IConfig $config
54
-	 * @param IRequest $request
55
-	 */
56
-	public function __construct(ILockingProvider $lockingProvider, IDBConnection $connection, IConfig $config, IRequest $request) {
57
-		$this->lockingProvider = $lockingProvider;
58
-		$this->connection = $connection;
59
-		$this->config = $config;
60
-		$this->request = $request;
61
-	}
62
-
63
-	/**
64
-	 * @return ILockingProvider
65
-	 */
66
-	protected function getLockingProvider() {
67
-		if ($this->lockingProvider instanceof DBLockingProvider) {
68
-			return \OC::$server->query('OCA\Testing\Locking\FakeDBLockingProvider');
69
-		} else {
70
-			throw new \RuntimeException('Lock provisioning is only possible using the DBLockingProvider');
71
-		}
72
-	}
73
-
74
-	/**
75
-	 * @param array $parameters
76
-	 * @return int
77
-	 */
78
-	protected function getType($parameters) {
79
-		return isset($parameters['type']) ? (int) $parameters['type'] : 0;
80
-	}
81
-
82
-	/**
83
-	 * @param array $parameters
84
-	 * @return int
85
-	 */
86
-	protected function getPath($parameters) {
87
-		$node = \OC::$server->getRootFolder()
88
-			->getUserFolder($parameters['user'])
89
-			->get($this->request->getParam('path'));
90
-		return 'files/' . md5($node->getStorage()->getId() . '::' . trim($node->getInternalPath(), '/'));
91
-	}
92
-
93
-	/**
94
-	 * @return \OC_OCS_Result
95
-	 */
96
-	public function isLockingEnabled() {
97
-		try {
98
-			$this->getLockingProvider();
99
-			return new \OC_OCS_Result(null, 100);
100
-		} catch (\RuntimeException $e) {
101
-			return new \OC_OCS_Result(null, Http::STATUS_NOT_IMPLEMENTED, $e->getMessage());
102
-		}
103
-	}
104
-
105
-	/**
106
-	 * @param array $parameters
107
-	 * @return \OC_OCS_Result
108
-	 */
109
-	public function acquireLock(array $parameters) {
110
-		try {
111
-			$path = $this->getPath($parameters);
112
-		} catch (NoUserException $e) {
113
-			return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'User not found');
114
-		} catch (NotFoundException $e) {
115
-			return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'Path not found');
116
-		}
117
-		$type = $this->getType($parameters);
118
-
119
-		$lockingProvider = $this->getLockingProvider();
120
-
121
-		try {
122
-			$lockingProvider->acquireLock($path, $type);
123
-			$this->config->setAppValue('testing', 'locking_' . $path, $type);
124
-			return new \OC_OCS_Result(null, 100);
125
-		} catch (LockedException $e) {
126
-			return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
127
-		}
128
-	}
129
-
130
-	/**
131
-	 * @param array $parameters
132
-	 * @return \OC_OCS_Result
133
-	 */
134
-	public function changeLock(array $parameters) {
135
-		try {
136
-			$path = $this->getPath($parameters);
137
-		} catch (NoUserException $e) {
138
-			return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'User not found');
139
-		} catch (NotFoundException $e) {
140
-			return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'Path not found');
141
-		}
142
-		$type = $this->getType($parameters);
143
-
144
-		$lockingProvider = $this->getLockingProvider();
145
-
146
-		try {
147
-			$lockingProvider->changeLock($path, $type);
148
-			$this->config->setAppValue('testing', 'locking_' . $path, $type);
149
-			return new \OC_OCS_Result(null, 100);
150
-		} catch (LockedException $e) {
151
-			return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
152
-		}
153
-	}
154
-
155
-	/**
156
-	 * @param array $parameters
157
-	 * @return \OC_OCS_Result
158
-	 */
159
-	public function releaseLock(array $parameters) {
160
-		try {
161
-			$path = $this->getPath($parameters);
162
-		} catch (NoUserException $e) {
163
-			return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'User not found');
164
-		} catch (NotFoundException $e) {
165
-			return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'Path not found');
166
-		}
167
-		$type = $this->getType($parameters);
168
-
169
-		$lockingProvider = $this->getLockingProvider();
170
-
171
-		try {
172
-			$lockingProvider->releaseLock($path, $type);
173
-			$this->config->deleteAppValue('testing', 'locking_' . $path);
174
-			return new \OC_OCS_Result(null, 100);
175
-		} catch (LockedException $e) {
176
-			return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
177
-		}
178
-	}
179
-
180
-	/**
181
-	 * @param array $parameters
182
-	 * @return \OC_OCS_Result
183
-	 */
184
-	public function isLocked(array $parameters) {
185
-		try {
186
-			$path = $this->getPath($parameters);
187
-		} catch (NoUserException $e) {
188
-			return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'User not found');
189
-		} catch (NotFoundException $e) {
190
-			return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'Path not found');
191
-		}
192
-		$type = $this->getType($parameters);
193
-
194
-		$lockingProvider = $this->getLockingProvider();
195
-
196
-		if ($lockingProvider->isLocked($path, $type)) {
197
-			return new \OC_OCS_Result(null, 100);
198
-		}
199
-
200
-		return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
201
-	}
202
-
203
-	/**
204
-	 * @param array $parameters
205
-	 * @return \OC_OCS_Result
206
-	 */
207
-	public function releaseAll(array $parameters) {
208
-		$type = $this->getType($parameters);
209
-
210
-		$lockingProvider = $this->getLockingProvider();
211
-
212
-		foreach ($this->config->getAppKeys('testing') as $lock) {
213
-			if (strpos($lock, 'locking_') === 0) {
214
-				$path = substr($lock, strlen('locking_'));
215
-
216
-				if ($type === ILockingProvider::LOCK_EXCLUSIVE && $this->config->getAppValue('testing', $lock) == ILockingProvider::LOCK_EXCLUSIVE) {
217
-					$lockingProvider->releaseLock($path, $this->config->getAppValue('testing', $lock));
218
-				} else if ($type === ILockingProvider::LOCK_SHARED && $this->config->getAppValue('testing', $lock) == ILockingProvider::LOCK_SHARED) {
219
-					$lockingProvider->releaseLock($path, $this->config->getAppValue('testing', $lock));
220
-				} else {
221
-					$lockingProvider->releaseLock($path, $this->config->getAppValue('testing', $lock));
222
-				}
223
-			}
224
-		}
225
-
226
-		return new \OC_OCS_Result(null, 100);
227
-	}
38
+    /** @var ILockingProvider */
39
+    protected $lockingProvider;
40
+
41
+    /** @var IDBConnection */
42
+    protected $connection;
43
+
44
+    /** @var IConfig */
45
+    protected $config;
46
+
47
+    /** @var IRequest */
48
+    protected $request;
49
+
50
+    /**
51
+     * @param ILockingProvider $lockingProvider
52
+     * @param IDBConnection $connection
53
+     * @param IConfig $config
54
+     * @param IRequest $request
55
+     */
56
+    public function __construct(ILockingProvider $lockingProvider, IDBConnection $connection, IConfig $config, IRequest $request) {
57
+        $this->lockingProvider = $lockingProvider;
58
+        $this->connection = $connection;
59
+        $this->config = $config;
60
+        $this->request = $request;
61
+    }
62
+
63
+    /**
64
+     * @return ILockingProvider
65
+     */
66
+    protected function getLockingProvider() {
67
+        if ($this->lockingProvider instanceof DBLockingProvider) {
68
+            return \OC::$server->query('OCA\Testing\Locking\FakeDBLockingProvider');
69
+        } else {
70
+            throw new \RuntimeException('Lock provisioning is only possible using the DBLockingProvider');
71
+        }
72
+    }
73
+
74
+    /**
75
+     * @param array $parameters
76
+     * @return int
77
+     */
78
+    protected function getType($parameters) {
79
+        return isset($parameters['type']) ? (int) $parameters['type'] : 0;
80
+    }
81
+
82
+    /**
83
+     * @param array $parameters
84
+     * @return int
85
+     */
86
+    protected function getPath($parameters) {
87
+        $node = \OC::$server->getRootFolder()
88
+            ->getUserFolder($parameters['user'])
89
+            ->get($this->request->getParam('path'));
90
+        return 'files/' . md5($node->getStorage()->getId() . '::' . trim($node->getInternalPath(), '/'));
91
+    }
92
+
93
+    /**
94
+     * @return \OC_OCS_Result
95
+     */
96
+    public function isLockingEnabled() {
97
+        try {
98
+            $this->getLockingProvider();
99
+            return new \OC_OCS_Result(null, 100);
100
+        } catch (\RuntimeException $e) {
101
+            return new \OC_OCS_Result(null, Http::STATUS_NOT_IMPLEMENTED, $e->getMessage());
102
+        }
103
+    }
104
+
105
+    /**
106
+     * @param array $parameters
107
+     * @return \OC_OCS_Result
108
+     */
109
+    public function acquireLock(array $parameters) {
110
+        try {
111
+            $path = $this->getPath($parameters);
112
+        } catch (NoUserException $e) {
113
+            return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'User not found');
114
+        } catch (NotFoundException $e) {
115
+            return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'Path not found');
116
+        }
117
+        $type = $this->getType($parameters);
118
+
119
+        $lockingProvider = $this->getLockingProvider();
120
+
121
+        try {
122
+            $lockingProvider->acquireLock($path, $type);
123
+            $this->config->setAppValue('testing', 'locking_' . $path, $type);
124
+            return new \OC_OCS_Result(null, 100);
125
+        } catch (LockedException $e) {
126
+            return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
127
+        }
128
+    }
129
+
130
+    /**
131
+     * @param array $parameters
132
+     * @return \OC_OCS_Result
133
+     */
134
+    public function changeLock(array $parameters) {
135
+        try {
136
+            $path = $this->getPath($parameters);
137
+        } catch (NoUserException $e) {
138
+            return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'User not found');
139
+        } catch (NotFoundException $e) {
140
+            return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'Path not found');
141
+        }
142
+        $type = $this->getType($parameters);
143
+
144
+        $lockingProvider = $this->getLockingProvider();
145
+
146
+        try {
147
+            $lockingProvider->changeLock($path, $type);
148
+            $this->config->setAppValue('testing', 'locking_' . $path, $type);
149
+            return new \OC_OCS_Result(null, 100);
150
+        } catch (LockedException $e) {
151
+            return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
152
+        }
153
+    }
154
+
155
+    /**
156
+     * @param array $parameters
157
+     * @return \OC_OCS_Result
158
+     */
159
+    public function releaseLock(array $parameters) {
160
+        try {
161
+            $path = $this->getPath($parameters);
162
+        } catch (NoUserException $e) {
163
+            return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'User not found');
164
+        } catch (NotFoundException $e) {
165
+            return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'Path not found');
166
+        }
167
+        $type = $this->getType($parameters);
168
+
169
+        $lockingProvider = $this->getLockingProvider();
170
+
171
+        try {
172
+            $lockingProvider->releaseLock($path, $type);
173
+            $this->config->deleteAppValue('testing', 'locking_' . $path);
174
+            return new \OC_OCS_Result(null, 100);
175
+        } catch (LockedException $e) {
176
+            return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
177
+        }
178
+    }
179
+
180
+    /**
181
+     * @param array $parameters
182
+     * @return \OC_OCS_Result
183
+     */
184
+    public function isLocked(array $parameters) {
185
+        try {
186
+            $path = $this->getPath($parameters);
187
+        } catch (NoUserException $e) {
188
+            return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'User not found');
189
+        } catch (NotFoundException $e) {
190
+            return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND, 'Path not found');
191
+        }
192
+        $type = $this->getType($parameters);
193
+
194
+        $lockingProvider = $this->getLockingProvider();
195
+
196
+        if ($lockingProvider->isLocked($path, $type)) {
197
+            return new \OC_OCS_Result(null, 100);
198
+        }
199
+
200
+        return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
201
+    }
202
+
203
+    /**
204
+     * @param array $parameters
205
+     * @return \OC_OCS_Result
206
+     */
207
+    public function releaseAll(array $parameters) {
208
+        $type = $this->getType($parameters);
209
+
210
+        $lockingProvider = $this->getLockingProvider();
211
+
212
+        foreach ($this->config->getAppKeys('testing') as $lock) {
213
+            if (strpos($lock, 'locking_') === 0) {
214
+                $path = substr($lock, strlen('locking_'));
215
+
216
+                if ($type === ILockingProvider::LOCK_EXCLUSIVE && $this->config->getAppValue('testing', $lock) == ILockingProvider::LOCK_EXCLUSIVE) {
217
+                    $lockingProvider->releaseLock($path, $this->config->getAppValue('testing', $lock));
218
+                } else if ($type === ILockingProvider::LOCK_SHARED && $this->config->getAppValue('testing', $lock) == ILockingProvider::LOCK_SHARED) {
219
+                    $lockingProvider->releaseLock($path, $this->config->getAppValue('testing', $lock));
220
+                } else {
221
+                    $lockingProvider->releaseLock($path, $this->config->getAppValue('testing', $lock));
222
+                }
223
+            }
224
+        }
225
+
226
+        return new \OC_OCS_Result(null, 100);
227
+    }
228 228
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 		$node = \OC::$server->getRootFolder()
88 88
 			->getUserFolder($parameters['user'])
89 89
 			->get($this->request->getParam('path'));
90
-		return 'files/' . md5($node->getStorage()->getId() . '::' . trim($node->getInternalPath(), '/'));
90
+		return 'files/'.md5($node->getStorage()->getId().'::'.trim($node->getInternalPath(), '/'));
91 91
 	}
92 92
 
93 93
 	/**
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 
121 121
 		try {
122 122
 			$lockingProvider->acquireLock($path, $type);
123
-			$this->config->setAppValue('testing', 'locking_' . $path, $type);
123
+			$this->config->setAppValue('testing', 'locking_'.$path, $type);
124 124
 			return new \OC_OCS_Result(null, 100);
125 125
 		} catch (LockedException $e) {
126 126
 			return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 
146 146
 		try {
147 147
 			$lockingProvider->changeLock($path, $type);
148
-			$this->config->setAppValue('testing', 'locking_' . $path, $type);
148
+			$this->config->setAppValue('testing', 'locking_'.$path, $type);
149 149
 			return new \OC_OCS_Result(null, 100);
150 150
 		} catch (LockedException $e) {
151 151
 			return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 
171 171
 		try {
172 172
 			$lockingProvider->releaseLock($path, $type);
173
-			$this->config->deleteAppValue('testing', 'locking_' . $path);
173
+			$this->config->deleteAppValue('testing', 'locking_'.$path);
174 174
 			return new \OC_OCS_Result(null, 100);
175 175
 		} catch (LockedException $e) {
176 176
 			return new \OC_OCS_Result(null, Http::STATUS_LOCKED);
Please login to merge, or discard this patch.
apps/updatenotification/lib/Notification/Notifier.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -102,6 +102,9 @@
 block discarded – undo
102 102
 		return \OC_App::getAppVersions();
103 103
 	}
104 104
 
105
+	/**
106
+	 * @param string $appId
107
+	 */
105 108
 	protected function getAppInfo($appId) {
106 109
 		return \OC_App::getAppInfo($appId);
107 110
 	}
Please login to merge, or discard this patch.
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -35,127 +35,127 @@
 block discarded – undo
35 35
 
36 36
 class Notifier implements INotifier {
37 37
 
38
-	/** @var IURLGenerator */
39
-	protected $url;
40
-
41
-	/** @var IManager */
42
-	protected $notificationManager;
43
-
44
-	/** @var IFactory */
45
-	protected $l10NFactory;
46
-
47
-	/** @var IUserSession */
48
-	protected $userSession;
49
-
50
-	/** @var IGroupManager */
51
-	protected $groupManager;
52
-
53
-	/** @var string[] */
54
-	protected $appVersions;
55
-
56
-	/**
57
-	 * Notifier constructor.
58
-	 *
59
-	 * @param IURLGenerator $url
60
-	 * @param IManager $notificationManager
61
-	 * @param IFactory $l10NFactory
62
-	 * @param IUserSession $userSession
63
-	 * @param IGroupManager $groupManager
64
-	 */
65
-	public function __construct(IURLGenerator $url, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) {
66
-		$this->url = $url;
67
-		$this->notificationManager = $notificationManager;
68
-		$this->l10NFactory = $l10NFactory;
69
-		$this->userSession = $userSession;
70
-		$this->groupManager = $groupManager;
71
-		$this->appVersions = $this->getAppVersions();
72
-	}
73
-
74
-	/**
75
-	 * @param INotification $notification
76
-	 * @param string $languageCode The code of the language that should be used to prepare the notification
77
-	 * @return INotification
78
-	 * @throws \InvalidArgumentException When the notification was not prepared by a notifier
79
-	 * @since 9.0.0
80
-	 */
81
-	public function prepare(INotification $notification, $languageCode) {
82
-		if ($notification->getApp() !== 'updatenotification') {
83
-			throw new \InvalidArgumentException();
84
-		}
85
-
86
-		$l = $this->l10NFactory->get('updatenotification', $languageCode);
87
-		if ($notification->getObjectType() === 'core') {
88
-			$this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions());
89
-
90
-			$parameters = $notification->getSubjectParameters();
91
-			$notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']]));
92
-
93
-			if ($this->isAdmin()) {
94
-				$notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater');
95
-			}
96
-		} else {
97
-			$appInfo = $this->getAppInfo($notification->getObjectType());
98
-			$appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name'];
99
-
100
-			if (isset($this->appVersions[$notification->getObjectType()])) {
101
-				$this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]);
102
-			}
103
-
104
-			$notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()]))
105
-				->setRichSubject($l->t('Update for {app} to version %s is available.', $notification->getObjectId()), [
106
-					'app' => [
107
-						'type' => 'app',
108
-						'id' => $notification->getObjectType(),
109
-						'name' => $appName,
110
-					]
111
-				]);
112
-
113
-			if ($this->isAdmin()) {
114
-				$notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps') . '#app-' . $notification->getObjectType());
115
-			}
116
-		}
117
-
118
-		$notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg')));
119
-
120
-		return $notification;
121
-	}
122
-
123
-	/**
124
-	 * Remove the notification and prevent rendering, when the update is installed
125
-	 *
126
-	 * @param INotification $notification
127
-	 * @param string $installedVersion
128
-	 * @throws \InvalidArgumentException When the update is already installed
129
-	 */
130
-	protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) {
131
-		if (version_compare($notification->getObjectId(), $installedVersion, '<=')) {
132
-			$this->notificationManager->markProcessed($notification);
133
-			throw new \InvalidArgumentException();
134
-		}
135
-	}
136
-
137
-	/**
138
-	 * @return bool
139
-	 */
140
-	protected function isAdmin() {
141
-		$user = $this->userSession->getUser();
142
-
143
-		if ($user instanceof IUser) {
144
-			return $this->groupManager->isAdmin($user->getUID());
145
-		}
146
-
147
-		return false;
148
-	}
149
-
150
-	protected function getCoreVersions() {
151
-		return implode('.', \OCP\Util::getVersion());
152
-	}
153
-
154
-	protected function getAppVersions() {
155
-		return \OC_App::getAppVersions();
156
-	}
157
-
158
-	protected function getAppInfo($appId) {
159
-		return \OC_App::getAppInfo($appId);
160
-	}
38
+    /** @var IURLGenerator */
39
+    protected $url;
40
+
41
+    /** @var IManager */
42
+    protected $notificationManager;
43
+
44
+    /** @var IFactory */
45
+    protected $l10NFactory;
46
+
47
+    /** @var IUserSession */
48
+    protected $userSession;
49
+
50
+    /** @var IGroupManager */
51
+    protected $groupManager;
52
+
53
+    /** @var string[] */
54
+    protected $appVersions;
55
+
56
+    /**
57
+     * Notifier constructor.
58
+     *
59
+     * @param IURLGenerator $url
60
+     * @param IManager $notificationManager
61
+     * @param IFactory $l10NFactory
62
+     * @param IUserSession $userSession
63
+     * @param IGroupManager $groupManager
64
+     */
65
+    public function __construct(IURLGenerator $url, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) {
66
+        $this->url = $url;
67
+        $this->notificationManager = $notificationManager;
68
+        $this->l10NFactory = $l10NFactory;
69
+        $this->userSession = $userSession;
70
+        $this->groupManager = $groupManager;
71
+        $this->appVersions = $this->getAppVersions();
72
+    }
73
+
74
+    /**
75
+     * @param INotification $notification
76
+     * @param string $languageCode The code of the language that should be used to prepare the notification
77
+     * @return INotification
78
+     * @throws \InvalidArgumentException When the notification was not prepared by a notifier
79
+     * @since 9.0.0
80
+     */
81
+    public function prepare(INotification $notification, $languageCode) {
82
+        if ($notification->getApp() !== 'updatenotification') {
83
+            throw new \InvalidArgumentException();
84
+        }
85
+
86
+        $l = $this->l10NFactory->get('updatenotification', $languageCode);
87
+        if ($notification->getObjectType() === 'core') {
88
+            $this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions());
89
+
90
+            $parameters = $notification->getSubjectParameters();
91
+            $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']]));
92
+
93
+            if ($this->isAdmin()) {
94
+                $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater');
95
+            }
96
+        } else {
97
+            $appInfo = $this->getAppInfo($notification->getObjectType());
98
+            $appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name'];
99
+
100
+            if (isset($this->appVersions[$notification->getObjectType()])) {
101
+                $this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]);
102
+            }
103
+
104
+            $notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()]))
105
+                ->setRichSubject($l->t('Update for {app} to version %s is available.', $notification->getObjectId()), [
106
+                    'app' => [
107
+                        'type' => 'app',
108
+                        'id' => $notification->getObjectType(),
109
+                        'name' => $appName,
110
+                    ]
111
+                ]);
112
+
113
+            if ($this->isAdmin()) {
114
+                $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps') . '#app-' . $notification->getObjectType());
115
+            }
116
+        }
117
+
118
+        $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg')));
119
+
120
+        return $notification;
121
+    }
122
+
123
+    /**
124
+     * Remove the notification and prevent rendering, when the update is installed
125
+     *
126
+     * @param INotification $notification
127
+     * @param string $installedVersion
128
+     * @throws \InvalidArgumentException When the update is already installed
129
+     */
130
+    protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) {
131
+        if (version_compare($notification->getObjectId(), $installedVersion, '<=')) {
132
+            $this->notificationManager->markProcessed($notification);
133
+            throw new \InvalidArgumentException();
134
+        }
135
+    }
136
+
137
+    /**
138
+     * @return bool
139
+     */
140
+    protected function isAdmin() {
141
+        $user = $this->userSession->getUser();
142
+
143
+        if ($user instanceof IUser) {
144
+            return $this->groupManager->isAdmin($user->getUID());
145
+        }
146
+
147
+        return false;
148
+    }
149
+
150
+    protected function getCoreVersions() {
151
+        return implode('.', \OCP\Util::getVersion());
152
+    }
153
+
154
+    protected function getAppVersions() {
155
+        return \OC_App::getAppVersions();
156
+    }
157
+
158
+    protected function getAppInfo($appId) {
159
+        return \OC_App::getAppInfo($appId);
160
+    }
161 161
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 			$notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']]));
92 92
 
93 93
 			if ($this->isAdmin()) {
94
-				$notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater');
94
+				$notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index').'#updater');
95 95
 			}
96 96
 		} else {
97 97
 			$appInfo = $this->getAppInfo($notification->getObjectType());
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 				]);
112 112
 
113 113
 			if ($this->isAdmin()) {
114
-				$notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps') . '#app-' . $notification->getObjectType());
114
+				$notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps').'#app-'.$notification->getObjectType());
115 115
 			}
116 116
 		}
117 117
 
Please login to merge, or discard this patch.