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