Completed
Pull Request — master (#9293)
by Blizzz
20:13
created
apps/files_external/lib/Lib/Storage/SMB.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -53,7 +53,6 @@
 block discarded – undo
53 53
 use OCP\Files\Storage\INotifyStorage;
54 54
 use OCP\Files\StorageNotAvailableException;
55 55
 use OCP\ILogger;
56
-use OCP\Util;
57 56
 
58 57
 class SMB extends Common implements INotifyStorage {
59 58
 	/**
Please login to merge, or discard this patch.
Indentation   +480 added lines, -480 removed lines patch added patch discarded remove patch
@@ -56,484 +56,484 @@
 block discarded – undo
56 56
 use OCP\Util;
57 57
 
58 58
 class SMB extends Common implements INotifyStorage {
59
-	/**
60
-	 * @var \Icewind\SMB\Server
61
-	 */
62
-	protected $server;
63
-
64
-	/**
65
-	 * @var \Icewind\SMB\Share
66
-	 */
67
-	protected $share;
68
-
69
-	/**
70
-	 * @var string
71
-	 */
72
-	protected $root;
73
-
74
-	/**
75
-	 * @var \Icewind\SMB\FileInfo[]
76
-	 */
77
-	protected $statCache;
78
-
79
-	public function __construct($params) {
80
-		if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
81
-			if (Server::NativeAvailable()) {
82
-				$this->server = new NativeServer($params['host'], $params['user'], $params['password']);
83
-			} else {
84
-				$this->server = new Server($params['host'], $params['user'], $params['password']);
85
-			}
86
-			$this->share = $this->server->getShare(trim($params['share'], '/'));
87
-
88
-			$this->root = $params['root'] ?? '/';
89
-			$this->root = '/' . ltrim($this->root, '/');
90
-			$this->root = rtrim($this->root, '/') . '/';
91
-		} else {
92
-			throw new \Exception('Invalid configuration');
93
-		}
94
-		$this->statCache = new CappedMemoryCache();
95
-		parent::__construct($params);
96
-	}
97
-
98
-	/**
99
-	 * @return string
100
-	 */
101
-	public function getId() {
102
-		// FIXME: double slash to keep compatible with the old storage ids,
103
-		// failure to do so will lead to creation of a new storage id and
104
-		// loss of shares from the storage
105
-		return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
106
-	}
107
-
108
-	/**
109
-	 * @param string $path
110
-	 * @return string
111
-	 */
112
-	protected function buildPath($path) {
113
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
114
-	}
115
-
116
-	protected function relativePath($fullPath) {
117
-		if ($fullPath === $this->root) {
118
-			return '';
119
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
120
-			return substr($fullPath, strlen($this->root));
121
-		} else {
122
-			return null;
123
-		}
124
-	}
125
-
126
-	/**
127
-	 * @param string $path
128
-	 * @return \Icewind\SMB\IFileInfo
129
-	 * @throws StorageNotAvailableException
130
-	 */
131
-	protected function getFileInfo($path) {
132
-		try {
133
-			$path = $this->buildPath($path);
134
-			if (!isset($this->statCache[$path])) {
135
-				$this->statCache[$path] = $this->share->stat($path);
136
-			}
137
-			return $this->statCache[$path];
138
-		} catch (ConnectException $e) {
139
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
140
-		}
141
-	}
142
-
143
-	/**
144
-	 * @param string $path
145
-	 * @return \Icewind\SMB\IFileInfo[]
146
-	 * @throws StorageNotAvailableException
147
-	 */
148
-	protected function getFolderContents($path) {
149
-		try {
150
-			$path = $this->buildPath($path);
151
-			$files = $this->share->dir($path);
152
-			foreach ($files as $file) {
153
-				$this->statCache[$path . '/' . $file->getName()] = $file;
154
-			}
155
-			return array_filter($files, function (IFileInfo $file) {
156
-				try {
157
-					return !$file->isHidden();
158
-				} catch (ForbiddenException $e) {
159
-					return false;
160
-				} catch (NotFoundException $e) {
161
-					return false;
162
-				}
163
-			});
164
-		} catch (ConnectException $e) {
165
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
166
-		}
167
-	}
168
-
169
-	/**
170
-	 * @param \Icewind\SMB\IFileInfo $info
171
-	 * @return array
172
-	 */
173
-	protected function formatInfo($info) {
174
-		$result = [
175
-			'size' => $info->getSize(),
176
-			'mtime' => $info->getMTime(),
177
-		];
178
-		if ($info->isDirectory()) {
179
-			$result['type'] = 'dir';
180
-		} else {
181
-			$result['type'] = 'file';
182
-		}
183
-		return $result;
184
-	}
185
-
186
-	/**
187
-	 * Rename the files. If the source or the target is the root, the rename won't happen.
188
-	 *
189
-	 * @param string $source the old name of the path
190
-	 * @param string $target the new name of the path
191
-	 * @return bool true if the rename is successful, false otherwise
192
-	 */
193
-	public function rename($source, $target) {
194
-		if ($this->isRootDir($source) || $this->isRootDir($target)) {
195
-			return false;
196
-		}
197
-
198
-		$absoluteSource = $this->buildPath($source);
199
-		$absoluteTarget = $this->buildPath($target);
200
-		try {
201
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
202
-		} catch (AlreadyExistsException $e) {
203
-			$this->remove($target);
204
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
205
-		} catch (\Exception $e) {
206
-			\OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
207
-			return false;
208
-		}
209
-		unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
210
-		return $result;
211
-	}
212
-
213
-	public function stat($path) {
214
-		try {
215
-			$result = $this->formatInfo($this->getFileInfo($path));
216
-		} catch (ForbiddenException $e) {
217
-			return false;
218
-		} catch (NotFoundException $e) {
219
-			return false;
220
-		}
221
-		if ($this->remoteIsShare() && $this->isRootDir($path)) {
222
-			$result['mtime'] = $this->shareMTime();
223
-		}
224
-		return $result;
225
-	}
226
-
227
-	/**
228
-	 * get the best guess for the modification time of the share
229
-	 *
230
-	 * @return int
231
-	 */
232
-	private function shareMTime() {
233
-		$highestMTime = 0;
234
-		$files = $this->share->dir($this->root);
235
-		foreach ($files as $fileInfo) {
236
-			try {
237
-				if ($fileInfo->getMTime() > $highestMTime) {
238
-					$highestMTime = $fileInfo->getMTime();
239
-				}
240
-			} catch (NotFoundException $e) {
241
-				// Ignore this, can happen on unavailable DFS shares
242
-			}
243
-		}
244
-		return $highestMTime;
245
-	}
246
-
247
-	/**
248
-	 * Check if the path is our root dir (not the smb one)
249
-	 *
250
-	 * @param string $path the path
251
-	 * @return bool
252
-	 */
253
-	private function isRootDir($path) {
254
-		return $path === '' || $path === '/' || $path === '.';
255
-	}
256
-
257
-	/**
258
-	 * Check if our root points to a smb share
259
-	 *
260
-	 * @return bool true if our root points to a share false otherwise
261
-	 */
262
-	private function remoteIsShare() {
263
-		return $this->share->getName() && (!$this->root || $this->root === '/');
264
-	}
265
-
266
-	/**
267
-	 * @param string $path
268
-	 * @return bool
269
-	 */
270
-	public function unlink($path) {
271
-		if ($this->isRootDir($path)) {
272
-			return false;
273
-		}
274
-
275
-		try {
276
-			if ($this->is_dir($path)) {
277
-				return $this->rmdir($path);
278
-			} else {
279
-				$path = $this->buildPath($path);
280
-				unset($this->statCache[$path]);
281
-				$this->share->del($path);
282
-				return true;
283
-			}
284
-		} catch (NotFoundException $e) {
285
-			return false;
286
-		} catch (ForbiddenException $e) {
287
-			return false;
288
-		} catch (ConnectException $e) {
289
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
290
-		}
291
-	}
292
-
293
-	/**
294
-	 * check if a file or folder has been updated since $time
295
-	 *
296
-	 * @param string $path
297
-	 * @param int $time
298
-	 * @return bool
299
-	 */
300
-	public function hasUpdated($path, $time) {
301
-		if (!$path and $this->root === '/') {
302
-			// mtime doesn't work for shares, but giving the nature of the backend,
303
-			// doing a full update is still just fast enough
304
-			return true;
305
-		} else {
306
-			$actualTime = $this->filemtime($path);
307
-			return $actualTime > $time;
308
-		}
309
-	}
310
-
311
-	/**
312
-	 * @param string $path
313
-	 * @param string $mode
314
-	 * @return resource|false
315
-	 */
316
-	public function fopen($path, $mode) {
317
-		$fullPath = $this->buildPath($path);
318
-		try {
319
-			switch ($mode) {
320
-				case 'r':
321
-				case 'rb':
322
-					if (!$this->file_exists($path)) {
323
-						return false;
324
-					}
325
-					return $this->share->read($fullPath);
326
-				case 'w':
327
-				case 'wb':
328
-					$source = $this->share->write($fullPath);
329
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
330
-						unset($this->statCache[$fullPath]);
331
-					});
332
-				case 'a':
333
-				case 'ab':
334
-				case 'r+':
335
-				case 'w+':
336
-				case 'wb+':
337
-				case 'a+':
338
-				case 'x':
339
-				case 'x+':
340
-				case 'c':
341
-				case 'c+':
342
-					//emulate these
343
-					if (strrpos($path, '.') !== false) {
344
-						$ext = substr($path, strrpos($path, '.'));
345
-					} else {
346
-						$ext = '';
347
-					}
348
-					if ($this->file_exists($path)) {
349
-						if (!$this->isUpdatable($path)) {
350
-							return false;
351
-						}
352
-						$tmpFile = $this->getCachedFile($path);
353
-					} else {
354
-						if (!$this->isCreatable(dirname($path))) {
355
-							return false;
356
-						}
357
-						$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
358
-					}
359
-					$source = fopen($tmpFile, $mode);
360
-					$share = $this->share;
361
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
362
-						unset($this->statCache[$fullPath]);
363
-						$share->put($tmpFile, $fullPath);
364
-						unlink($tmpFile);
365
-					});
366
-			}
367
-			return false;
368
-		} catch (NotFoundException $e) {
369
-			return false;
370
-		} catch (ForbiddenException $e) {
371
-			return false;
372
-		} catch (ConnectException $e) {
373
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
374
-		}
375
-	}
376
-
377
-	public function rmdir($path) {
378
-		if ($this->isRootDir($path)) {
379
-			return false;
380
-		}
381
-
382
-		try {
383
-			$this->statCache = array();
384
-			$content = $this->share->dir($this->buildPath($path));
385
-			foreach ($content as $file) {
386
-				if ($file->isDirectory()) {
387
-					$this->rmdir($path . '/' . $file->getName());
388
-				} else {
389
-					$this->share->del($file->getPath());
390
-				}
391
-			}
392
-			$this->share->rmdir($this->buildPath($path));
393
-			return true;
394
-		} catch (NotFoundException $e) {
395
-			return false;
396
-		} catch (ForbiddenException $e) {
397
-			return false;
398
-		} catch (ConnectException $e) {
399
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
400
-		}
401
-	}
402
-
403
-	public function touch($path, $time = null) {
404
-		try {
405
-			if (!$this->file_exists($path)) {
406
-				$fh = $this->share->write($this->buildPath($path));
407
-				fclose($fh);
408
-				return true;
409
-			}
410
-			return false;
411
-		} catch (ConnectException $e) {
412
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
413
-		}
414
-	}
415
-
416
-	public function opendir($path) {
417
-		try {
418
-			$files = $this->getFolderContents($path);
419
-		} catch (NotFoundException $e) {
420
-			return false;
421
-		} catch (ForbiddenException $e) {
422
-			return false;
423
-		}
424
-		$names = array_map(function ($info) {
425
-			/** @var \Icewind\SMB\IFileInfo $info */
426
-			return $info->getName();
427
-		}, $files);
428
-		return IteratorDirectory::wrap($names);
429
-	}
430
-
431
-	public function filetype($path) {
432
-		try {
433
-			return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
434
-		} catch (NotFoundException $e) {
435
-			return false;
436
-		} catch (ForbiddenException $e) {
437
-			return false;
438
-		}
439
-	}
440
-
441
-	public function mkdir($path) {
442
-		$path = $this->buildPath($path);
443
-		try {
444
-			$this->share->mkdir($path);
445
-			return true;
446
-		} catch (ConnectException $e) {
447
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
448
-		} catch (Exception $e) {
449
-			return false;
450
-		}
451
-	}
452
-
453
-	public function file_exists($path) {
454
-		try {
455
-			$this->getFileInfo($path);
456
-			return true;
457
-		} catch (NotFoundException $e) {
458
-			return false;
459
-		} catch (ForbiddenException $e) {
460
-			return false;
461
-		} catch (ConnectException $e) {
462
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
463
-		}
464
-	}
465
-
466
-	public function isReadable($path) {
467
-		try {
468
-			$info = $this->getFileInfo($path);
469
-			return !$info->isHidden();
470
-		} catch (NotFoundException $e) {
471
-			return false;
472
-		} catch (ForbiddenException $e) {
473
-			return false;
474
-		}
475
-	}
476
-
477
-	public function isUpdatable($path) {
478
-		try {
479
-			$info = $this->getFileInfo($path);
480
-			// following windows behaviour for read-only folders: they can be written into
481
-			// (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
482
-			return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
483
-		} catch (NotFoundException $e) {
484
-			return false;
485
-		} catch (ForbiddenException $e) {
486
-			return false;
487
-		}
488
-	}
489
-
490
-	public function isDeletable($path) {
491
-		try {
492
-			$info = $this->getFileInfo($path);
493
-			return !$info->isHidden() && !$info->isReadOnly();
494
-		} catch (NotFoundException $e) {
495
-			return false;
496
-		} catch (ForbiddenException $e) {
497
-			return false;
498
-		}
499
-	}
500
-
501
-	/**
502
-	 * check if smbclient is installed
503
-	 */
504
-	public static function checkDependencies() {
505
-		return (
506
-			(bool)\OC_Helper::findBinaryPath('smbclient')
507
-			|| Server::NativeAvailable()
508
-		) ? true : ['smbclient'];
509
-	}
510
-
511
-	/**
512
-	 * Test a storage for availability
513
-	 *
514
-	 * @return bool
515
-	 */
516
-	public function test() {
517
-		try {
518
-			return parent::test();
519
-		} catch (Exception $e) {
520
-			return false;
521
-		}
522
-	}
523
-
524
-	public function listen($path, callable $callback) {
525
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
526
-			if ($change instanceof IRenameChange) {
527
-				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
528
-			} else {
529
-				return $callback($change->getType(), $change->getPath());
530
-			}
531
-		});
532
-	}
533
-
534
-	public function notify($path) {
535
-		$path = '/' . ltrim($path, '/');
536
-		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
537
-		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
538
-	}
59
+    /**
60
+     * @var \Icewind\SMB\Server
61
+     */
62
+    protected $server;
63
+
64
+    /**
65
+     * @var \Icewind\SMB\Share
66
+     */
67
+    protected $share;
68
+
69
+    /**
70
+     * @var string
71
+     */
72
+    protected $root;
73
+
74
+    /**
75
+     * @var \Icewind\SMB\FileInfo[]
76
+     */
77
+    protected $statCache;
78
+
79
+    public function __construct($params) {
80
+        if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
81
+            if (Server::NativeAvailable()) {
82
+                $this->server = new NativeServer($params['host'], $params['user'], $params['password']);
83
+            } else {
84
+                $this->server = new Server($params['host'], $params['user'], $params['password']);
85
+            }
86
+            $this->share = $this->server->getShare(trim($params['share'], '/'));
87
+
88
+            $this->root = $params['root'] ?? '/';
89
+            $this->root = '/' . ltrim($this->root, '/');
90
+            $this->root = rtrim($this->root, '/') . '/';
91
+        } else {
92
+            throw new \Exception('Invalid configuration');
93
+        }
94
+        $this->statCache = new CappedMemoryCache();
95
+        parent::__construct($params);
96
+    }
97
+
98
+    /**
99
+     * @return string
100
+     */
101
+    public function getId() {
102
+        // FIXME: double slash to keep compatible with the old storage ids,
103
+        // failure to do so will lead to creation of a new storage id and
104
+        // loss of shares from the storage
105
+        return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
106
+    }
107
+
108
+    /**
109
+     * @param string $path
110
+     * @return string
111
+     */
112
+    protected function buildPath($path) {
113
+        return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
114
+    }
115
+
116
+    protected function relativePath($fullPath) {
117
+        if ($fullPath === $this->root) {
118
+            return '';
119
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
120
+            return substr($fullPath, strlen($this->root));
121
+        } else {
122
+            return null;
123
+        }
124
+    }
125
+
126
+    /**
127
+     * @param string $path
128
+     * @return \Icewind\SMB\IFileInfo
129
+     * @throws StorageNotAvailableException
130
+     */
131
+    protected function getFileInfo($path) {
132
+        try {
133
+            $path = $this->buildPath($path);
134
+            if (!isset($this->statCache[$path])) {
135
+                $this->statCache[$path] = $this->share->stat($path);
136
+            }
137
+            return $this->statCache[$path];
138
+        } catch (ConnectException $e) {
139
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
140
+        }
141
+    }
142
+
143
+    /**
144
+     * @param string $path
145
+     * @return \Icewind\SMB\IFileInfo[]
146
+     * @throws StorageNotAvailableException
147
+     */
148
+    protected function getFolderContents($path) {
149
+        try {
150
+            $path = $this->buildPath($path);
151
+            $files = $this->share->dir($path);
152
+            foreach ($files as $file) {
153
+                $this->statCache[$path . '/' . $file->getName()] = $file;
154
+            }
155
+            return array_filter($files, function (IFileInfo $file) {
156
+                try {
157
+                    return !$file->isHidden();
158
+                } catch (ForbiddenException $e) {
159
+                    return false;
160
+                } catch (NotFoundException $e) {
161
+                    return false;
162
+                }
163
+            });
164
+        } catch (ConnectException $e) {
165
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
166
+        }
167
+    }
168
+
169
+    /**
170
+     * @param \Icewind\SMB\IFileInfo $info
171
+     * @return array
172
+     */
173
+    protected function formatInfo($info) {
174
+        $result = [
175
+            'size' => $info->getSize(),
176
+            'mtime' => $info->getMTime(),
177
+        ];
178
+        if ($info->isDirectory()) {
179
+            $result['type'] = 'dir';
180
+        } else {
181
+            $result['type'] = 'file';
182
+        }
183
+        return $result;
184
+    }
185
+
186
+    /**
187
+     * Rename the files. If the source or the target is the root, the rename won't happen.
188
+     *
189
+     * @param string $source the old name of the path
190
+     * @param string $target the new name of the path
191
+     * @return bool true if the rename is successful, false otherwise
192
+     */
193
+    public function rename($source, $target) {
194
+        if ($this->isRootDir($source) || $this->isRootDir($target)) {
195
+            return false;
196
+        }
197
+
198
+        $absoluteSource = $this->buildPath($source);
199
+        $absoluteTarget = $this->buildPath($target);
200
+        try {
201
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
202
+        } catch (AlreadyExistsException $e) {
203
+            $this->remove($target);
204
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
205
+        } catch (\Exception $e) {
206
+            \OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
207
+            return false;
208
+        }
209
+        unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
210
+        return $result;
211
+    }
212
+
213
+    public function stat($path) {
214
+        try {
215
+            $result = $this->formatInfo($this->getFileInfo($path));
216
+        } catch (ForbiddenException $e) {
217
+            return false;
218
+        } catch (NotFoundException $e) {
219
+            return false;
220
+        }
221
+        if ($this->remoteIsShare() && $this->isRootDir($path)) {
222
+            $result['mtime'] = $this->shareMTime();
223
+        }
224
+        return $result;
225
+    }
226
+
227
+    /**
228
+     * get the best guess for the modification time of the share
229
+     *
230
+     * @return int
231
+     */
232
+    private function shareMTime() {
233
+        $highestMTime = 0;
234
+        $files = $this->share->dir($this->root);
235
+        foreach ($files as $fileInfo) {
236
+            try {
237
+                if ($fileInfo->getMTime() > $highestMTime) {
238
+                    $highestMTime = $fileInfo->getMTime();
239
+                }
240
+            } catch (NotFoundException $e) {
241
+                // Ignore this, can happen on unavailable DFS shares
242
+            }
243
+        }
244
+        return $highestMTime;
245
+    }
246
+
247
+    /**
248
+     * Check if the path is our root dir (not the smb one)
249
+     *
250
+     * @param string $path the path
251
+     * @return bool
252
+     */
253
+    private function isRootDir($path) {
254
+        return $path === '' || $path === '/' || $path === '.';
255
+    }
256
+
257
+    /**
258
+     * Check if our root points to a smb share
259
+     *
260
+     * @return bool true if our root points to a share false otherwise
261
+     */
262
+    private function remoteIsShare() {
263
+        return $this->share->getName() && (!$this->root || $this->root === '/');
264
+    }
265
+
266
+    /**
267
+     * @param string $path
268
+     * @return bool
269
+     */
270
+    public function unlink($path) {
271
+        if ($this->isRootDir($path)) {
272
+            return false;
273
+        }
274
+
275
+        try {
276
+            if ($this->is_dir($path)) {
277
+                return $this->rmdir($path);
278
+            } else {
279
+                $path = $this->buildPath($path);
280
+                unset($this->statCache[$path]);
281
+                $this->share->del($path);
282
+                return true;
283
+            }
284
+        } catch (NotFoundException $e) {
285
+            return false;
286
+        } catch (ForbiddenException $e) {
287
+            return false;
288
+        } catch (ConnectException $e) {
289
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
290
+        }
291
+    }
292
+
293
+    /**
294
+     * check if a file or folder has been updated since $time
295
+     *
296
+     * @param string $path
297
+     * @param int $time
298
+     * @return bool
299
+     */
300
+    public function hasUpdated($path, $time) {
301
+        if (!$path and $this->root === '/') {
302
+            // mtime doesn't work for shares, but giving the nature of the backend,
303
+            // doing a full update is still just fast enough
304
+            return true;
305
+        } else {
306
+            $actualTime = $this->filemtime($path);
307
+            return $actualTime > $time;
308
+        }
309
+    }
310
+
311
+    /**
312
+     * @param string $path
313
+     * @param string $mode
314
+     * @return resource|false
315
+     */
316
+    public function fopen($path, $mode) {
317
+        $fullPath = $this->buildPath($path);
318
+        try {
319
+            switch ($mode) {
320
+                case 'r':
321
+                case 'rb':
322
+                    if (!$this->file_exists($path)) {
323
+                        return false;
324
+                    }
325
+                    return $this->share->read($fullPath);
326
+                case 'w':
327
+                case 'wb':
328
+                    $source = $this->share->write($fullPath);
329
+                    return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
330
+                        unset($this->statCache[$fullPath]);
331
+                    });
332
+                case 'a':
333
+                case 'ab':
334
+                case 'r+':
335
+                case 'w+':
336
+                case 'wb+':
337
+                case 'a+':
338
+                case 'x':
339
+                case 'x+':
340
+                case 'c':
341
+                case 'c+':
342
+                    //emulate these
343
+                    if (strrpos($path, '.') !== false) {
344
+                        $ext = substr($path, strrpos($path, '.'));
345
+                    } else {
346
+                        $ext = '';
347
+                    }
348
+                    if ($this->file_exists($path)) {
349
+                        if (!$this->isUpdatable($path)) {
350
+                            return false;
351
+                        }
352
+                        $tmpFile = $this->getCachedFile($path);
353
+                    } else {
354
+                        if (!$this->isCreatable(dirname($path))) {
355
+                            return false;
356
+                        }
357
+                        $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
358
+                    }
359
+                    $source = fopen($tmpFile, $mode);
360
+                    $share = $this->share;
361
+                    return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
362
+                        unset($this->statCache[$fullPath]);
363
+                        $share->put($tmpFile, $fullPath);
364
+                        unlink($tmpFile);
365
+                    });
366
+            }
367
+            return false;
368
+        } catch (NotFoundException $e) {
369
+            return false;
370
+        } catch (ForbiddenException $e) {
371
+            return false;
372
+        } catch (ConnectException $e) {
373
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
374
+        }
375
+    }
376
+
377
+    public function rmdir($path) {
378
+        if ($this->isRootDir($path)) {
379
+            return false;
380
+        }
381
+
382
+        try {
383
+            $this->statCache = array();
384
+            $content = $this->share->dir($this->buildPath($path));
385
+            foreach ($content as $file) {
386
+                if ($file->isDirectory()) {
387
+                    $this->rmdir($path . '/' . $file->getName());
388
+                } else {
389
+                    $this->share->del($file->getPath());
390
+                }
391
+            }
392
+            $this->share->rmdir($this->buildPath($path));
393
+            return true;
394
+        } catch (NotFoundException $e) {
395
+            return false;
396
+        } catch (ForbiddenException $e) {
397
+            return false;
398
+        } catch (ConnectException $e) {
399
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
400
+        }
401
+    }
402
+
403
+    public function touch($path, $time = null) {
404
+        try {
405
+            if (!$this->file_exists($path)) {
406
+                $fh = $this->share->write($this->buildPath($path));
407
+                fclose($fh);
408
+                return true;
409
+            }
410
+            return false;
411
+        } catch (ConnectException $e) {
412
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
413
+        }
414
+    }
415
+
416
+    public function opendir($path) {
417
+        try {
418
+            $files = $this->getFolderContents($path);
419
+        } catch (NotFoundException $e) {
420
+            return false;
421
+        } catch (ForbiddenException $e) {
422
+            return false;
423
+        }
424
+        $names = array_map(function ($info) {
425
+            /** @var \Icewind\SMB\IFileInfo $info */
426
+            return $info->getName();
427
+        }, $files);
428
+        return IteratorDirectory::wrap($names);
429
+    }
430
+
431
+    public function filetype($path) {
432
+        try {
433
+            return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
434
+        } catch (NotFoundException $e) {
435
+            return false;
436
+        } catch (ForbiddenException $e) {
437
+            return false;
438
+        }
439
+    }
440
+
441
+    public function mkdir($path) {
442
+        $path = $this->buildPath($path);
443
+        try {
444
+            $this->share->mkdir($path);
445
+            return true;
446
+        } catch (ConnectException $e) {
447
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
448
+        } catch (Exception $e) {
449
+            return false;
450
+        }
451
+    }
452
+
453
+    public function file_exists($path) {
454
+        try {
455
+            $this->getFileInfo($path);
456
+            return true;
457
+        } catch (NotFoundException $e) {
458
+            return false;
459
+        } catch (ForbiddenException $e) {
460
+            return false;
461
+        } catch (ConnectException $e) {
462
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
463
+        }
464
+    }
465
+
466
+    public function isReadable($path) {
467
+        try {
468
+            $info = $this->getFileInfo($path);
469
+            return !$info->isHidden();
470
+        } catch (NotFoundException $e) {
471
+            return false;
472
+        } catch (ForbiddenException $e) {
473
+            return false;
474
+        }
475
+    }
476
+
477
+    public function isUpdatable($path) {
478
+        try {
479
+            $info = $this->getFileInfo($path);
480
+            // following windows behaviour for read-only folders: they can be written into
481
+            // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
482
+            return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
483
+        } catch (NotFoundException $e) {
484
+            return false;
485
+        } catch (ForbiddenException $e) {
486
+            return false;
487
+        }
488
+    }
489
+
490
+    public function isDeletable($path) {
491
+        try {
492
+            $info = $this->getFileInfo($path);
493
+            return !$info->isHidden() && !$info->isReadOnly();
494
+        } catch (NotFoundException $e) {
495
+            return false;
496
+        } catch (ForbiddenException $e) {
497
+            return false;
498
+        }
499
+    }
500
+
501
+    /**
502
+     * check if smbclient is installed
503
+     */
504
+    public static function checkDependencies() {
505
+        return (
506
+            (bool)\OC_Helper::findBinaryPath('smbclient')
507
+            || Server::NativeAvailable()
508
+        ) ? true : ['smbclient'];
509
+    }
510
+
511
+    /**
512
+     * Test a storage for availability
513
+     *
514
+     * @return bool
515
+     */
516
+    public function test() {
517
+        try {
518
+            return parent::test();
519
+        } catch (Exception $e) {
520
+            return false;
521
+        }
522
+    }
523
+
524
+    public function listen($path, callable $callback) {
525
+        $this->notify($path)->listen(function (IChange $change) use ($callback) {
526
+            if ($change instanceof IRenameChange) {
527
+                return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
528
+            } else {
529
+                return $callback($change->getType(), $change->getPath());
530
+            }
531
+        });
532
+    }
533
+
534
+    public function notify($path) {
535
+        $path = '/' . ltrim($path, '/');
536
+        $shareNotifyHandler = $this->share->notify($this->buildPath($path));
537
+        return new SMBNotifyHandler($shareNotifyHandler, $this->root);
538
+    }
539 539
 }
Please login to merge, or discard this patch.
lib/private/App/AppStore/Fetcher/Fetcher.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -36,7 +36,6 @@
 block discarded – undo
36 36
 use OCP\Http\Client\IClientService;
37 37
 use OCP\IConfig;
38 38
 use OCP\ILogger;
39
-use OCP\Util;
40 39
 
41 40
 abstract class Fetcher {
42 41
 	const INVALIDATE_AFTER_SECONDS = 300;
Please login to merge, or discard this patch.
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -39,162 +39,162 @@
 block discarded – undo
39 39
 use OCP\Util;
40 40
 
41 41
 abstract class Fetcher {
42
-	const INVALIDATE_AFTER_SECONDS = 300;
43
-
44
-	/** @var IAppData */
45
-	protected $appData;
46
-	/** @var IClientService */
47
-	protected $clientService;
48
-	/** @var ITimeFactory */
49
-	protected $timeFactory;
50
-	/** @var IConfig */
51
-	protected $config;
52
-	/** @var Ilogger */
53
-	protected $logger;
54
-	/** @var string */
55
-	protected $fileName;
56
-	/** @var string */
57
-	protected $endpointUrl;
58
-	/** @var string */
59
-	protected $version;
60
-
61
-	/**
62
-	 * @param Factory $appDataFactory
63
-	 * @param IClientService $clientService
64
-	 * @param ITimeFactory $timeFactory
65
-	 * @param IConfig $config
66
-	 * @param ILogger $logger
67
-	 */
68
-	public function __construct(Factory $appDataFactory,
69
-								IClientService $clientService,
70
-								ITimeFactory $timeFactory,
71
-								IConfig $config,
72
-								ILogger $logger) {
73
-		$this->appData = $appDataFactory->get('appstore');
74
-		$this->clientService = $clientService;
75
-		$this->timeFactory = $timeFactory;
76
-		$this->config = $config;
77
-		$this->logger = $logger;
78
-	}
79
-
80
-	/**
81
-	 * Fetches the response from the server
82
-	 *
83
-	 * @param string $ETag
84
-	 * @param string $content
85
-	 *
86
-	 * @return array
87
-	 */
88
-	protected function fetch($ETag, $content) {
89
-		$appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
90
-
91
-		if (!$appstoreenabled) {
92
-			return [];
93
-		}
94
-
95
-		$options = [
96
-			'timeout' => 10,
97
-		];
98
-
99
-		if ($ETag !== '') {
100
-			$options['headers'] = [
101
-				'If-None-Match' => $ETag,
102
-			];
103
-		}
104
-
105
-		$client = $this->clientService->newClient();
106
-		$response = $client->get($this->endpointUrl, $options);
107
-
108
-		$responseJson = [];
109
-		if ($response->getStatusCode() === Http::STATUS_NOT_MODIFIED) {
110
-			$responseJson['data'] = json_decode($content, true);
111
-		} else {
112
-			$responseJson['data'] = json_decode($response->getBody(), true);
113
-			$ETag = $response->getHeader('ETag');
114
-		}
115
-
116
-		$responseJson['timestamp'] = $this->timeFactory->getTime();
117
-		$responseJson['ncversion'] = $this->getVersion();
118
-		if ($ETag !== '') {
119
-			$responseJson['ETag'] = $ETag;
120
-		}
121
-
122
-		return $responseJson;
123
-	}
124
-
125
-	/**
126
-	 * Returns the array with the categories on the appstore server
127
-	 *
128
-	 * @return array
129
-	 */
130
-	public function get() {
131
-		$appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
132
-		$internetavailable = $this->config->getSystemValue('has_internet_connection', true);
133
-
134
-		if (!$appstoreenabled || !$internetavailable) {
135
-			return [];
136
-		}
137
-
138
-		$rootFolder = $this->appData->getFolder('/');
139
-
140
-		$ETag = '';
141
-		$content = '';
142
-
143
-		try {
144
-			// File does already exists
145
-			$file = $rootFolder->getFile($this->fileName);
146
-			$jsonBlob = json_decode($file->getContent(), true);
147
-			if (is_array($jsonBlob)) {
148
-
149
-				// No caching when the version has been updated
150
-				if (isset($jsonBlob['ncversion']) && $jsonBlob['ncversion'] === $this->getVersion()) {
151
-
152
-					// If the timestamp is older than 300 seconds request the files new
153
-					if ((int)$jsonBlob['timestamp'] > ($this->timeFactory->getTime() - self::INVALIDATE_AFTER_SECONDS)) {
154
-						return $jsonBlob['data'];
155
-					}
156
-
157
-					if (isset($jsonBlob['ETag'])) {
158
-						$ETag = $jsonBlob['ETag'];
159
-						$content = json_encode($jsonBlob['data']);
160
-					}
161
-				}
162
-			}
163
-		} catch (NotFoundException $e) {
164
-			// File does not already exists
165
-			$file = $rootFolder->newFile($this->fileName);
166
-		}
167
-
168
-		// Refresh the file content
169
-		try {
170
-			$responseJson = $this->fetch($ETag, $content);
171
-			$file->putContent(json_encode($responseJson));
172
-			return json_decode($file->getContent(), true)['data'];
173
-		} catch (ConnectException $e) {
174
-			$this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO, 'message' => 'Could not connect to appstore']);
175
-			return [];
176
-		} catch (\Exception $e) {
177
-			$this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO]);
178
-			return [];
179
-		}
180
-	}
181
-
182
-	/**
183
-	 * Get the currently Nextcloud version
184
-	 * @return string
185
-	 */
186
-	protected function getVersion() {
187
-		if ($this->version === null) {
188
-			$this->version = $this->config->getSystemValue('version', '0.0.0');
189
-		}
190
-		return $this->version;
191
-	}
192
-
193
-	/**
194
-	 * Set the current Nextcloud version
195
-	 * @param string $version
196
-	 */
197
-	public function setVersion(string $version) {
198
-		$this->version = $version;
199
-	}
42
+    const INVALIDATE_AFTER_SECONDS = 300;
43
+
44
+    /** @var IAppData */
45
+    protected $appData;
46
+    /** @var IClientService */
47
+    protected $clientService;
48
+    /** @var ITimeFactory */
49
+    protected $timeFactory;
50
+    /** @var IConfig */
51
+    protected $config;
52
+    /** @var Ilogger */
53
+    protected $logger;
54
+    /** @var string */
55
+    protected $fileName;
56
+    /** @var string */
57
+    protected $endpointUrl;
58
+    /** @var string */
59
+    protected $version;
60
+
61
+    /**
62
+     * @param Factory $appDataFactory
63
+     * @param IClientService $clientService
64
+     * @param ITimeFactory $timeFactory
65
+     * @param IConfig $config
66
+     * @param ILogger $logger
67
+     */
68
+    public function __construct(Factory $appDataFactory,
69
+                                IClientService $clientService,
70
+                                ITimeFactory $timeFactory,
71
+                                IConfig $config,
72
+                                ILogger $logger) {
73
+        $this->appData = $appDataFactory->get('appstore');
74
+        $this->clientService = $clientService;
75
+        $this->timeFactory = $timeFactory;
76
+        $this->config = $config;
77
+        $this->logger = $logger;
78
+    }
79
+
80
+    /**
81
+     * Fetches the response from the server
82
+     *
83
+     * @param string $ETag
84
+     * @param string $content
85
+     *
86
+     * @return array
87
+     */
88
+    protected function fetch($ETag, $content) {
89
+        $appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
90
+
91
+        if (!$appstoreenabled) {
92
+            return [];
93
+        }
94
+
95
+        $options = [
96
+            'timeout' => 10,
97
+        ];
98
+
99
+        if ($ETag !== '') {
100
+            $options['headers'] = [
101
+                'If-None-Match' => $ETag,
102
+            ];
103
+        }
104
+
105
+        $client = $this->clientService->newClient();
106
+        $response = $client->get($this->endpointUrl, $options);
107
+
108
+        $responseJson = [];
109
+        if ($response->getStatusCode() === Http::STATUS_NOT_MODIFIED) {
110
+            $responseJson['data'] = json_decode($content, true);
111
+        } else {
112
+            $responseJson['data'] = json_decode($response->getBody(), true);
113
+            $ETag = $response->getHeader('ETag');
114
+        }
115
+
116
+        $responseJson['timestamp'] = $this->timeFactory->getTime();
117
+        $responseJson['ncversion'] = $this->getVersion();
118
+        if ($ETag !== '') {
119
+            $responseJson['ETag'] = $ETag;
120
+        }
121
+
122
+        return $responseJson;
123
+    }
124
+
125
+    /**
126
+     * Returns the array with the categories on the appstore server
127
+     *
128
+     * @return array
129
+     */
130
+    public function get() {
131
+        $appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
132
+        $internetavailable = $this->config->getSystemValue('has_internet_connection', true);
133
+
134
+        if (!$appstoreenabled || !$internetavailable) {
135
+            return [];
136
+        }
137
+
138
+        $rootFolder = $this->appData->getFolder('/');
139
+
140
+        $ETag = '';
141
+        $content = '';
142
+
143
+        try {
144
+            // File does already exists
145
+            $file = $rootFolder->getFile($this->fileName);
146
+            $jsonBlob = json_decode($file->getContent(), true);
147
+            if (is_array($jsonBlob)) {
148
+
149
+                // No caching when the version has been updated
150
+                if (isset($jsonBlob['ncversion']) && $jsonBlob['ncversion'] === $this->getVersion()) {
151
+
152
+                    // If the timestamp is older than 300 seconds request the files new
153
+                    if ((int)$jsonBlob['timestamp'] > ($this->timeFactory->getTime() - self::INVALIDATE_AFTER_SECONDS)) {
154
+                        return $jsonBlob['data'];
155
+                    }
156
+
157
+                    if (isset($jsonBlob['ETag'])) {
158
+                        $ETag = $jsonBlob['ETag'];
159
+                        $content = json_encode($jsonBlob['data']);
160
+                    }
161
+                }
162
+            }
163
+        } catch (NotFoundException $e) {
164
+            // File does not already exists
165
+            $file = $rootFolder->newFile($this->fileName);
166
+        }
167
+
168
+        // Refresh the file content
169
+        try {
170
+            $responseJson = $this->fetch($ETag, $content);
171
+            $file->putContent(json_encode($responseJson));
172
+            return json_decode($file->getContent(), true)['data'];
173
+        } catch (ConnectException $e) {
174
+            $this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO, 'message' => 'Could not connect to appstore']);
175
+            return [];
176
+        } catch (\Exception $e) {
177
+            $this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO]);
178
+            return [];
179
+        }
180
+    }
181
+
182
+    /**
183
+     * Get the currently Nextcloud version
184
+     * @return string
185
+     */
186
+    protected function getVersion() {
187
+        if ($this->version === null) {
188
+            $this->version = $this->config->getSystemValue('version', '0.0.0');
189
+        }
190
+        return $this->version;
191
+    }
192
+
193
+    /**
194
+     * Set the current Nextcloud version
195
+     * @param string $version
196
+     */
197
+    public function setVersion(string $version) {
198
+        $this->version = $version;
199
+    }
200 200
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/DAV.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -34,7 +34,6 @@
 block discarded – undo
34 34
 namespace OC\Files\Storage;
35 35
 
36 36
 use Exception;
37
-use GuzzleHttp\Exception\RequestException;
38 37
 use OCP\ILogger;
39 38
 use Psr\Http\Message\ResponseInterface;
40 39
 use Icewind\Streams\CallbackWrapper;
Please login to merge, or discard this patch.
Indentation   +796 added lines, -796 removed lines patch added patch discarded remove patch
@@ -58,801 +58,801 @@
 block discarded – undo
58 58
  * @package OC\Files\Storage
59 59
  */
60 60
 class DAV extends Common {
61
-	/** @var string */
62
-	protected $password;
63
-	/** @var string */
64
-	protected $user;
65
-	/** @var string */
66
-	protected $authType;
67
-	/** @var string */
68
-	protected $host;
69
-	/** @var bool */
70
-	protected $secure;
71
-	/** @var string */
72
-	protected $root;
73
-	/** @var string */
74
-	protected $certPath;
75
-	/** @var bool */
76
-	protected $ready;
77
-	/** @var Client */
78
-	protected $client;
79
-	/** @var ArrayCache */
80
-	protected $statCache;
81
-	/** @var \OCP\Http\Client\IClientService */
82
-	protected $httpClientService;
83
-
84
-	/**
85
-	 * @param array $params
86
-	 * @throws \Exception
87
-	 */
88
-	public function __construct($params) {
89
-		$this->statCache = new ArrayCache();
90
-		$this->httpClientService = \OC::$server->getHTTPClientService();
91
-		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
92
-			$host = $params['host'];
93
-			//remove leading http[s], will be generated in createBaseUri()
94
-			if (substr($host, 0, 8) == "https://") $host = substr($host, 8);
95
-			else if (substr($host, 0, 7) == "http://") $host = substr($host, 7);
96
-			$this->host = $host;
97
-			$this->user = $params['user'];
98
-			$this->password = $params['password'];
99
-			if (isset($params['authType'])) {
100
-				$this->authType = $params['authType'];
101
-			}
102
-			if (isset($params['secure'])) {
103
-				if (is_string($params['secure'])) {
104
-					$this->secure = ($params['secure'] === 'true');
105
-				} else {
106
-					$this->secure = (bool)$params['secure'];
107
-				}
108
-			} else {
109
-				$this->secure = false;
110
-			}
111
-			if ($this->secure === true) {
112
-				// inject mock for testing
113
-				$certManager = \OC::$server->getCertificateManager();
114
-				if (is_null($certManager)) { //no user
115
-					$certManager = \OC::$server->getCertificateManager(null);
116
-				}
117
-				$certPath = $certManager->getAbsoluteBundlePath();
118
-				if (file_exists($certPath)) {
119
-					$this->certPath = $certPath;
120
-				}
121
-			}
122
-			$this->root = $params['root'] ?? '/';
123
-			$this->root = '/' . ltrim($this->root, '/');
124
-			$this->root = rtrim($this->root, '/') . '/';
125
-		} else {
126
-			throw new \Exception('Invalid webdav storage configuration');
127
-		}
128
-	}
129
-
130
-	protected function init() {
131
-		if ($this->ready) {
132
-			return;
133
-		}
134
-		$this->ready = true;
135
-
136
-		$settings = [
137
-			'baseUri' => $this->createBaseUri(),
138
-			'userName' => $this->user,
139
-			'password' => $this->password,
140
-		];
141
-		if (isset($this->authType)) {
142
-			$settings['authType'] = $this->authType;
143
-		}
144
-
145
-		$proxy = \OC::$server->getConfig()->getSystemValue('proxy', '');
146
-		if ($proxy !== '') {
147
-			$settings['proxy'] = $proxy;
148
-		}
149
-
150
-		$this->client = new Client($settings);
151
-		$this->client->setThrowExceptions(true);
152
-		if ($this->secure === true && $this->certPath) {
153
-			$this->client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
154
-		}
155
-	}
156
-
157
-	/**
158
-	 * Clear the stat cache
159
-	 */
160
-	public function clearStatCache() {
161
-		$this->statCache->clear();
162
-	}
163
-
164
-	/** {@inheritdoc} */
165
-	public function getId() {
166
-		return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
167
-	}
168
-
169
-	/** {@inheritdoc} */
170
-	public function createBaseUri() {
171
-		$baseUri = 'http';
172
-		if ($this->secure) {
173
-			$baseUri .= 's';
174
-		}
175
-		$baseUri .= '://' . $this->host . $this->root;
176
-		return $baseUri;
177
-	}
178
-
179
-	/** {@inheritdoc} */
180
-	public function mkdir($path) {
181
-		$this->init();
182
-		$path = $this->cleanPath($path);
183
-		$result = $this->simpleResponse('MKCOL', $path, null, 201);
184
-		if ($result) {
185
-			$this->statCache->set($path, true);
186
-		}
187
-		return $result;
188
-	}
189
-
190
-	/** {@inheritdoc} */
191
-	public function rmdir($path) {
192
-		$this->init();
193
-		$path = $this->cleanPath($path);
194
-		// FIXME: some WebDAV impl return 403 when trying to DELETE
195
-		// a non-empty folder
196
-		$result = $this->simpleResponse('DELETE', $path . '/', null, 204);
197
-		$this->statCache->clear($path . '/');
198
-		$this->statCache->remove($path);
199
-		return $result;
200
-	}
201
-
202
-	/** {@inheritdoc} */
203
-	public function opendir($path) {
204
-		$this->init();
205
-		$path = $this->cleanPath($path);
206
-		try {
207
-			$response = $this->client->propFind(
208
-				$this->encodePath($path),
209
-				['{DAV:}href'],
210
-				1
211
-			);
212
-			if ($response === false) {
213
-				return false;
214
-			}
215
-			$content = [];
216
-			$files = array_keys($response);
217
-			array_shift($files); //the first entry is the current directory
218
-
219
-			if (!$this->statCache->hasKey($path)) {
220
-				$this->statCache->set($path, true);
221
-			}
222
-			foreach ($files as $file) {
223
-				$file = urldecode($file);
224
-				// do not store the real entry, we might not have all properties
225
-				if (!$this->statCache->hasKey($path)) {
226
-					$this->statCache->set($file, true);
227
-				}
228
-				$file = basename($file);
229
-				$content[] = $file;
230
-			}
231
-			return IteratorDirectory::wrap($content);
232
-		} catch (\Exception $e) {
233
-			$this->convertException($e, $path);
234
-		}
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * Propfind call with cache handling.
240
-	 *
241
-	 * First checks if information is cached.
242
-	 * If not, request it from the server then store to cache.
243
-	 *
244
-	 * @param string $path path to propfind
245
-	 *
246
-	 * @return array|boolean propfind response or false if the entry was not found
247
-	 *
248
-	 * @throws ClientHttpException
249
-	 */
250
-	protected function propfind($path) {
251
-		$path = $this->cleanPath($path);
252
-		$cachedResponse = $this->statCache->get($path);
253
-		// we either don't know it, or we know it exists but need more details
254
-		if (is_null($cachedResponse) || $cachedResponse === true) {
255
-			$this->init();
256
-			try {
257
-				$response = $this->client->propFind(
258
-					$this->encodePath($path),
259
-					array(
260
-						'{DAV:}getlastmodified',
261
-						'{DAV:}getcontentlength',
262
-						'{DAV:}getcontenttype',
263
-						'{http://owncloud.org/ns}permissions',
264
-						'{http://open-collaboration-services.org/ns}share-permissions',
265
-						'{DAV:}resourcetype',
266
-						'{DAV:}getetag',
267
-					)
268
-				);
269
-				$this->statCache->set($path, $response);
270
-			} catch (ClientHttpException $e) {
271
-				if ($e->getHttpStatus() === 404) {
272
-					$this->statCache->clear($path . '/');
273
-					$this->statCache->set($path, false);
274
-					return false;
275
-				}
276
-				$this->convertException($e, $path);
277
-			} catch (\Exception $e) {
278
-				$this->convertException($e, $path);
279
-			}
280
-		} else {
281
-			$response = $cachedResponse;
282
-		}
283
-		return $response;
284
-	}
285
-
286
-	/** {@inheritdoc} */
287
-	public function filetype($path) {
288
-		try {
289
-			$response = $this->propfind($path);
290
-			if ($response === false) {
291
-				return false;
292
-			}
293
-			$responseType = [];
294
-			if (isset($response["{DAV:}resourcetype"])) {
295
-				/** @var ResourceType[] $response */
296
-				$responseType = $response["{DAV:}resourcetype"]->getValue();
297
-			}
298
-			return (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
299
-		} catch (\Exception $e) {
300
-			$this->convertException($e, $path);
301
-		}
302
-		return false;
303
-	}
304
-
305
-	/** {@inheritdoc} */
306
-	public function file_exists($path) {
307
-		try {
308
-			$path = $this->cleanPath($path);
309
-			$cachedState = $this->statCache->get($path);
310
-			if ($cachedState === false) {
311
-				// we know the file doesn't exist
312
-				return false;
313
-			} else if (!is_null($cachedState)) {
314
-				return true;
315
-			}
316
-			// need to get from server
317
-			return ($this->propfind($path) !== false);
318
-		} catch (\Exception $e) {
319
-			$this->convertException($e, $path);
320
-		}
321
-		return false;
322
-	}
323
-
324
-	/** {@inheritdoc} */
325
-	public function unlink($path) {
326
-		$this->init();
327
-		$path = $this->cleanPath($path);
328
-		$result = $this->simpleResponse('DELETE', $path, null, 204);
329
-		$this->statCache->clear($path . '/');
330
-		$this->statCache->remove($path);
331
-		return $result;
332
-	}
333
-
334
-	/** {@inheritdoc} */
335
-	public function fopen($path, $mode) {
336
-		$this->init();
337
-		$path = $this->cleanPath($path);
338
-		switch ($mode) {
339
-			case 'r':
340
-			case 'rb':
341
-				try {
342
-					$response = $this->httpClientService
343
-						->newClient()
344
-						->get($this->createBaseUri() . $this->encodePath($path), [
345
-							'auth' => [$this->user, $this->password],
346
-							'stream' => true
347
-						]);
348
-				} catch (\GuzzleHttp\Exception\ClientException $e) {
349
-					if ($e->getResponse() instanceof ResponseInterface
350
-						&& $e->getResponse()->getStatusCode() === 404) {
351
-						return false;
352
-					} else {
353
-						throw $e;
354
-					}
355
-				}
356
-
357
-				if ($response->getStatusCode() !== Http::STATUS_OK) {
358
-					if ($response->getStatusCode() === Http::STATUS_LOCKED) {
359
-						throw new \OCP\Lock\LockedException($path);
360
-					} else {
361
-						Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), ILogger::ERROR);
362
-					}
363
-				}
364
-
365
-				return $response->getBody();
366
-			case 'w':
367
-			case 'wb':
368
-			case 'a':
369
-			case 'ab':
370
-			case 'r+':
371
-			case 'w+':
372
-			case 'wb+':
373
-			case 'a+':
374
-			case 'x':
375
-			case 'x+':
376
-			case 'c':
377
-			case 'c+':
378
-				//emulate these
379
-				$tempManager = \OC::$server->getTempManager();
380
-				if (strrpos($path, '.') !== false) {
381
-					$ext = substr($path, strrpos($path, '.'));
382
-				} else {
383
-					$ext = '';
384
-				}
385
-				if ($this->file_exists($path)) {
386
-					if (!$this->isUpdatable($path)) {
387
-						return false;
388
-					}
389
-					if ($mode === 'w' or $mode === 'w+') {
390
-						$tmpFile = $tempManager->getTemporaryFile($ext);
391
-					} else {
392
-						$tmpFile = $this->getCachedFile($path);
393
-					}
394
-				} else {
395
-					if (!$this->isCreatable(dirname($path))) {
396
-						return false;
397
-					}
398
-					$tmpFile = $tempManager->getTemporaryFile($ext);
399
-				}
400
-				$handle = fopen($tmpFile, $mode);
401
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
402
-					$this->writeBack($tmpFile, $path);
403
-				});
404
-		}
405
-	}
406
-
407
-	/**
408
-	 * @param string $tmpFile
409
-	 */
410
-	public function writeBack($tmpFile, $path) {
411
-		$this->uploadFile($tmpFile, $path);
412
-		unlink($tmpFile);
413
-	}
414
-
415
-	/** {@inheritdoc} */
416
-	public function free_space($path) {
417
-		$this->init();
418
-		$path = $this->cleanPath($path);
419
-		try {
420
-			// TODO: cacheable ?
421
-			$response = $this->client->propfind($this->encodePath($path), ['{DAV:}quota-available-bytes']);
422
-			if ($response === false) {
423
-				return FileInfo::SPACE_UNKNOWN;
424
-			}
425
-			if (isset($response['{DAV:}quota-available-bytes'])) {
426
-				return (int)$response['{DAV:}quota-available-bytes'];
427
-			} else {
428
-				return FileInfo::SPACE_UNKNOWN;
429
-			}
430
-		} catch (\Exception $e) {
431
-			return FileInfo::SPACE_UNKNOWN;
432
-		}
433
-	}
434
-
435
-	/** {@inheritdoc} */
436
-	public function touch($path, $mtime = null) {
437
-		$this->init();
438
-		if (is_null($mtime)) {
439
-			$mtime = time();
440
-		}
441
-		$path = $this->cleanPath($path);
442
-
443
-		// if file exists, update the mtime, else create a new empty file
444
-		if ($this->file_exists($path)) {
445
-			try {
446
-				$this->statCache->remove($path);
447
-				$this->client->proppatch($this->encodePath($path), ['{DAV:}lastmodified' => $mtime]);
448
-				// non-owncloud clients might not have accepted the property, need to recheck it
449
-				$response = $this->client->propfind($this->encodePath($path), ['{DAV:}getlastmodified'], 0);
450
-				if ($response === false) {
451
-					return false;
452
-				}
453
-				if (isset($response['{DAV:}getlastmodified'])) {
454
-					$remoteMtime = strtotime($response['{DAV:}getlastmodified']);
455
-					if ($remoteMtime !== $mtime) {
456
-						// server has not accepted the mtime
457
-						return false;
458
-					}
459
-				}
460
-			} catch (ClientHttpException $e) {
461
-				if ($e->getHttpStatus() === 501) {
462
-					return false;
463
-				}
464
-				$this->convertException($e, $path);
465
-				return false;
466
-			} catch (\Exception $e) {
467
-				$this->convertException($e, $path);
468
-				return false;
469
-			}
470
-		} else {
471
-			$this->file_put_contents($path, '');
472
-		}
473
-		return true;
474
-	}
475
-
476
-	/**
477
-	 * @param string $path
478
-	 * @param string $data
479
-	 * @return int
480
-	 */
481
-	public function file_put_contents($path, $data) {
482
-		$path = $this->cleanPath($path);
483
-		$result = parent::file_put_contents($path, $data);
484
-		$this->statCache->remove($path);
485
-		return $result;
486
-	}
487
-
488
-	/**
489
-	 * @param string $path
490
-	 * @param string $target
491
-	 */
492
-	protected function uploadFile($path, $target) {
493
-		$this->init();
494
-
495
-		// invalidate
496
-		$target = $this->cleanPath($target);
497
-		$this->statCache->remove($target);
498
-		$source = fopen($path, 'r');
499
-
500
-		$this->httpClientService
501
-			->newClient()
502
-			->put($this->createBaseUri() . $this->encodePath($target), [
503
-				'body' => $source,
504
-				'auth' => [$this->user, $this->password]
505
-			]);
506
-
507
-		$this->removeCachedFile($target);
508
-	}
509
-
510
-	/** {@inheritdoc} */
511
-	public function rename($path1, $path2) {
512
-		$this->init();
513
-		$path1 = $this->cleanPath($path1);
514
-		$path2 = $this->cleanPath($path2);
515
-		try {
516
-			// overwrite directory ?
517
-			if ($this->is_dir($path2)) {
518
-				// needs trailing slash in destination
519
-				$path2 = rtrim($path2, '/') . '/';
520
-			}
521
-			$this->client->request(
522
-				'MOVE',
523
-				$this->encodePath($path1),
524
-				null,
525
-				[
526
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
527
-				]
528
-			);
529
-			$this->statCache->clear($path1 . '/');
530
-			$this->statCache->clear($path2 . '/');
531
-			$this->statCache->set($path1, false);
532
-			$this->statCache->set($path2, true);
533
-			$this->removeCachedFile($path1);
534
-			$this->removeCachedFile($path2);
535
-			return true;
536
-		} catch (\Exception $e) {
537
-			$this->convertException($e);
538
-		}
539
-		return false;
540
-	}
541
-
542
-	/** {@inheritdoc} */
543
-	public function copy($path1, $path2) {
544
-		$this->init();
545
-		$path1 = $this->cleanPath($path1);
546
-		$path2 = $this->cleanPath($path2);
547
-		try {
548
-			// overwrite directory ?
549
-			if ($this->is_dir($path2)) {
550
-				// needs trailing slash in destination
551
-				$path2 = rtrim($path2, '/') . '/';
552
-			}
553
-			$this->client->request(
554
-				'COPY',
555
-				$this->encodePath($path1),
556
-				null,
557
-				[
558
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
559
-				]
560
-			);
561
-			$this->statCache->clear($path2 . '/');
562
-			$this->statCache->set($path2, true);
563
-			$this->removeCachedFile($path2);
564
-			return true;
565
-		} catch (\Exception $e) {
566
-			$this->convertException($e);
567
-		}
568
-		return false;
569
-	}
570
-
571
-	/** {@inheritdoc} */
572
-	public function stat($path) {
573
-		try {
574
-			$response = $this->propfind($path);
575
-			if (!$response) {
576
-				return false;
577
-			}
578
-			return [
579
-				'mtime' => strtotime($response['{DAV:}getlastmodified']),
580
-				'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
581
-			];
582
-		} catch (\Exception $e) {
583
-			$this->convertException($e, $path);
584
-		}
585
-		return array();
586
-	}
587
-
588
-	/** {@inheritdoc} */
589
-	public function getMimeType($path) {
590
-		$remoteMimetype = $this->getMimeTypeFromRemote($path);
591
-		if ($remoteMimetype === 'application/octet-stream') {
592
-			return \OC::$server->getMimeTypeDetector()->detectPath($path);
593
-		} else {
594
-			return $remoteMimetype;
595
-		}
596
-	}
597
-
598
-	public function getMimeTypeFromRemote($path) {
599
-		try {
600
-			$response = $this->propfind($path);
601
-			if ($response === false) {
602
-				return false;
603
-			}
604
-			$responseType = [];
605
-			if (isset($response["{DAV:}resourcetype"])) {
606
-				/** @var ResourceType[] $response */
607
-				$responseType = $response["{DAV:}resourcetype"]->getValue();
608
-			}
609
-			$type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
610
-			if ($type == 'dir') {
611
-				return 'httpd/unix-directory';
612
-			} elseif (isset($response['{DAV:}getcontenttype'])) {
613
-				return $response['{DAV:}getcontenttype'];
614
-			} else {
615
-				return 'application/octet-stream';
616
-			}
617
-		} catch (\Exception $e) {
618
-			return false;
619
-		}
620
-	}
621
-
622
-	/**
623
-	 * @param string $path
624
-	 * @return string
625
-	 */
626
-	public function cleanPath($path) {
627
-		if ($path === '') {
628
-			return $path;
629
-		}
630
-		$path = Filesystem::normalizePath($path);
631
-		// remove leading slash
632
-		return substr($path, 1);
633
-	}
634
-
635
-	/**
636
-	 * URL encodes the given path but keeps the slashes
637
-	 *
638
-	 * @param string $path to encode
639
-	 * @return string encoded path
640
-	 */
641
-	protected function encodePath($path) {
642
-		// slashes need to stay
643
-		return str_replace('%2F', '/', rawurlencode($path));
644
-	}
645
-
646
-	/**
647
-	 * @param string $method
648
-	 * @param string $path
649
-	 * @param string|resource|null $body
650
-	 * @param int $expected
651
-	 * @return bool
652
-	 * @throws StorageInvalidException
653
-	 * @throws StorageNotAvailableException
654
-	 */
655
-	protected function simpleResponse($method, $path, $body, $expected) {
656
-		$path = $this->cleanPath($path);
657
-		try {
658
-			$response = $this->client->request($method, $this->encodePath($path), $body);
659
-			return $response['statusCode'] == $expected;
660
-		} catch (ClientHttpException $e) {
661
-			if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
662
-				$this->statCache->clear($path . '/');
663
-				$this->statCache->set($path, false);
664
-				return false;
665
-			}
666
-
667
-			$this->convertException($e, $path);
668
-		} catch (\Exception $e) {
669
-			$this->convertException($e, $path);
670
-		}
671
-		return false;
672
-	}
673
-
674
-	/**
675
-	 * check if curl is installed
676
-	 */
677
-	public static function checkDependencies() {
678
-		return true;
679
-	}
680
-
681
-	/** {@inheritdoc} */
682
-	public function isUpdatable($path) {
683
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
684
-	}
685
-
686
-	/** {@inheritdoc} */
687
-	public function isCreatable($path) {
688
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
689
-	}
690
-
691
-	/** {@inheritdoc} */
692
-	public function isSharable($path) {
693
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
694
-	}
695
-
696
-	/** {@inheritdoc} */
697
-	public function isDeletable($path) {
698
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
699
-	}
700
-
701
-	/** {@inheritdoc} */
702
-	public function getPermissions($path) {
703
-		$this->init();
704
-		$path = $this->cleanPath($path);
705
-		$response = $this->propfind($path);
706
-		if ($response === false) {
707
-			return 0;
708
-		}
709
-		if (isset($response['{http://owncloud.org/ns}permissions'])) {
710
-			return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
711
-		} else if ($this->is_dir($path)) {
712
-			return Constants::PERMISSION_ALL;
713
-		} else if ($this->file_exists($path)) {
714
-			return Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
715
-		} else {
716
-			return 0;
717
-		}
718
-	}
719
-
720
-	/** {@inheritdoc} */
721
-	public function getETag($path) {
722
-		$this->init();
723
-		$path = $this->cleanPath($path);
724
-		$response = $this->propfind($path);
725
-		if ($response === false) {
726
-			return null;
727
-		}
728
-		if (isset($response['{DAV:}getetag'])) {
729
-			return trim($response['{DAV:}getetag'], '"');
730
-		}
731
-		return parent::getEtag($path);
732
-	}
733
-
734
-	/**
735
-	 * @param string $permissionsString
736
-	 * @return int
737
-	 */
738
-	protected function parsePermissions($permissionsString) {
739
-		$permissions = Constants::PERMISSION_READ;
740
-		if (strpos($permissionsString, 'R') !== false) {
741
-			$permissions |= Constants::PERMISSION_SHARE;
742
-		}
743
-		if (strpos($permissionsString, 'D') !== false) {
744
-			$permissions |= Constants::PERMISSION_DELETE;
745
-		}
746
-		if (strpos($permissionsString, 'W') !== false) {
747
-			$permissions |= Constants::PERMISSION_UPDATE;
748
-		}
749
-		if (strpos($permissionsString, 'CK') !== false) {
750
-			$permissions |= Constants::PERMISSION_CREATE;
751
-			$permissions |= Constants::PERMISSION_UPDATE;
752
-		}
753
-		return $permissions;
754
-	}
755
-
756
-	/**
757
-	 * check if a file or folder has been updated since $time
758
-	 *
759
-	 * @param string $path
760
-	 * @param int $time
761
-	 * @throws \OCP\Files\StorageNotAvailableException
762
-	 * @return bool
763
-	 */
764
-	public function hasUpdated($path, $time) {
765
-		$this->init();
766
-		$path = $this->cleanPath($path);
767
-		try {
768
-			// force refresh for $path
769
-			$this->statCache->remove($path);
770
-			$response = $this->propfind($path);
771
-			if ($response === false) {
772
-				if ($path === '') {
773
-					// if root is gone it means the storage is not available
774
-					throw new StorageNotAvailableException('root is gone');
775
-				}
776
-				return false;
777
-			}
778
-			if (isset($response['{DAV:}getetag'])) {
779
-				$cachedData = $this->getCache()->get($path);
780
-				$etag = null;
781
-				if (isset($response['{DAV:}getetag'])) {
782
-					$etag = trim($response['{DAV:}getetag'], '"');
783
-				}
784
-				if (!empty($etag) && $cachedData['etag'] !== $etag) {
785
-					return true;
786
-				} else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
787
-					$sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
788
-					return $sharePermissions !== $cachedData['permissions'];
789
-				} else if (isset($response['{http://owncloud.org/ns}permissions'])) {
790
-					$permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
791
-					return $permissions !== $cachedData['permissions'];
792
-				} else {
793
-					return false;
794
-				}
795
-			} else {
796
-				$remoteMtime = strtotime($response['{DAV:}getlastmodified']);
797
-				return $remoteMtime > $time;
798
-			}
799
-		} catch (ClientHttpException $e) {
800
-			if ($e->getHttpStatus() === 405) {
801
-				if ($path === '') {
802
-					// if root is gone it means the storage is not available
803
-					throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
804
-				}
805
-				return false;
806
-			}
807
-			$this->convertException($e, $path);
808
-			return false;
809
-		} catch (\Exception $e) {
810
-			$this->convertException($e, $path);
811
-			return false;
812
-		}
813
-	}
814
-
815
-	/**
816
-	 * Interpret the given exception and decide whether it is due to an
817
-	 * unavailable storage, invalid storage or other.
818
-	 * This will either throw StorageInvalidException, StorageNotAvailableException
819
-	 * or do nothing.
820
-	 *
821
-	 * @param Exception $e sabre exception
822
-	 * @param string $path optional path from the operation
823
-	 *
824
-	 * @throws StorageInvalidException if the storage is invalid, for example
825
-	 * when the authentication expired or is invalid
826
-	 * @throws StorageNotAvailableException if the storage is not available,
827
-	 * which might be temporary
828
-	 */
829
-	protected function convertException(Exception $e, $path = '') {
830
-		\OC::$server->getLogger()->logException($e, ['app' => 'files_external']);
831
-		if ($e instanceof ClientHttpException) {
832
-			if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
833
-				throw new \OCP\Lock\LockedException($path);
834
-			}
835
-			if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
836
-				// either password was changed or was invalid all along
837
-				throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
838
-			} else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
839
-				// ignore exception for MethodNotAllowed, false will be returned
840
-				return;
841
-			}
842
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
843
-		} else if ($e instanceof ClientException) {
844
-			// connection timeout or refused, server could be temporarily down
845
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
846
-		} else if ($e instanceof \InvalidArgumentException) {
847
-			// parse error because the server returned HTML instead of XML,
848
-			// possibly temporarily down
849
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
850
-		} else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
851
-			// rethrow
852
-			throw $e;
853
-		}
854
-
855
-		// TODO: only log for now, but in the future need to wrap/rethrow exception
856
-	}
61
+    /** @var string */
62
+    protected $password;
63
+    /** @var string */
64
+    protected $user;
65
+    /** @var string */
66
+    protected $authType;
67
+    /** @var string */
68
+    protected $host;
69
+    /** @var bool */
70
+    protected $secure;
71
+    /** @var string */
72
+    protected $root;
73
+    /** @var string */
74
+    protected $certPath;
75
+    /** @var bool */
76
+    protected $ready;
77
+    /** @var Client */
78
+    protected $client;
79
+    /** @var ArrayCache */
80
+    protected $statCache;
81
+    /** @var \OCP\Http\Client\IClientService */
82
+    protected $httpClientService;
83
+
84
+    /**
85
+     * @param array $params
86
+     * @throws \Exception
87
+     */
88
+    public function __construct($params) {
89
+        $this->statCache = new ArrayCache();
90
+        $this->httpClientService = \OC::$server->getHTTPClientService();
91
+        if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
92
+            $host = $params['host'];
93
+            //remove leading http[s], will be generated in createBaseUri()
94
+            if (substr($host, 0, 8) == "https://") $host = substr($host, 8);
95
+            else if (substr($host, 0, 7) == "http://") $host = substr($host, 7);
96
+            $this->host = $host;
97
+            $this->user = $params['user'];
98
+            $this->password = $params['password'];
99
+            if (isset($params['authType'])) {
100
+                $this->authType = $params['authType'];
101
+            }
102
+            if (isset($params['secure'])) {
103
+                if (is_string($params['secure'])) {
104
+                    $this->secure = ($params['secure'] === 'true');
105
+                } else {
106
+                    $this->secure = (bool)$params['secure'];
107
+                }
108
+            } else {
109
+                $this->secure = false;
110
+            }
111
+            if ($this->secure === true) {
112
+                // inject mock for testing
113
+                $certManager = \OC::$server->getCertificateManager();
114
+                if (is_null($certManager)) { //no user
115
+                    $certManager = \OC::$server->getCertificateManager(null);
116
+                }
117
+                $certPath = $certManager->getAbsoluteBundlePath();
118
+                if (file_exists($certPath)) {
119
+                    $this->certPath = $certPath;
120
+                }
121
+            }
122
+            $this->root = $params['root'] ?? '/';
123
+            $this->root = '/' . ltrim($this->root, '/');
124
+            $this->root = rtrim($this->root, '/') . '/';
125
+        } else {
126
+            throw new \Exception('Invalid webdav storage configuration');
127
+        }
128
+    }
129
+
130
+    protected function init() {
131
+        if ($this->ready) {
132
+            return;
133
+        }
134
+        $this->ready = true;
135
+
136
+        $settings = [
137
+            'baseUri' => $this->createBaseUri(),
138
+            'userName' => $this->user,
139
+            'password' => $this->password,
140
+        ];
141
+        if (isset($this->authType)) {
142
+            $settings['authType'] = $this->authType;
143
+        }
144
+
145
+        $proxy = \OC::$server->getConfig()->getSystemValue('proxy', '');
146
+        if ($proxy !== '') {
147
+            $settings['proxy'] = $proxy;
148
+        }
149
+
150
+        $this->client = new Client($settings);
151
+        $this->client->setThrowExceptions(true);
152
+        if ($this->secure === true && $this->certPath) {
153
+            $this->client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
154
+        }
155
+    }
156
+
157
+    /**
158
+     * Clear the stat cache
159
+     */
160
+    public function clearStatCache() {
161
+        $this->statCache->clear();
162
+    }
163
+
164
+    /** {@inheritdoc} */
165
+    public function getId() {
166
+        return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
167
+    }
168
+
169
+    /** {@inheritdoc} */
170
+    public function createBaseUri() {
171
+        $baseUri = 'http';
172
+        if ($this->secure) {
173
+            $baseUri .= 's';
174
+        }
175
+        $baseUri .= '://' . $this->host . $this->root;
176
+        return $baseUri;
177
+    }
178
+
179
+    /** {@inheritdoc} */
180
+    public function mkdir($path) {
181
+        $this->init();
182
+        $path = $this->cleanPath($path);
183
+        $result = $this->simpleResponse('MKCOL', $path, null, 201);
184
+        if ($result) {
185
+            $this->statCache->set($path, true);
186
+        }
187
+        return $result;
188
+    }
189
+
190
+    /** {@inheritdoc} */
191
+    public function rmdir($path) {
192
+        $this->init();
193
+        $path = $this->cleanPath($path);
194
+        // FIXME: some WebDAV impl return 403 when trying to DELETE
195
+        // a non-empty folder
196
+        $result = $this->simpleResponse('DELETE', $path . '/', null, 204);
197
+        $this->statCache->clear($path . '/');
198
+        $this->statCache->remove($path);
199
+        return $result;
200
+    }
201
+
202
+    /** {@inheritdoc} */
203
+    public function opendir($path) {
204
+        $this->init();
205
+        $path = $this->cleanPath($path);
206
+        try {
207
+            $response = $this->client->propFind(
208
+                $this->encodePath($path),
209
+                ['{DAV:}href'],
210
+                1
211
+            );
212
+            if ($response === false) {
213
+                return false;
214
+            }
215
+            $content = [];
216
+            $files = array_keys($response);
217
+            array_shift($files); //the first entry is the current directory
218
+
219
+            if (!$this->statCache->hasKey($path)) {
220
+                $this->statCache->set($path, true);
221
+            }
222
+            foreach ($files as $file) {
223
+                $file = urldecode($file);
224
+                // do not store the real entry, we might not have all properties
225
+                if (!$this->statCache->hasKey($path)) {
226
+                    $this->statCache->set($file, true);
227
+                }
228
+                $file = basename($file);
229
+                $content[] = $file;
230
+            }
231
+            return IteratorDirectory::wrap($content);
232
+        } catch (\Exception $e) {
233
+            $this->convertException($e, $path);
234
+        }
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * Propfind call with cache handling.
240
+     *
241
+     * First checks if information is cached.
242
+     * If not, request it from the server then store to cache.
243
+     *
244
+     * @param string $path path to propfind
245
+     *
246
+     * @return array|boolean propfind response or false if the entry was not found
247
+     *
248
+     * @throws ClientHttpException
249
+     */
250
+    protected function propfind($path) {
251
+        $path = $this->cleanPath($path);
252
+        $cachedResponse = $this->statCache->get($path);
253
+        // we either don't know it, or we know it exists but need more details
254
+        if (is_null($cachedResponse) || $cachedResponse === true) {
255
+            $this->init();
256
+            try {
257
+                $response = $this->client->propFind(
258
+                    $this->encodePath($path),
259
+                    array(
260
+                        '{DAV:}getlastmodified',
261
+                        '{DAV:}getcontentlength',
262
+                        '{DAV:}getcontenttype',
263
+                        '{http://owncloud.org/ns}permissions',
264
+                        '{http://open-collaboration-services.org/ns}share-permissions',
265
+                        '{DAV:}resourcetype',
266
+                        '{DAV:}getetag',
267
+                    )
268
+                );
269
+                $this->statCache->set($path, $response);
270
+            } catch (ClientHttpException $e) {
271
+                if ($e->getHttpStatus() === 404) {
272
+                    $this->statCache->clear($path . '/');
273
+                    $this->statCache->set($path, false);
274
+                    return false;
275
+                }
276
+                $this->convertException($e, $path);
277
+            } catch (\Exception $e) {
278
+                $this->convertException($e, $path);
279
+            }
280
+        } else {
281
+            $response = $cachedResponse;
282
+        }
283
+        return $response;
284
+    }
285
+
286
+    /** {@inheritdoc} */
287
+    public function filetype($path) {
288
+        try {
289
+            $response = $this->propfind($path);
290
+            if ($response === false) {
291
+                return false;
292
+            }
293
+            $responseType = [];
294
+            if (isset($response["{DAV:}resourcetype"])) {
295
+                /** @var ResourceType[] $response */
296
+                $responseType = $response["{DAV:}resourcetype"]->getValue();
297
+            }
298
+            return (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
299
+        } catch (\Exception $e) {
300
+            $this->convertException($e, $path);
301
+        }
302
+        return false;
303
+    }
304
+
305
+    /** {@inheritdoc} */
306
+    public function file_exists($path) {
307
+        try {
308
+            $path = $this->cleanPath($path);
309
+            $cachedState = $this->statCache->get($path);
310
+            if ($cachedState === false) {
311
+                // we know the file doesn't exist
312
+                return false;
313
+            } else if (!is_null($cachedState)) {
314
+                return true;
315
+            }
316
+            // need to get from server
317
+            return ($this->propfind($path) !== false);
318
+        } catch (\Exception $e) {
319
+            $this->convertException($e, $path);
320
+        }
321
+        return false;
322
+    }
323
+
324
+    /** {@inheritdoc} */
325
+    public function unlink($path) {
326
+        $this->init();
327
+        $path = $this->cleanPath($path);
328
+        $result = $this->simpleResponse('DELETE', $path, null, 204);
329
+        $this->statCache->clear($path . '/');
330
+        $this->statCache->remove($path);
331
+        return $result;
332
+    }
333
+
334
+    /** {@inheritdoc} */
335
+    public function fopen($path, $mode) {
336
+        $this->init();
337
+        $path = $this->cleanPath($path);
338
+        switch ($mode) {
339
+            case 'r':
340
+            case 'rb':
341
+                try {
342
+                    $response = $this->httpClientService
343
+                        ->newClient()
344
+                        ->get($this->createBaseUri() . $this->encodePath($path), [
345
+                            'auth' => [$this->user, $this->password],
346
+                            'stream' => true
347
+                        ]);
348
+                } catch (\GuzzleHttp\Exception\ClientException $e) {
349
+                    if ($e->getResponse() instanceof ResponseInterface
350
+                        && $e->getResponse()->getStatusCode() === 404) {
351
+                        return false;
352
+                    } else {
353
+                        throw $e;
354
+                    }
355
+                }
356
+
357
+                if ($response->getStatusCode() !== Http::STATUS_OK) {
358
+                    if ($response->getStatusCode() === Http::STATUS_LOCKED) {
359
+                        throw new \OCP\Lock\LockedException($path);
360
+                    } else {
361
+                        Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), ILogger::ERROR);
362
+                    }
363
+                }
364
+
365
+                return $response->getBody();
366
+            case 'w':
367
+            case 'wb':
368
+            case 'a':
369
+            case 'ab':
370
+            case 'r+':
371
+            case 'w+':
372
+            case 'wb+':
373
+            case 'a+':
374
+            case 'x':
375
+            case 'x+':
376
+            case 'c':
377
+            case 'c+':
378
+                //emulate these
379
+                $tempManager = \OC::$server->getTempManager();
380
+                if (strrpos($path, '.') !== false) {
381
+                    $ext = substr($path, strrpos($path, '.'));
382
+                } else {
383
+                    $ext = '';
384
+                }
385
+                if ($this->file_exists($path)) {
386
+                    if (!$this->isUpdatable($path)) {
387
+                        return false;
388
+                    }
389
+                    if ($mode === 'w' or $mode === 'w+') {
390
+                        $tmpFile = $tempManager->getTemporaryFile($ext);
391
+                    } else {
392
+                        $tmpFile = $this->getCachedFile($path);
393
+                    }
394
+                } else {
395
+                    if (!$this->isCreatable(dirname($path))) {
396
+                        return false;
397
+                    }
398
+                    $tmpFile = $tempManager->getTemporaryFile($ext);
399
+                }
400
+                $handle = fopen($tmpFile, $mode);
401
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
402
+                    $this->writeBack($tmpFile, $path);
403
+                });
404
+        }
405
+    }
406
+
407
+    /**
408
+     * @param string $tmpFile
409
+     */
410
+    public function writeBack($tmpFile, $path) {
411
+        $this->uploadFile($tmpFile, $path);
412
+        unlink($tmpFile);
413
+    }
414
+
415
+    /** {@inheritdoc} */
416
+    public function free_space($path) {
417
+        $this->init();
418
+        $path = $this->cleanPath($path);
419
+        try {
420
+            // TODO: cacheable ?
421
+            $response = $this->client->propfind($this->encodePath($path), ['{DAV:}quota-available-bytes']);
422
+            if ($response === false) {
423
+                return FileInfo::SPACE_UNKNOWN;
424
+            }
425
+            if (isset($response['{DAV:}quota-available-bytes'])) {
426
+                return (int)$response['{DAV:}quota-available-bytes'];
427
+            } else {
428
+                return FileInfo::SPACE_UNKNOWN;
429
+            }
430
+        } catch (\Exception $e) {
431
+            return FileInfo::SPACE_UNKNOWN;
432
+        }
433
+    }
434
+
435
+    /** {@inheritdoc} */
436
+    public function touch($path, $mtime = null) {
437
+        $this->init();
438
+        if (is_null($mtime)) {
439
+            $mtime = time();
440
+        }
441
+        $path = $this->cleanPath($path);
442
+
443
+        // if file exists, update the mtime, else create a new empty file
444
+        if ($this->file_exists($path)) {
445
+            try {
446
+                $this->statCache->remove($path);
447
+                $this->client->proppatch($this->encodePath($path), ['{DAV:}lastmodified' => $mtime]);
448
+                // non-owncloud clients might not have accepted the property, need to recheck it
449
+                $response = $this->client->propfind($this->encodePath($path), ['{DAV:}getlastmodified'], 0);
450
+                if ($response === false) {
451
+                    return false;
452
+                }
453
+                if (isset($response['{DAV:}getlastmodified'])) {
454
+                    $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
455
+                    if ($remoteMtime !== $mtime) {
456
+                        // server has not accepted the mtime
457
+                        return false;
458
+                    }
459
+                }
460
+            } catch (ClientHttpException $e) {
461
+                if ($e->getHttpStatus() === 501) {
462
+                    return false;
463
+                }
464
+                $this->convertException($e, $path);
465
+                return false;
466
+            } catch (\Exception $e) {
467
+                $this->convertException($e, $path);
468
+                return false;
469
+            }
470
+        } else {
471
+            $this->file_put_contents($path, '');
472
+        }
473
+        return true;
474
+    }
475
+
476
+    /**
477
+     * @param string $path
478
+     * @param string $data
479
+     * @return int
480
+     */
481
+    public function file_put_contents($path, $data) {
482
+        $path = $this->cleanPath($path);
483
+        $result = parent::file_put_contents($path, $data);
484
+        $this->statCache->remove($path);
485
+        return $result;
486
+    }
487
+
488
+    /**
489
+     * @param string $path
490
+     * @param string $target
491
+     */
492
+    protected function uploadFile($path, $target) {
493
+        $this->init();
494
+
495
+        // invalidate
496
+        $target = $this->cleanPath($target);
497
+        $this->statCache->remove($target);
498
+        $source = fopen($path, 'r');
499
+
500
+        $this->httpClientService
501
+            ->newClient()
502
+            ->put($this->createBaseUri() . $this->encodePath($target), [
503
+                'body' => $source,
504
+                'auth' => [$this->user, $this->password]
505
+            ]);
506
+
507
+        $this->removeCachedFile($target);
508
+    }
509
+
510
+    /** {@inheritdoc} */
511
+    public function rename($path1, $path2) {
512
+        $this->init();
513
+        $path1 = $this->cleanPath($path1);
514
+        $path2 = $this->cleanPath($path2);
515
+        try {
516
+            // overwrite directory ?
517
+            if ($this->is_dir($path2)) {
518
+                // needs trailing slash in destination
519
+                $path2 = rtrim($path2, '/') . '/';
520
+            }
521
+            $this->client->request(
522
+                'MOVE',
523
+                $this->encodePath($path1),
524
+                null,
525
+                [
526
+                    'Destination' => $this->createBaseUri() . $this->encodePath($path2),
527
+                ]
528
+            );
529
+            $this->statCache->clear($path1 . '/');
530
+            $this->statCache->clear($path2 . '/');
531
+            $this->statCache->set($path1, false);
532
+            $this->statCache->set($path2, true);
533
+            $this->removeCachedFile($path1);
534
+            $this->removeCachedFile($path2);
535
+            return true;
536
+        } catch (\Exception $e) {
537
+            $this->convertException($e);
538
+        }
539
+        return false;
540
+    }
541
+
542
+    /** {@inheritdoc} */
543
+    public function copy($path1, $path2) {
544
+        $this->init();
545
+        $path1 = $this->cleanPath($path1);
546
+        $path2 = $this->cleanPath($path2);
547
+        try {
548
+            // overwrite directory ?
549
+            if ($this->is_dir($path2)) {
550
+                // needs trailing slash in destination
551
+                $path2 = rtrim($path2, '/') . '/';
552
+            }
553
+            $this->client->request(
554
+                'COPY',
555
+                $this->encodePath($path1),
556
+                null,
557
+                [
558
+                    'Destination' => $this->createBaseUri() . $this->encodePath($path2),
559
+                ]
560
+            );
561
+            $this->statCache->clear($path2 . '/');
562
+            $this->statCache->set($path2, true);
563
+            $this->removeCachedFile($path2);
564
+            return true;
565
+        } catch (\Exception $e) {
566
+            $this->convertException($e);
567
+        }
568
+        return false;
569
+    }
570
+
571
+    /** {@inheritdoc} */
572
+    public function stat($path) {
573
+        try {
574
+            $response = $this->propfind($path);
575
+            if (!$response) {
576
+                return false;
577
+            }
578
+            return [
579
+                'mtime' => strtotime($response['{DAV:}getlastmodified']),
580
+                'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
581
+            ];
582
+        } catch (\Exception $e) {
583
+            $this->convertException($e, $path);
584
+        }
585
+        return array();
586
+    }
587
+
588
+    /** {@inheritdoc} */
589
+    public function getMimeType($path) {
590
+        $remoteMimetype = $this->getMimeTypeFromRemote($path);
591
+        if ($remoteMimetype === 'application/octet-stream') {
592
+            return \OC::$server->getMimeTypeDetector()->detectPath($path);
593
+        } else {
594
+            return $remoteMimetype;
595
+        }
596
+    }
597
+
598
+    public function getMimeTypeFromRemote($path) {
599
+        try {
600
+            $response = $this->propfind($path);
601
+            if ($response === false) {
602
+                return false;
603
+            }
604
+            $responseType = [];
605
+            if (isset($response["{DAV:}resourcetype"])) {
606
+                /** @var ResourceType[] $response */
607
+                $responseType = $response["{DAV:}resourcetype"]->getValue();
608
+            }
609
+            $type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
610
+            if ($type == 'dir') {
611
+                return 'httpd/unix-directory';
612
+            } elseif (isset($response['{DAV:}getcontenttype'])) {
613
+                return $response['{DAV:}getcontenttype'];
614
+            } else {
615
+                return 'application/octet-stream';
616
+            }
617
+        } catch (\Exception $e) {
618
+            return false;
619
+        }
620
+    }
621
+
622
+    /**
623
+     * @param string $path
624
+     * @return string
625
+     */
626
+    public function cleanPath($path) {
627
+        if ($path === '') {
628
+            return $path;
629
+        }
630
+        $path = Filesystem::normalizePath($path);
631
+        // remove leading slash
632
+        return substr($path, 1);
633
+    }
634
+
635
+    /**
636
+     * URL encodes the given path but keeps the slashes
637
+     *
638
+     * @param string $path to encode
639
+     * @return string encoded path
640
+     */
641
+    protected function encodePath($path) {
642
+        // slashes need to stay
643
+        return str_replace('%2F', '/', rawurlencode($path));
644
+    }
645
+
646
+    /**
647
+     * @param string $method
648
+     * @param string $path
649
+     * @param string|resource|null $body
650
+     * @param int $expected
651
+     * @return bool
652
+     * @throws StorageInvalidException
653
+     * @throws StorageNotAvailableException
654
+     */
655
+    protected function simpleResponse($method, $path, $body, $expected) {
656
+        $path = $this->cleanPath($path);
657
+        try {
658
+            $response = $this->client->request($method, $this->encodePath($path), $body);
659
+            return $response['statusCode'] == $expected;
660
+        } catch (ClientHttpException $e) {
661
+            if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
662
+                $this->statCache->clear($path . '/');
663
+                $this->statCache->set($path, false);
664
+                return false;
665
+            }
666
+
667
+            $this->convertException($e, $path);
668
+        } catch (\Exception $e) {
669
+            $this->convertException($e, $path);
670
+        }
671
+        return false;
672
+    }
673
+
674
+    /**
675
+     * check if curl is installed
676
+     */
677
+    public static function checkDependencies() {
678
+        return true;
679
+    }
680
+
681
+    /** {@inheritdoc} */
682
+    public function isUpdatable($path) {
683
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
684
+    }
685
+
686
+    /** {@inheritdoc} */
687
+    public function isCreatable($path) {
688
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
689
+    }
690
+
691
+    /** {@inheritdoc} */
692
+    public function isSharable($path) {
693
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
694
+    }
695
+
696
+    /** {@inheritdoc} */
697
+    public function isDeletable($path) {
698
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
699
+    }
700
+
701
+    /** {@inheritdoc} */
702
+    public function getPermissions($path) {
703
+        $this->init();
704
+        $path = $this->cleanPath($path);
705
+        $response = $this->propfind($path);
706
+        if ($response === false) {
707
+            return 0;
708
+        }
709
+        if (isset($response['{http://owncloud.org/ns}permissions'])) {
710
+            return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
711
+        } else if ($this->is_dir($path)) {
712
+            return Constants::PERMISSION_ALL;
713
+        } else if ($this->file_exists($path)) {
714
+            return Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
715
+        } else {
716
+            return 0;
717
+        }
718
+    }
719
+
720
+    /** {@inheritdoc} */
721
+    public function getETag($path) {
722
+        $this->init();
723
+        $path = $this->cleanPath($path);
724
+        $response = $this->propfind($path);
725
+        if ($response === false) {
726
+            return null;
727
+        }
728
+        if (isset($response['{DAV:}getetag'])) {
729
+            return trim($response['{DAV:}getetag'], '"');
730
+        }
731
+        return parent::getEtag($path);
732
+    }
733
+
734
+    /**
735
+     * @param string $permissionsString
736
+     * @return int
737
+     */
738
+    protected function parsePermissions($permissionsString) {
739
+        $permissions = Constants::PERMISSION_READ;
740
+        if (strpos($permissionsString, 'R') !== false) {
741
+            $permissions |= Constants::PERMISSION_SHARE;
742
+        }
743
+        if (strpos($permissionsString, 'D') !== false) {
744
+            $permissions |= Constants::PERMISSION_DELETE;
745
+        }
746
+        if (strpos($permissionsString, 'W') !== false) {
747
+            $permissions |= Constants::PERMISSION_UPDATE;
748
+        }
749
+        if (strpos($permissionsString, 'CK') !== false) {
750
+            $permissions |= Constants::PERMISSION_CREATE;
751
+            $permissions |= Constants::PERMISSION_UPDATE;
752
+        }
753
+        return $permissions;
754
+    }
755
+
756
+    /**
757
+     * check if a file or folder has been updated since $time
758
+     *
759
+     * @param string $path
760
+     * @param int $time
761
+     * @throws \OCP\Files\StorageNotAvailableException
762
+     * @return bool
763
+     */
764
+    public function hasUpdated($path, $time) {
765
+        $this->init();
766
+        $path = $this->cleanPath($path);
767
+        try {
768
+            // force refresh for $path
769
+            $this->statCache->remove($path);
770
+            $response = $this->propfind($path);
771
+            if ($response === false) {
772
+                if ($path === '') {
773
+                    // if root is gone it means the storage is not available
774
+                    throw new StorageNotAvailableException('root is gone');
775
+                }
776
+                return false;
777
+            }
778
+            if (isset($response['{DAV:}getetag'])) {
779
+                $cachedData = $this->getCache()->get($path);
780
+                $etag = null;
781
+                if (isset($response['{DAV:}getetag'])) {
782
+                    $etag = trim($response['{DAV:}getetag'], '"');
783
+                }
784
+                if (!empty($etag) && $cachedData['etag'] !== $etag) {
785
+                    return true;
786
+                } else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
787
+                    $sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
788
+                    return $sharePermissions !== $cachedData['permissions'];
789
+                } else if (isset($response['{http://owncloud.org/ns}permissions'])) {
790
+                    $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
791
+                    return $permissions !== $cachedData['permissions'];
792
+                } else {
793
+                    return false;
794
+                }
795
+            } else {
796
+                $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
797
+                return $remoteMtime > $time;
798
+            }
799
+        } catch (ClientHttpException $e) {
800
+            if ($e->getHttpStatus() === 405) {
801
+                if ($path === '') {
802
+                    // if root is gone it means the storage is not available
803
+                    throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
804
+                }
805
+                return false;
806
+            }
807
+            $this->convertException($e, $path);
808
+            return false;
809
+        } catch (\Exception $e) {
810
+            $this->convertException($e, $path);
811
+            return false;
812
+        }
813
+    }
814
+
815
+    /**
816
+     * Interpret the given exception and decide whether it is due to an
817
+     * unavailable storage, invalid storage or other.
818
+     * This will either throw StorageInvalidException, StorageNotAvailableException
819
+     * or do nothing.
820
+     *
821
+     * @param Exception $e sabre exception
822
+     * @param string $path optional path from the operation
823
+     *
824
+     * @throws StorageInvalidException if the storage is invalid, for example
825
+     * when the authentication expired or is invalid
826
+     * @throws StorageNotAvailableException if the storage is not available,
827
+     * which might be temporary
828
+     */
829
+    protected function convertException(Exception $e, $path = '') {
830
+        \OC::$server->getLogger()->logException($e, ['app' => 'files_external']);
831
+        if ($e instanceof ClientHttpException) {
832
+            if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
833
+                throw new \OCP\Lock\LockedException($path);
834
+            }
835
+            if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
836
+                // either password was changed or was invalid all along
837
+                throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
838
+            } else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
839
+                // ignore exception for MethodNotAllowed, false will be returned
840
+                return;
841
+            }
842
+            throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
843
+        } else if ($e instanceof ClientException) {
844
+            // connection timeout or refused, server could be temporarily down
845
+            throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
846
+        } else if ($e instanceof \InvalidArgumentException) {
847
+            // parse error because the server returned HTML instead of XML,
848
+            // possibly temporarily down
849
+            throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
850
+        } else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
851
+            // rethrow
852
+            throw $e;
853
+        }
854
+
855
+        // TODO: only log for now, but in the future need to wrap/rethrow exception
856
+    }
857 857
 }
858 858
 
Please login to merge, or discard this patch.
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 				if (is_string($params['secure'])) {
104 104
 					$this->secure = ($params['secure'] === 'true');
105 105
 				} else {
106
-					$this->secure = (bool)$params['secure'];
106
+					$this->secure = (bool) $params['secure'];
107 107
 				}
108 108
 			} else {
109 109
 				$this->secure = false;
@@ -120,8 +120,8 @@  discard block
 block discarded – undo
120 120
 				}
121 121
 			}
122 122
 			$this->root = $params['root'] ?? '/';
123
-			$this->root = '/' . ltrim($this->root, '/');
124
-			$this->root = rtrim($this->root, '/') . '/';
123
+			$this->root = '/'.ltrim($this->root, '/');
124
+			$this->root = rtrim($this->root, '/').'/';
125 125
 		} else {
126 126
 			throw new \Exception('Invalid webdav storage configuration');
127 127
 		}
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 
164 164
 	/** {@inheritdoc} */
165 165
 	public function getId() {
166
-		return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
166
+		return 'webdav::'.$this->user.'@'.$this->host.'/'.$this->root;
167 167
 	}
168 168
 
169 169
 	/** {@inheritdoc} */
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		if ($this->secure) {
173 173
 			$baseUri .= 's';
174 174
 		}
175
-		$baseUri .= '://' . $this->host . $this->root;
175
+		$baseUri .= '://'.$this->host.$this->root;
176 176
 		return $baseUri;
177 177
 	}
178 178
 
@@ -193,8 +193,8 @@  discard block
 block discarded – undo
193 193
 		$path = $this->cleanPath($path);
194 194
 		// FIXME: some WebDAV impl return 403 when trying to DELETE
195 195
 		// a non-empty folder
196
-		$result = $this->simpleResponse('DELETE', $path . '/', null, 204);
197
-		$this->statCache->clear($path . '/');
196
+		$result = $this->simpleResponse('DELETE', $path.'/', null, 204);
197
+		$this->statCache->clear($path.'/');
198 198
 		$this->statCache->remove($path);
199 199
 		return $result;
200 200
 	}
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 				$this->statCache->set($path, $response);
270 270
 			} catch (ClientHttpException $e) {
271 271
 				if ($e->getHttpStatus() === 404) {
272
-					$this->statCache->clear($path . '/');
272
+					$this->statCache->clear($path.'/');
273 273
 					$this->statCache->set($path, false);
274 274
 					return false;
275 275
 				}
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 		$this->init();
327 327
 		$path = $this->cleanPath($path);
328 328
 		$result = $this->simpleResponse('DELETE', $path, null, 204);
329
-		$this->statCache->clear($path . '/');
329
+		$this->statCache->clear($path.'/');
330 330
 		$this->statCache->remove($path);
331 331
 		return $result;
332 332
 	}
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 				try {
342 342
 					$response = $this->httpClientService
343 343
 						->newClient()
344
-						->get($this->createBaseUri() . $this->encodePath($path), [
344
+						->get($this->createBaseUri().$this->encodePath($path), [
345 345
 							'auth' => [$this->user, $this->password],
346 346
 							'stream' => true
347 347
 						]);
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 					if ($response->getStatusCode() === Http::STATUS_LOCKED) {
359 359
 						throw new \OCP\Lock\LockedException($path);
360 360
 					} else {
361
-						Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), ILogger::ERROR);
361
+						Util::writeLog("webdav client", 'Guzzle get returned status code '.$response->getStatusCode(), ILogger::ERROR);
362 362
 					}
363 363
 				}
364 364
 
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
 					$tmpFile = $tempManager->getTemporaryFile($ext);
399 399
 				}
400 400
 				$handle = fopen($tmpFile, $mode);
401
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
401
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
402 402
 					$this->writeBack($tmpFile, $path);
403 403
 				});
404 404
 		}
@@ -423,7 +423,7 @@  discard block
 block discarded – undo
423 423
 				return FileInfo::SPACE_UNKNOWN;
424 424
 			}
425 425
 			if (isset($response['{DAV:}quota-available-bytes'])) {
426
-				return (int)$response['{DAV:}quota-available-bytes'];
426
+				return (int) $response['{DAV:}quota-available-bytes'];
427 427
 			} else {
428 428
 				return FileInfo::SPACE_UNKNOWN;
429 429
 			}
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 
500 500
 		$this->httpClientService
501 501
 			->newClient()
502
-			->put($this->createBaseUri() . $this->encodePath($target), [
502
+			->put($this->createBaseUri().$this->encodePath($target), [
503 503
 				'body' => $source,
504 504
 				'auth' => [$this->user, $this->password]
505 505
 			]);
@@ -516,18 +516,18 @@  discard block
 block discarded – undo
516 516
 			// overwrite directory ?
517 517
 			if ($this->is_dir($path2)) {
518 518
 				// needs trailing slash in destination
519
-				$path2 = rtrim($path2, '/') . '/';
519
+				$path2 = rtrim($path2, '/').'/';
520 520
 			}
521 521
 			$this->client->request(
522 522
 				'MOVE',
523 523
 				$this->encodePath($path1),
524 524
 				null,
525 525
 				[
526
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
526
+					'Destination' => $this->createBaseUri().$this->encodePath($path2),
527 527
 				]
528 528
 			);
529
-			$this->statCache->clear($path1 . '/');
530
-			$this->statCache->clear($path2 . '/');
529
+			$this->statCache->clear($path1.'/');
530
+			$this->statCache->clear($path2.'/');
531 531
 			$this->statCache->set($path1, false);
532 532
 			$this->statCache->set($path2, true);
533 533
 			$this->removeCachedFile($path1);
@@ -548,17 +548,17 @@  discard block
 block discarded – undo
548 548
 			// overwrite directory ?
549 549
 			if ($this->is_dir($path2)) {
550 550
 				// needs trailing slash in destination
551
-				$path2 = rtrim($path2, '/') . '/';
551
+				$path2 = rtrim($path2, '/').'/';
552 552
 			}
553 553
 			$this->client->request(
554 554
 				'COPY',
555 555
 				$this->encodePath($path1),
556 556
 				null,
557 557
 				[
558
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
558
+					'Destination' => $this->createBaseUri().$this->encodePath($path2),
559 559
 				]
560 560
 			);
561
-			$this->statCache->clear($path2 . '/');
561
+			$this->statCache->clear($path2.'/');
562 562
 			$this->statCache->set($path2, true);
563 563
 			$this->removeCachedFile($path2);
564 564
 			return true;
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
 			}
578 578
 			return [
579 579
 				'mtime' => strtotime($response['{DAV:}getlastmodified']),
580
-				'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
580
+				'size' => (int) isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
581 581
 			];
582 582
 		} catch (\Exception $e) {
583 583
 			$this->convertException($e, $path);
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 			return $response['statusCode'] == $expected;
660 660
 		} catch (ClientHttpException $e) {
661 661
 			if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
662
-				$this->statCache->clear($path . '/');
662
+				$this->statCache->clear($path.'/');
663 663
 				$this->statCache->set($path, false);
664 664
 				return false;
665 665
 			}
@@ -680,22 +680,22 @@  discard block
 block discarded – undo
680 680
 
681 681
 	/** {@inheritdoc} */
682 682
 	public function isUpdatable($path) {
683
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
683
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
684 684
 	}
685 685
 
686 686
 	/** {@inheritdoc} */
687 687
 	public function isCreatable($path) {
688
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
688
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_CREATE);
689 689
 	}
690 690
 
691 691
 	/** {@inheritdoc} */
692 692
 	public function isSharable($path) {
693
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
693
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_SHARE);
694 694
 	}
695 695
 
696 696
 	/** {@inheritdoc} */
697 697
 	public function isDeletable($path) {
698
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
698
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_DELETE);
699 699
 	}
700 700
 
701 701
 	/** {@inheritdoc} */
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
 				if (!empty($etag) && $cachedData['etag'] !== $etag) {
785 785
 					return true;
786 786
 				} else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
787
-					$sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
787
+					$sharePermissions = (int) $response['{http://open-collaboration-services.org/ns}share-permissions'];
788 788
 					return $sharePermissions !== $cachedData['permissions'];
789 789
 				} else if (isset($response['{http://owncloud.org/ns}permissions'])) {
790 790
 					$permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
@@ -800,7 +800,7 @@  discard block
 block discarded – undo
800 800
 			if ($e->getHttpStatus() === 405) {
801 801
 				if ($path === '') {
802 802
 					// if root is gone it means the storage is not available
803
-					throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
803
+					throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
804 804
 				}
805 805
 				return false;
806 806
 			}
@@ -834,19 +834,19 @@  discard block
 block discarded – undo
834 834
 			}
835 835
 			if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
836 836
 				// either password was changed or was invalid all along
837
-				throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
837
+				throw new StorageInvalidException(get_class($e).': '.$e->getMessage());
838 838
 			} else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
839 839
 				// ignore exception for MethodNotAllowed, false will be returned
840 840
 				return;
841 841
 			}
842
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
842
+			throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
843 843
 		} else if ($e instanceof ClientException) {
844 844
 			// connection timeout or refused, server could be temporarily down
845
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
845
+			throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
846 846
 		} else if ($e instanceof \InvalidArgumentException) {
847 847
 			// parse error because the server returned HTML instead of XML,
848 848
 			// possibly temporarily down
849
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
849
+			throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
850 850
 		} else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
851 851
 			// rethrow
852 852
 			throw $e;
Please login to merge, or discard this patch.
lib/private/Settings/Manager.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -46,7 +46,6 @@
 block discarded – undo
46 46
 use OCP\Settings\ISettings;
47 47
 use OCP\Settings\IManager;
48 48
 use OCP\Settings\ISection;
49
-use OCP\Util;
50 49
 
51 50
 class Manager implements IManager {
52 51
 	/** @var ILogger */
Please login to merge, or discard this patch.
Indentation   +352 added lines, -352 removed lines patch added patch discarded remove patch
@@ -49,356 +49,356 @@
 block discarded – undo
49 49
 use OCP\Util;
50 50
 
51 51
 class Manager implements IManager {
52
-	/** @var ILogger */
53
-	private $log;
54
-	/** @var IDBConnection */
55
-	private $dbc;
56
-	/** @var IL10N */
57
-	private $l;
58
-	/** @var IConfig */
59
-	private $config;
60
-	/** @var EncryptionManager */
61
-	private $encryptionManager;
62
-	/** @var IUserManager */
63
-	private $userManager;
64
-	/** @var ILockingProvider */
65
-	private $lockingProvider;
66
-	/** @var IRequest */
67
-	private $request;
68
-	/** @var IURLGenerator */
69
-	private $url;
70
-	/** @var AccountManager */
71
-	private $accountManager;
72
-	/** @var IGroupManager */
73
-	private $groupManager;
74
-	/** @var IFactory */
75
-	private $l10nFactory;
76
-	/** @var IAppManager */
77
-	private $appManager;
78
-
79
-	/**
80
-	 * @param ILogger $log
81
-	 * @param IDBConnection $dbc
82
-	 * @param IL10N $l
83
-	 * @param IConfig $config
84
-	 * @param EncryptionManager $encryptionManager
85
-	 * @param IUserManager $userManager
86
-	 * @param ILockingProvider $lockingProvider
87
-	 * @param IRequest $request
88
-	 * @param IURLGenerator $url
89
-	 * @param AccountManager $accountManager
90
-	 * @param IGroupManager $groupManager
91
-	 * @param IFactory $l10nFactory
92
-	 * @param IAppManager $appManager
93
-	 */
94
-	public function __construct(
95
-		ILogger $log,
96
-		IDBConnection $dbc,
97
-		IL10N $l,
98
-		IConfig $config,
99
-		EncryptionManager $encryptionManager,
100
-		IUserManager $userManager,
101
-		ILockingProvider $lockingProvider,
102
-		IRequest $request,
103
-		IURLGenerator $url,
104
-		AccountManager $accountManager,
105
-		IGroupManager $groupManager,
106
-		IFactory $l10nFactory,
107
-		IAppManager $appManager
108
-	) {
109
-		$this->log = $log;
110
-		$this->dbc = $dbc;
111
-		$this->l = $l;
112
-		$this->config = $config;
113
-		$this->encryptionManager = $encryptionManager;
114
-		$this->userManager = $userManager;
115
-		$this->lockingProvider = $lockingProvider;
116
-		$this->request = $request;
117
-		$this->url = $url;
118
-		$this->accountManager = $accountManager;
119
-		$this->groupManager = $groupManager;
120
-		$this->l10nFactory = $l10nFactory;
121
-		$this->appManager = $appManager;
122
-	}
123
-
124
-	/** @var array */
125
-	protected $sectionClasses = [];
126
-
127
-	/** @var array */
128
-	protected $sections = [];
129
-
130
-	/**
131
-	 * @param string $type 'admin' or 'personal'
132
-	 * @param string $section Class must implement OCP\Settings\ISection
133
-	 * @return void
134
-	 */
135
-	public function registerSection(string $type, string $section) {
136
-		$this->sectionClasses[$section] = $type;
137
-	}
138
-
139
-	/**
140
-	 * @param string $type 'admin' or 'personal'
141
-	 * @return ISection[]
142
-	 */
143
-	protected function getSections(string $type): array {
144
-		if (!isset($this->sections[$type])) {
145
-			$this->sections[$type] = [];
146
-		}
147
-
148
-		foreach ($this->sectionClasses as $class => $sectionType) {
149
-			try {
150
-				/** @var ISection $section */
151
-				$section = \OC::$server->query($class);
152
-			} catch (QueryException $e) {
153
-				$this->log->logException($e, ['level' => ILogger::INFO]);
154
-				continue;
155
-			}
156
-
157
-			if (!$section instanceof ISection) {
158
-				$this->log->logException(new \InvalidArgumentException('Invalid settings section registered'), ['level' => ILogger::INFO]);
159
-				continue;
160
-			}
161
-
162
-			$this->sections[$sectionType][$section->getID()] = $section;
163
-
164
-			unset($this->sectionClasses[$class]);
165
-		}
166
-
167
-		return $this->sections[$type];
168
-	}
169
-
170
-	/** @var array */
171
-	protected $settingClasses = [];
172
-
173
-	/** @var array */
174
-	protected $settings = [];
175
-
176
-	/**
177
-	 * @param string $type 'admin' or 'personal'
178
-	 * @param string $setting Class must implement OCP\Settings\ISetting
179
-	 * @return void
180
-	 */
181
-	public function registerSetting(string $type, string $setting) {
182
-		$this->settingClasses[$setting] = $type;
183
-	}
184
-
185
-	/**
186
-	 * @param string $type 'admin' or 'personal'
187
-	 * @param string $section
188
-	 * @return ISettings[]
189
-	 */
190
-	protected function getSettings(string $type, string $section): array {
191
-		if (!isset($this->settings[$type])) {
192
-			$this->settings[$type] = [];
193
-		}
194
-		if (!isset($this->settings[$type][$section])) {
195
-			$this->settings[$type][$section] = [];
196
-		}
197
-
198
-		foreach ($this->settingClasses as $class => $settingsType) {
199
-			try {
200
-				/** @var ISettings $setting */
201
-				$setting = \OC::$server->query($class);
202
-			} catch (QueryException $e) {
203
-				$this->log->logException($e, ['level' => ILogger::INFO]);
204
-				continue;
205
-			}
206
-
207
-			if (!$setting instanceof ISettings) {
208
-				$this->log->logException(new \InvalidArgumentException('Invalid settings setting registered'), ['level' => ILogger::INFO]);
209
-				continue;
210
-			}
211
-
212
-			if (!isset($this->settings[$settingsType][$setting->getSection()])) {
213
-				$this->settings[$settingsType][$setting->getSection()] = [];
214
-			}
215
-			$this->settings[$settingsType][$setting->getSection()][] = $setting;
216
-
217
-			unset($this->settingClasses[$class]);
218
-		}
219
-
220
-		return $this->settings[$type][$section];
221
-	}
222
-
223
-	/**
224
-	 * @inheritdoc
225
-	 */
226
-	public function getAdminSections(): array {
227
-		// built-in sections
228
-		$sections = [
229
-			0 => [new Section('server', $this->l->t('Basic settings'), 0, $this->url->imagePath('settings', 'admin.svg'))],
230
-			5 => [new Section('sharing', $this->l->t('Sharing'), 0, $this->url->imagePath('core', 'actions/share.svg'))],
231
-			10 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
232
-			45 => [new Section('encryption', $this->l->t('Encryption'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
233
-			98 => [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))],
234
-			99 => [new Section('tips-tricks', $this->l->t('Tips & tricks'), 0, $this->url->imagePath('settings', 'help.svg'))],
235
-		];
236
-
237
-		$appSections = $this->getSections('admin');
238
-
239
-		foreach ($appSections as $section) {
240
-			/** @var ISection $section */
241
-			if (!isset($sections[$section->getPriority()])) {
242
-				$sections[$section->getPriority()] = [];
243
-			}
244
-
245
-			$sections[$section->getPriority()][] = $section;
246
-		}
247
-
248
-		ksort($sections);
249
-
250
-		return $sections;
251
-	}
252
-
253
-	/**
254
-	 * @param string $section
255
-	 * @return ISection[]
256
-	 */
257
-	private function getBuiltInAdminSettings($section): array {
258
-		$forms = [];
259
-
260
-		if ($section === 'server') {
261
-			/** @var ISettings $form */
262
-			$form = new Admin\Server($this->dbc, $this->request, $this->config, $this->lockingProvider, $this->l);
263
-			$forms[$form->getPriority()] = [$form];
264
-			$form = new Admin\ServerDevNotice();
265
-			$forms[$form->getPriority()] = [$form];
266
-		}
267
-		if ($section === 'encryption') {
268
-			/** @var ISettings $form */
269
-			$form = new Admin\Encryption($this->encryptionManager, $this->userManager);
270
-			$forms[$form->getPriority()] = [$form];
271
-		}
272
-		if ($section === 'sharing') {
273
-			/** @var ISettings $form */
274
-			$form = new Admin\Sharing($this->config, $this->l);
275
-			$forms[$form->getPriority()] = [$form];
276
-		}
277
-		if ($section === 'additional') {
278
-			/** @var ISettings $form */
279
-			$form = new Admin\Additional($this->config);
280
-			$forms[$form->getPriority()] = [$form];
281
-		}
282
-		if ($section === 'tips-tricks') {
283
-			/** @var ISettings $form */
284
-			$form = new Admin\TipsTricks($this->config);
285
-			$forms[$form->getPriority()] = [$form];
286
-		}
287
-
288
-		return $forms;
289
-	}
290
-
291
-	/**
292
-	 * @param string $section
293
-	 * @return ISection[]
294
-	 */
295
-	private function getBuiltInPersonalSettings($section): array {
296
-		$forms = [];
297
-
298
-		if ($section === 'personal-info') {
299
-			/** @var ISettings $form */
300
-			$form = new Personal\PersonalInfo(
301
-				$this->config,
302
-				$this->userManager,
303
-				$this->groupManager,
304
-				$this->accountManager,
305
-				$this->appManager,
306
-				$this->l10nFactory,
307
-				$this->l
308
-			);
309
-			$forms[$form->getPriority()] = [$form];
310
-		}
311
-		if($section === 'security') {
312
-			/** @var ISettings $form */
313
-			$form = new Personal\Security();
314
-			$forms[$form->getPriority()] = [$form];
315
-		}
316
-		if ($section === 'additional') {
317
-			/** @var ISettings $form */
318
-			$form = new Personal\Additional();
319
-			$forms[$form->getPriority()] = [$form];
320
-		}
321
-
322
-		return $forms;
323
-	}
324
-
325
-	/**
326
-	 * @inheritdoc
327
-	 */
328
-	public function getAdminSettings($section): array {
329
-		$settings = $this->getBuiltInAdminSettings($section);
330
-		$appSettings = $this->getSettings('admin', $section);
331
-
332
-		foreach ($appSettings as $setting) {
333
-			if (!isset($settings[$setting->getPriority()])) {
334
-				$settings[$setting->getPriority()] = [];
335
-			}
336
-			$settings[$setting->getPriority()][] = $setting;
337
-		}
338
-
339
-		ksort($settings);
340
-		return $settings;
341
-	}
342
-
343
-	/**
344
-	 * @inheritdoc
345
-	 */
346
-	public function getPersonalSections(): array {
347
-		$sections = [
348
-			0 => [new Section('personal-info', $this->l->t('Personal info'), 0, $this->url->imagePath('core', 'actions/info.svg'))],
349
-			5 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('settings', 'password.svg'))],
350
-			15 => [new Section('sync-clients', $this->l->t('Sync clients'), 0, $this->url->imagePath('settings', 'change.svg'))],
351
-		];
352
-
353
-		$legacyForms = \OC_App::getForms('personal');
354
-		if(!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
355
-			$sections[98] = [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))];
356
-		}
357
-
358
-		$appSections = $this->getSections('personal');
359
-
360
-		foreach ($appSections as $section) {
361
-			/** @var ISection $section */
362
-			if (!isset($sections[$section->getPriority()])) {
363
-				$sections[$section->getPriority()] = [];
364
-			}
365
-
366
-			$sections[$section->getPriority()][] = $section;
367
-		}
368
-
369
-		ksort($sections);
370
-
371
-		return $sections;
372
-	}
373
-
374
-	/**
375
-	 * @param string[] $forms
376
-	 * @return bool
377
-	 */
378
-	private function hasLegacyPersonalSettingsToRender(array $forms): bool {
379
-		foreach ($forms as $form) {
380
-			if(trim($form) !== '') {
381
-				return true;
382
-			}
383
-		}
384
-		return false;
385
-	}
386
-
387
-	/**
388
-	 * @inheritdoc
389
-	 */
390
-	public function getPersonalSettings($section): array {
391
-		$settings = $this->getBuiltInPersonalSettings($section);
392
-		$appSettings = $this->getSettings('personal', $section);
393
-
394
-		foreach ($appSettings as $setting) {
395
-			if (!isset($settings[$setting->getPriority()])) {
396
-				$settings[$setting->getPriority()] = [];
397
-			}
398
-			$settings[$setting->getPriority()][] = $setting;
399
-		}
400
-
401
-		ksort($settings);
402
-		return $settings;
403
-	}
52
+    /** @var ILogger */
53
+    private $log;
54
+    /** @var IDBConnection */
55
+    private $dbc;
56
+    /** @var IL10N */
57
+    private $l;
58
+    /** @var IConfig */
59
+    private $config;
60
+    /** @var EncryptionManager */
61
+    private $encryptionManager;
62
+    /** @var IUserManager */
63
+    private $userManager;
64
+    /** @var ILockingProvider */
65
+    private $lockingProvider;
66
+    /** @var IRequest */
67
+    private $request;
68
+    /** @var IURLGenerator */
69
+    private $url;
70
+    /** @var AccountManager */
71
+    private $accountManager;
72
+    /** @var IGroupManager */
73
+    private $groupManager;
74
+    /** @var IFactory */
75
+    private $l10nFactory;
76
+    /** @var IAppManager */
77
+    private $appManager;
78
+
79
+    /**
80
+     * @param ILogger $log
81
+     * @param IDBConnection $dbc
82
+     * @param IL10N $l
83
+     * @param IConfig $config
84
+     * @param EncryptionManager $encryptionManager
85
+     * @param IUserManager $userManager
86
+     * @param ILockingProvider $lockingProvider
87
+     * @param IRequest $request
88
+     * @param IURLGenerator $url
89
+     * @param AccountManager $accountManager
90
+     * @param IGroupManager $groupManager
91
+     * @param IFactory $l10nFactory
92
+     * @param IAppManager $appManager
93
+     */
94
+    public function __construct(
95
+        ILogger $log,
96
+        IDBConnection $dbc,
97
+        IL10N $l,
98
+        IConfig $config,
99
+        EncryptionManager $encryptionManager,
100
+        IUserManager $userManager,
101
+        ILockingProvider $lockingProvider,
102
+        IRequest $request,
103
+        IURLGenerator $url,
104
+        AccountManager $accountManager,
105
+        IGroupManager $groupManager,
106
+        IFactory $l10nFactory,
107
+        IAppManager $appManager
108
+    ) {
109
+        $this->log = $log;
110
+        $this->dbc = $dbc;
111
+        $this->l = $l;
112
+        $this->config = $config;
113
+        $this->encryptionManager = $encryptionManager;
114
+        $this->userManager = $userManager;
115
+        $this->lockingProvider = $lockingProvider;
116
+        $this->request = $request;
117
+        $this->url = $url;
118
+        $this->accountManager = $accountManager;
119
+        $this->groupManager = $groupManager;
120
+        $this->l10nFactory = $l10nFactory;
121
+        $this->appManager = $appManager;
122
+    }
123
+
124
+    /** @var array */
125
+    protected $sectionClasses = [];
126
+
127
+    /** @var array */
128
+    protected $sections = [];
129
+
130
+    /**
131
+     * @param string $type 'admin' or 'personal'
132
+     * @param string $section Class must implement OCP\Settings\ISection
133
+     * @return void
134
+     */
135
+    public function registerSection(string $type, string $section) {
136
+        $this->sectionClasses[$section] = $type;
137
+    }
138
+
139
+    /**
140
+     * @param string $type 'admin' or 'personal'
141
+     * @return ISection[]
142
+     */
143
+    protected function getSections(string $type): array {
144
+        if (!isset($this->sections[$type])) {
145
+            $this->sections[$type] = [];
146
+        }
147
+
148
+        foreach ($this->sectionClasses as $class => $sectionType) {
149
+            try {
150
+                /** @var ISection $section */
151
+                $section = \OC::$server->query($class);
152
+            } catch (QueryException $e) {
153
+                $this->log->logException($e, ['level' => ILogger::INFO]);
154
+                continue;
155
+            }
156
+
157
+            if (!$section instanceof ISection) {
158
+                $this->log->logException(new \InvalidArgumentException('Invalid settings section registered'), ['level' => ILogger::INFO]);
159
+                continue;
160
+            }
161
+
162
+            $this->sections[$sectionType][$section->getID()] = $section;
163
+
164
+            unset($this->sectionClasses[$class]);
165
+        }
166
+
167
+        return $this->sections[$type];
168
+    }
169
+
170
+    /** @var array */
171
+    protected $settingClasses = [];
172
+
173
+    /** @var array */
174
+    protected $settings = [];
175
+
176
+    /**
177
+     * @param string $type 'admin' or 'personal'
178
+     * @param string $setting Class must implement OCP\Settings\ISetting
179
+     * @return void
180
+     */
181
+    public function registerSetting(string $type, string $setting) {
182
+        $this->settingClasses[$setting] = $type;
183
+    }
184
+
185
+    /**
186
+     * @param string $type 'admin' or 'personal'
187
+     * @param string $section
188
+     * @return ISettings[]
189
+     */
190
+    protected function getSettings(string $type, string $section): array {
191
+        if (!isset($this->settings[$type])) {
192
+            $this->settings[$type] = [];
193
+        }
194
+        if (!isset($this->settings[$type][$section])) {
195
+            $this->settings[$type][$section] = [];
196
+        }
197
+
198
+        foreach ($this->settingClasses as $class => $settingsType) {
199
+            try {
200
+                /** @var ISettings $setting */
201
+                $setting = \OC::$server->query($class);
202
+            } catch (QueryException $e) {
203
+                $this->log->logException($e, ['level' => ILogger::INFO]);
204
+                continue;
205
+            }
206
+
207
+            if (!$setting instanceof ISettings) {
208
+                $this->log->logException(new \InvalidArgumentException('Invalid settings setting registered'), ['level' => ILogger::INFO]);
209
+                continue;
210
+            }
211
+
212
+            if (!isset($this->settings[$settingsType][$setting->getSection()])) {
213
+                $this->settings[$settingsType][$setting->getSection()] = [];
214
+            }
215
+            $this->settings[$settingsType][$setting->getSection()][] = $setting;
216
+
217
+            unset($this->settingClasses[$class]);
218
+        }
219
+
220
+        return $this->settings[$type][$section];
221
+    }
222
+
223
+    /**
224
+     * @inheritdoc
225
+     */
226
+    public function getAdminSections(): array {
227
+        // built-in sections
228
+        $sections = [
229
+            0 => [new Section('server', $this->l->t('Basic settings'), 0, $this->url->imagePath('settings', 'admin.svg'))],
230
+            5 => [new Section('sharing', $this->l->t('Sharing'), 0, $this->url->imagePath('core', 'actions/share.svg'))],
231
+            10 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
232
+            45 => [new Section('encryption', $this->l->t('Encryption'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
233
+            98 => [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))],
234
+            99 => [new Section('tips-tricks', $this->l->t('Tips & tricks'), 0, $this->url->imagePath('settings', 'help.svg'))],
235
+        ];
236
+
237
+        $appSections = $this->getSections('admin');
238
+
239
+        foreach ($appSections as $section) {
240
+            /** @var ISection $section */
241
+            if (!isset($sections[$section->getPriority()])) {
242
+                $sections[$section->getPriority()] = [];
243
+            }
244
+
245
+            $sections[$section->getPriority()][] = $section;
246
+        }
247
+
248
+        ksort($sections);
249
+
250
+        return $sections;
251
+    }
252
+
253
+    /**
254
+     * @param string $section
255
+     * @return ISection[]
256
+     */
257
+    private function getBuiltInAdminSettings($section): array {
258
+        $forms = [];
259
+
260
+        if ($section === 'server') {
261
+            /** @var ISettings $form */
262
+            $form = new Admin\Server($this->dbc, $this->request, $this->config, $this->lockingProvider, $this->l);
263
+            $forms[$form->getPriority()] = [$form];
264
+            $form = new Admin\ServerDevNotice();
265
+            $forms[$form->getPriority()] = [$form];
266
+        }
267
+        if ($section === 'encryption') {
268
+            /** @var ISettings $form */
269
+            $form = new Admin\Encryption($this->encryptionManager, $this->userManager);
270
+            $forms[$form->getPriority()] = [$form];
271
+        }
272
+        if ($section === 'sharing') {
273
+            /** @var ISettings $form */
274
+            $form = new Admin\Sharing($this->config, $this->l);
275
+            $forms[$form->getPriority()] = [$form];
276
+        }
277
+        if ($section === 'additional') {
278
+            /** @var ISettings $form */
279
+            $form = new Admin\Additional($this->config);
280
+            $forms[$form->getPriority()] = [$form];
281
+        }
282
+        if ($section === 'tips-tricks') {
283
+            /** @var ISettings $form */
284
+            $form = new Admin\TipsTricks($this->config);
285
+            $forms[$form->getPriority()] = [$form];
286
+        }
287
+
288
+        return $forms;
289
+    }
290
+
291
+    /**
292
+     * @param string $section
293
+     * @return ISection[]
294
+     */
295
+    private function getBuiltInPersonalSettings($section): array {
296
+        $forms = [];
297
+
298
+        if ($section === 'personal-info') {
299
+            /** @var ISettings $form */
300
+            $form = new Personal\PersonalInfo(
301
+                $this->config,
302
+                $this->userManager,
303
+                $this->groupManager,
304
+                $this->accountManager,
305
+                $this->appManager,
306
+                $this->l10nFactory,
307
+                $this->l
308
+            );
309
+            $forms[$form->getPriority()] = [$form];
310
+        }
311
+        if($section === 'security') {
312
+            /** @var ISettings $form */
313
+            $form = new Personal\Security();
314
+            $forms[$form->getPriority()] = [$form];
315
+        }
316
+        if ($section === 'additional') {
317
+            /** @var ISettings $form */
318
+            $form = new Personal\Additional();
319
+            $forms[$form->getPriority()] = [$form];
320
+        }
321
+
322
+        return $forms;
323
+    }
324
+
325
+    /**
326
+     * @inheritdoc
327
+     */
328
+    public function getAdminSettings($section): array {
329
+        $settings = $this->getBuiltInAdminSettings($section);
330
+        $appSettings = $this->getSettings('admin', $section);
331
+
332
+        foreach ($appSettings as $setting) {
333
+            if (!isset($settings[$setting->getPriority()])) {
334
+                $settings[$setting->getPriority()] = [];
335
+            }
336
+            $settings[$setting->getPriority()][] = $setting;
337
+        }
338
+
339
+        ksort($settings);
340
+        return $settings;
341
+    }
342
+
343
+    /**
344
+     * @inheritdoc
345
+     */
346
+    public function getPersonalSections(): array {
347
+        $sections = [
348
+            0 => [new Section('personal-info', $this->l->t('Personal info'), 0, $this->url->imagePath('core', 'actions/info.svg'))],
349
+            5 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('settings', 'password.svg'))],
350
+            15 => [new Section('sync-clients', $this->l->t('Sync clients'), 0, $this->url->imagePath('settings', 'change.svg'))],
351
+        ];
352
+
353
+        $legacyForms = \OC_App::getForms('personal');
354
+        if(!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
355
+            $sections[98] = [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))];
356
+        }
357
+
358
+        $appSections = $this->getSections('personal');
359
+
360
+        foreach ($appSections as $section) {
361
+            /** @var ISection $section */
362
+            if (!isset($sections[$section->getPriority()])) {
363
+                $sections[$section->getPriority()] = [];
364
+            }
365
+
366
+            $sections[$section->getPriority()][] = $section;
367
+        }
368
+
369
+        ksort($sections);
370
+
371
+        return $sections;
372
+    }
373
+
374
+    /**
375
+     * @param string[] $forms
376
+     * @return bool
377
+     */
378
+    private function hasLegacyPersonalSettingsToRender(array $forms): bool {
379
+        foreach ($forms as $form) {
380
+            if(trim($form) !== '') {
381
+                return true;
382
+            }
383
+        }
384
+        return false;
385
+    }
386
+
387
+    /**
388
+     * @inheritdoc
389
+     */
390
+    public function getPersonalSettings($section): array {
391
+        $settings = $this->getBuiltInPersonalSettings($section);
392
+        $appSettings = $this->getSettings('personal', $section);
393
+
394
+        foreach ($appSettings as $setting) {
395
+            if (!isset($settings[$setting->getPriority()])) {
396
+                $settings[$setting->getPriority()] = [];
397
+            }
398
+            $settings[$setting->getPriority()][] = $setting;
399
+        }
400
+
401
+        ksort($settings);
402
+        return $settings;
403
+    }
404 404
 }
Please login to merge, or discard this patch.
core/ajax/update.php 2 patches
Indentation   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 use Symfony\Component\EventDispatcher\GenericEvent;
34 34
 
35 35
 if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
36
-	@set_time_limit(0);
36
+    @set_time_limit(0);
37 37
 }
38 38
 
39 39
 require_once '../../lib/base.php';
@@ -47,188 +47,188 @@  discard block
 block discarded – undo
47 47
 $eventSource->send('success', (string)$l->t('Preparing update'));
48 48
 
49 49
 class FeedBackHandler {
50
-	/** @var integer */
51
-	private $progressStateMax = 100;
52
-	/** @var integer */
53
-	private $progressStateStep = 0;
54
-	/** @var string */
55
-	private $currentStep;
56
-	/** @var \OCP\IEventSource */
57
-	private $eventSource;
58
-	/** @var \OCP\IL10N */
59
-	private $l10n;
60
-
61
-	public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
62
-		$this->eventSource = $eventSource;
63
-		$this->l10n = $l10n;
64
-	}
65
-
66
-	public function handleRepairFeedback($event) {
67
-		if (!$event instanceof GenericEvent) {
68
-			return;
69
-		}
70
-
71
-		switch ($event->getSubject()) {
72
-			case '\OC\Repair::startProgress':
73
-				$this->progressStateMax = $event->getArgument(0);
74
-				$this->progressStateStep = 0;
75
-				$this->currentStep = $event->getArgument(1);
76
-				break;
77
-			case '\OC\Repair::advance':
78
-				$this->progressStateStep += $event->getArgument(0);
79
-				$desc = $event->getArgument(1);
80
-				if (empty($desc)) {
81
-					$desc = $this->currentStep;
82
-				}
83
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
84
-				break;
85
-			case '\OC\Repair::finishProgress':
86
-				$this->progressStateMax = $this->progressStateStep;
87
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
88
-				break;
89
-			case '\OC\Repair::step':
90
-				break;
91
-			case '\OC\Repair::info':
92
-				break;
93
-			case '\OC\Repair::warning':
94
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
95
-				break;
96
-			case '\OC\Repair::error':
97
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
98
-				break;
99
-		}
100
-	}
50
+    /** @var integer */
51
+    private $progressStateMax = 100;
52
+    /** @var integer */
53
+    private $progressStateStep = 0;
54
+    /** @var string */
55
+    private $currentStep;
56
+    /** @var \OCP\IEventSource */
57
+    private $eventSource;
58
+    /** @var \OCP\IL10N */
59
+    private $l10n;
60
+
61
+    public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
62
+        $this->eventSource = $eventSource;
63
+        $this->l10n = $l10n;
64
+    }
65
+
66
+    public function handleRepairFeedback($event) {
67
+        if (!$event instanceof GenericEvent) {
68
+            return;
69
+        }
70
+
71
+        switch ($event->getSubject()) {
72
+            case '\OC\Repair::startProgress':
73
+                $this->progressStateMax = $event->getArgument(0);
74
+                $this->progressStateStep = 0;
75
+                $this->currentStep = $event->getArgument(1);
76
+                break;
77
+            case '\OC\Repair::advance':
78
+                $this->progressStateStep += $event->getArgument(0);
79
+                $desc = $event->getArgument(1);
80
+                if (empty($desc)) {
81
+                    $desc = $this->currentStep;
82
+                }
83
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
84
+                break;
85
+            case '\OC\Repair::finishProgress':
86
+                $this->progressStateMax = $this->progressStateStep;
87
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
88
+                break;
89
+            case '\OC\Repair::step':
90
+                break;
91
+            case '\OC\Repair::info':
92
+                break;
93
+            case '\OC\Repair::warning':
94
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
95
+                break;
96
+            case '\OC\Repair::error':
97
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
98
+                break;
99
+        }
100
+    }
101 101
 }
102 102
 
103 103
 if (\OCP\Util::needUpgrade()) {
104 104
 
105
-	$config = \OC::$server->getSystemConfig();
106
-	if ($config->getValue('upgrade.disable-web', false)) {
107
-		$eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
108
-		$eventSource->close();
109
-		exit();
110
-	}
111
-
112
-	// if a user is currently logged in, their session must be ignored to
113
-	// avoid side effects
114
-	\OC_User::setIncognitoMode(true);
115
-
116
-	$logger = \OC::$server->getLogger();
117
-	$config = \OC::$server->getConfig();
118
-	$updater = new \OC\Updater(
119
-			$config,
120
-			\OC::$server->getIntegrityCodeChecker(),
121
-			$logger,
122
-			\OC::$server->query(\OC\Installer::class)
123
-	);
124
-	$incompatibleApps = [];
125
-
126
-	$dispatcher = \OC::$server->getEventDispatcher();
127
-	$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
128
-		if ($event instanceof GenericEvent) {
129
-			$eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
130
-		}
131
-	});
132
-	$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
133
-		if ($event instanceof GenericEvent) {
134
-			$eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
135
-		}
136
-	});
137
-	$feedBack = new FeedBackHandler($eventSource, $l);
138
-	$dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
139
-	$dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
140
-	$dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
141
-	$dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
142
-	$dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
143
-	$dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
144
-	$dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
145
-
146
-	$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
147
-		$eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
148
-	});
149
-	$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
150
-		$eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
151
-	});
152
-	$updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
153
-		$eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
154
-	});
155
-	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
156
-		$eventSource->send('success', (string)$l->t('Updating database schema'));
157
-	});
158
-	$updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
159
-		$eventSource->send('success', (string)$l->t('Updated database'));
160
-	});
161
-	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
162
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
163
-	});
164
-	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
165
-		$eventSource->send('success', (string)$l->t('Checked database schema update'));
166
-	});
167
-	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
168
-		$eventSource->send('success', (string)$l->t('Checking updates of apps'));
169
-	});
170
-	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
171
-		$eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
172
-	});
173
-	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
174
-		$eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
175
-	});
176
-	$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
177
-		$eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
178
-	});
179
-	$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
180
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
181
-	});
182
-	$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
183
-		$eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
184
-	});
185
-	$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
186
-		$eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
187
-	});
188
-	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
189
-		$incompatibleApps[]= $app;
190
-	});
191
-	$updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
192
-		$eventSource->send('failure', $message);
193
-		$eventSource->close();
194
-		$config->setSystemValue('maintenance', false);
195
-	});
196
-	$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
197
-		$eventSource->send('success', (string)$l->t('Set log level to debug'));
198
-	});
199
-	$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
200
-		$eventSource->send('success', (string)$l->t('Reset log level'));
201
-	});
202
-	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
203
-		$eventSource->send('success', (string)$l->t('Starting code integrity check'));
204
-	});
205
-	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
206
-		$eventSource->send('success', (string)$l->t('Finished code integrity check'));
207
-	});
208
-
209
-	try {
210
-		$updater->upgrade();
211
-	} catch (\Exception $e) {
212
-		\OC::$server->getLogger()->logException($e, [
213
-			'level' => ILogger::ERROR,
214
-			'app' => 'update',
215
-		]);
216
-		$eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
217
-		$eventSource->close();
218
-		exit();
219
-	}
220
-
221
-	$disabledApps = [];
222
-	foreach ($incompatibleApps as $app) {
223
-		$disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
224
-	}
225
-
226
-	if (!empty($disabledApps)) {
227
-		$eventSource->send('notice',
228
-			(string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
229
-	}
105
+    $config = \OC::$server->getSystemConfig();
106
+    if ($config->getValue('upgrade.disable-web', false)) {
107
+        $eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
108
+        $eventSource->close();
109
+        exit();
110
+    }
111
+
112
+    // if a user is currently logged in, their session must be ignored to
113
+    // avoid side effects
114
+    \OC_User::setIncognitoMode(true);
115
+
116
+    $logger = \OC::$server->getLogger();
117
+    $config = \OC::$server->getConfig();
118
+    $updater = new \OC\Updater(
119
+            $config,
120
+            \OC::$server->getIntegrityCodeChecker(),
121
+            $logger,
122
+            \OC::$server->query(\OC\Installer::class)
123
+    );
124
+    $incompatibleApps = [];
125
+
126
+    $dispatcher = \OC::$server->getEventDispatcher();
127
+    $dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
128
+        if ($event instanceof GenericEvent) {
129
+            $eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
130
+        }
131
+    });
132
+    $dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
133
+        if ($event instanceof GenericEvent) {
134
+            $eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
135
+        }
136
+    });
137
+    $feedBack = new FeedBackHandler($eventSource, $l);
138
+    $dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
139
+    $dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
140
+    $dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
141
+    $dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
142
+    $dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
143
+    $dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
144
+    $dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
145
+
146
+    $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
147
+        $eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
148
+    });
149
+    $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
150
+        $eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
151
+    });
152
+    $updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
153
+        $eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
154
+    });
155
+    $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
156
+        $eventSource->send('success', (string)$l->t('Updating database schema'));
157
+    });
158
+    $updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
159
+        $eventSource->send('success', (string)$l->t('Updated database'));
160
+    });
161
+    $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
162
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
163
+    });
164
+    $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
165
+        $eventSource->send('success', (string)$l->t('Checked database schema update'));
166
+    });
167
+    $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
168
+        $eventSource->send('success', (string)$l->t('Checking updates of apps'));
169
+    });
170
+    $updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
171
+        $eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
172
+    });
173
+    $updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
174
+        $eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
175
+    });
176
+    $updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
177
+        $eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
178
+    });
179
+    $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
180
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
181
+    });
182
+    $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
183
+        $eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
184
+    });
185
+    $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
186
+        $eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
187
+    });
188
+    $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
189
+        $incompatibleApps[]= $app;
190
+    });
191
+    $updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
192
+        $eventSource->send('failure', $message);
193
+        $eventSource->close();
194
+        $config->setSystemValue('maintenance', false);
195
+    });
196
+    $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
197
+        $eventSource->send('success', (string)$l->t('Set log level to debug'));
198
+    });
199
+    $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
200
+        $eventSource->send('success', (string)$l->t('Reset log level'));
201
+    });
202
+    $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
203
+        $eventSource->send('success', (string)$l->t('Starting code integrity check'));
204
+    });
205
+    $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
206
+        $eventSource->send('success', (string)$l->t('Finished code integrity check'));
207
+    });
208
+
209
+    try {
210
+        $updater->upgrade();
211
+    } catch (\Exception $e) {
212
+        \OC::$server->getLogger()->logException($e, [
213
+            'level' => ILogger::ERROR,
214
+            'app' => 'update',
215
+        ]);
216
+        $eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
217
+        $eventSource->close();
218
+        exit();
219
+    }
220
+
221
+    $disabledApps = [];
222
+    foreach ($incompatibleApps as $app) {
223
+        $disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
224
+    }
225
+
226
+    if (!empty($disabledApps)) {
227
+        $eventSource->send('notice',
228
+            (string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
229
+    }
230 230
 } else {
231
-	$eventSource->send('notice', (string)$l->t('Already up to date'));
231
+    $eventSource->send('notice', (string)$l->t('Already up to date'));
232 232
 }
233 233
 
234 234
 $eventSource->send('done', '');
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 // need to send an initial message to force-init the event source,
45 45
 // which will then trigger its own CSRF check and produces its own CSRF error
46 46
 // message
47
-$eventSource->send('success', (string)$l->t('Preparing update'));
47
+$eventSource->send('success', (string) $l->t('Preparing update'));
48 48
 
49 49
 class FeedBackHandler {
50 50
 	/** @var integer */
@@ -80,21 +80,21 @@  discard block
 block discarded – undo
80 80
 				if (empty($desc)) {
81 81
 					$desc = $this->currentStep;
82 82
 				}
83
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
83
+				$this->eventSource->send('success', (string) $this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
84 84
 				break;
85 85
 			case '\OC\Repair::finishProgress':
86 86
 				$this->progressStateMax = $this->progressStateStep;
87
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
87
+				$this->eventSource->send('success', (string) $this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
88 88
 				break;
89 89
 			case '\OC\Repair::step':
90 90
 				break;
91 91
 			case '\OC\Repair::info':
92 92
 				break;
93 93
 			case '\OC\Repair::warning':
94
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
94
+				$this->eventSource->send('notice', (string) $this->l10n->t('Repair warning: ').$event->getArgument(0));
95 95
 				break;
96 96
 			case '\OC\Repair::error':
97
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
97
+				$this->eventSource->send('notice', (string) $this->l10n->t('Repair error: ').$event->getArgument(0));
98 98
 				break;
99 99
 		}
100 100
 	}
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 
105 105
 	$config = \OC::$server->getSystemConfig();
106 106
 	if ($config->getValue('upgrade.disable-web', false)) {
107
-		$eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
107
+		$eventSource->send('failure', (string) $l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
108 108
 		$eventSource->close();
109 109
 		exit();
110 110
 	}
@@ -126,12 +126,12 @@  discard block
 block discarded – undo
126 126
 	$dispatcher = \OC::$server->getEventDispatcher();
127 127
 	$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
128 128
 		if ($event instanceof GenericEvent) {
129
-			$eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
129
+			$eventSource->send('success', (string) $l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
130 130
 		}
131 131
 	});
132 132
 	$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
133 133
 		if ($event instanceof GenericEvent) {
134
-			$eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
134
+			$eventSource->send('success', (string) $l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
135 135
 		}
136 136
 	});
137 137
 	$feedBack = new FeedBackHandler($eventSource, $l);
@@ -143,67 +143,67 @@  discard block
 block discarded – undo
143 143
 	$dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
144 144
 	$dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
145 145
 
146
-	$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
147
-		$eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
146
+	$updater->listen('\OC\Updater', 'maintenanceEnabled', function() use ($eventSource, $l) {
147
+		$eventSource->send('success', (string) $l->t('Turned on maintenance mode'));
148 148
 	});
149
-	$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
150
-		$eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
149
+	$updater->listen('\OC\Updater', 'maintenanceDisabled', function() use ($eventSource, $l) {
150
+		$eventSource->send('success', (string) $l->t('Turned off maintenance mode'));
151 151
 	});
152
-	$updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
153
-		$eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
152
+	$updater->listen('\OC\Updater', 'maintenanceActive', function() use ($eventSource, $l) {
153
+		$eventSource->send('success', (string) $l->t('Maintenance mode is kept active'));
154 154
 	});
155
-	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
156
-		$eventSource->send('success', (string)$l->t('Updating database schema'));
155
+	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function() use($eventSource, $l) {
156
+		$eventSource->send('success', (string) $l->t('Updating database schema'));
157 157
 	});
158
-	$updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
159
-		$eventSource->send('success', (string)$l->t('Updated database'));
158
+	$updater->listen('\OC\Updater', 'dbUpgrade', function() use ($eventSource, $l) {
159
+		$eventSource->send('success', (string) $l->t('Updated database'));
160 160
 	});
161
-	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
162
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
161
+	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function() use($eventSource, $l) {
162
+		$eventSource->send('success', (string) $l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
163 163
 	});
164
-	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
165
-		$eventSource->send('success', (string)$l->t('Checked database schema update'));
164
+	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function() use ($eventSource, $l) {
165
+		$eventSource->send('success', (string) $l->t('Checked database schema update'));
166 166
 	});
167
-	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
168
-		$eventSource->send('success', (string)$l->t('Checking updates of apps'));
167
+	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function() use ($eventSource, $l) {
168
+		$eventSource->send('success', (string) $l->t('Checking updates of apps'));
169 169
 	});
170
-	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
171
-		$eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
170
+	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function($app) use ($eventSource, $l) {
171
+		$eventSource->send('success', (string) $l->t('Checking for update of app "%s" in appstore', [$app]));
172 172
 	});
173
-	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
174
-		$eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
173
+	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function($app) use ($eventSource, $l) {
174
+		$eventSource->send('success', (string) $l->t('Update app "%s" from appstore', [$app]));
175 175
 	});
176
-	$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
177
-		$eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
176
+	$updater->listen('\OC\Updater', 'checkAppStoreApp', function($app) use ($eventSource, $l) {
177
+		$eventSource->send('success', (string) $l->t('Checked for update of app "%s" in appstore', [$app]));
178 178
 	});
179
-	$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
180
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
179
+	$updater->listen('\OC\Updater', 'appSimulateUpdate', function($app) use ($eventSource, $l) {
180
+		$eventSource->send('success', (string) $l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
181 181
 	});
182
-	$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
183
-		$eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
182
+	$updater->listen('\OC\Updater', 'appUpgradeCheck', function() use ($eventSource, $l) {
183
+		$eventSource->send('success', (string) $l->t('Checked database schema update for apps'));
184 184
 	});
185
-	$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
186
-		$eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
185
+	$updater->listen('\OC\Updater', 'appUpgrade', function($app, $version) use ($eventSource, $l) {
186
+		$eventSource->send('success', (string) $l->t('Updated "%s" to %s', array($app, $version)));
187 187
 	});
188
-	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
189
-		$incompatibleApps[]= $app;
188
+	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function($app) use (&$incompatibleApps) {
189
+		$incompatibleApps[] = $app;
190 190
 	});
191
-	$updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
191
+	$updater->listen('\OC\Updater', 'failure', function($message) use ($eventSource, $config) {
192 192
 		$eventSource->send('failure', $message);
193 193
 		$eventSource->close();
194 194
 		$config->setSystemValue('maintenance', false);
195 195
 	});
196
-	$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
197
-		$eventSource->send('success', (string)$l->t('Set log level to debug'));
196
+	$updater->listen('\OC\Updater', 'setDebugLogLevel', function($logLevel, $logLevelName) use($eventSource, $l) {
197
+		$eventSource->send('success', (string) $l->t('Set log level to debug'));
198 198
 	});
199
-	$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
200
-		$eventSource->send('success', (string)$l->t('Reset log level'));
199
+	$updater->listen('\OC\Updater', 'resetLogLevel', function($logLevel, $logLevelName) use($eventSource, $l) {
200
+		$eventSource->send('success', (string) $l->t('Reset log level'));
201 201
 	});
202
-	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
203
-		$eventSource->send('success', (string)$l->t('Starting code integrity check'));
202
+	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function() use($eventSource, $l) {
203
+		$eventSource->send('success', (string) $l->t('Starting code integrity check'));
204 204
 	});
205
-	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
206
-		$eventSource->send('success', (string)$l->t('Finished code integrity check'));
205
+	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function() use($eventSource, $l) {
206
+		$eventSource->send('success', (string) $l->t('Finished code integrity check'));
207 207
 	});
208 208
 
209 209
 	try {
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 			'level' => ILogger::ERROR,
214 214
 			'app' => 'update',
215 215
 		]);
216
-		$eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
216
+		$eventSource->send('failure', get_class($e).': '.$e->getMessage());
217 217
 		$eventSource->close();
218 218
 		exit();
219 219
 	}
@@ -225,10 +225,10 @@  discard block
 block discarded – undo
225 225
 
226 226
 	if (!empty($disabledApps)) {
227 227
 		$eventSource->send('notice',
228
-			(string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
228
+			(string) $l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
229 229
 	}
230 230
 } else {
231
-	$eventSource->send('notice', (string)$l->t('Already up to date'));
231
+	$eventSource->send('notice', (string) $l->t('Already up to date'));
232 232
 }
233 233
 
234 234
 $eventSource->send('done', '');
Please login to merge, or discard this patch.
core/Controller/SetupController.php 2 patches
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -33,97 +33,97 @@
 block discarded – undo
33 33
 use OCP\ILogger;
34 34
 
35 35
 class SetupController {
36
-	/** @var Setup */
37
-	protected $setupHelper;
38
-	/** @var string */
39
-	private $autoConfigFile;
36
+    /** @var Setup */
37
+    protected $setupHelper;
38
+    /** @var string */
39
+    private $autoConfigFile;
40 40
 
41
-	/**
42
-	 * @param Setup $setupHelper
43
-	 */
44
-	function __construct(Setup $setupHelper) {
45
-		$this->autoConfigFile = \OC::$configDir.'autoconfig.php';
46
-		$this->setupHelper = $setupHelper;
47
-	}
41
+    /**
42
+     * @param Setup $setupHelper
43
+     */
44
+    function __construct(Setup $setupHelper) {
45
+        $this->autoConfigFile = \OC::$configDir.'autoconfig.php';
46
+        $this->setupHelper = $setupHelper;
47
+    }
48 48
 
49
-	/**
50
-	 * @param $post
51
-	 */
52
-	public function run($post) {
53
-		// Check for autosetup:
54
-		$post = $this->loadAutoConfig($post);
55
-		$opts = $this->setupHelper->getSystemInfo();
49
+    /**
50
+     * @param $post
51
+     */
52
+    public function run($post) {
53
+        // Check for autosetup:
54
+        $post = $this->loadAutoConfig($post);
55
+        $opts = $this->setupHelper->getSystemInfo();
56 56
 
57
-		// convert 'abcpassword' to 'abcpass'
58
-		if (isset($post['adminpassword'])) {
59
-			$post['adminpass'] = $post['adminpassword'];
60
-		}
61
-		if (isset($post['dbpassword'])) {
62
-			$post['dbpass'] = $post['dbpassword'];
63
-		}
57
+        // convert 'abcpassword' to 'abcpass'
58
+        if (isset($post['adminpassword'])) {
59
+            $post['adminpass'] = $post['adminpassword'];
60
+        }
61
+        if (isset($post['dbpassword'])) {
62
+            $post['dbpass'] = $post['dbpassword'];
63
+        }
64 64
 
65
-		if(isset($post['install']) AND $post['install']=='true') {
66
-			// We have to launch the installation process :
67
-			$e = $this->setupHelper->install($post);
68
-			$errors = array('errors' => $e);
65
+        if(isset($post['install']) AND $post['install']=='true') {
66
+            // We have to launch the installation process :
67
+            $e = $this->setupHelper->install($post);
68
+            $errors = array('errors' => $e);
69 69
 
70
-			if(count($e) > 0) {
71
-				$options = array_merge($opts, $post, $errors);
72
-				$this->display($options);
73
-			} else {
74
-				$this->finishSetup();
75
-			}
76
-		} else {
77
-			$options = array_merge($opts, $post);
78
-			$this->display($options);
79
-		}
80
-	}
70
+            if(count($e) > 0) {
71
+                $options = array_merge($opts, $post, $errors);
72
+                $this->display($options);
73
+            } else {
74
+                $this->finishSetup();
75
+            }
76
+        } else {
77
+            $options = array_merge($opts, $post);
78
+            $this->display($options);
79
+        }
80
+    }
81 81
 
82
-	public function display($post) {
83
-		$defaults = array(
84
-			'adminlogin' => '',
85
-			'adminpass' => '',
86
-			'dbuser' => '',
87
-			'dbpass' => '',
88
-			'dbname' => '',
89
-			'dbtablespace' => '',
90
-			'dbhost' => 'localhost',
91
-			'dbtype' => '',
92
-		);
93
-		$parameters = array_merge($defaults, $post);
82
+    public function display($post) {
83
+        $defaults = array(
84
+            'adminlogin' => '',
85
+            'adminpass' => '',
86
+            'dbuser' => '',
87
+            'dbpass' => '',
88
+            'dbname' => '',
89
+            'dbtablespace' => '',
90
+            'dbhost' => 'localhost',
91
+            'dbtype' => '',
92
+        );
93
+        $parameters = array_merge($defaults, $post);
94 94
 
95
-		\OC_Util::addVendorScript('strengthify/jquery.strengthify');
96
-		\OC_Util::addVendorStyle('strengthify/strengthify');
97
-		\OC_Util::addScript('setup');
98
-		\OC_Template::printGuestPage('', 'installation', $parameters);
99
-	}
95
+        \OC_Util::addVendorScript('strengthify/jquery.strengthify');
96
+        \OC_Util::addVendorStyle('strengthify/strengthify');
97
+        \OC_Util::addScript('setup');
98
+        \OC_Template::printGuestPage('', 'installation', $parameters);
99
+    }
100 100
 
101
-	public function finishSetup() {
102
-		if( file_exists( $this->autoConfigFile )) {
103
-			unlink($this->autoConfigFile);
104
-		}
105
-		\OC::$server->getIntegrityCodeChecker()->runInstanceVerification();
106
-		\OC_Util::redirectToDefaultPage();
107
-	}
101
+    public function finishSetup() {
102
+        if( file_exists( $this->autoConfigFile )) {
103
+            unlink($this->autoConfigFile);
104
+        }
105
+        \OC::$server->getIntegrityCodeChecker()->runInstanceVerification();
106
+        \OC_Util::redirectToDefaultPage();
107
+    }
108 108
 
109
-	public function loadAutoConfig($post) {
110
-		if( file_exists($this->autoConfigFile)) {
111
-			\OCP\Util::writeLog('core', 'Autoconfig file found, setting up ownCloud…', ILogger::INFO);
112
-			$AUTOCONFIG = array();
113
-			include $this->autoConfigFile;
114
-			$post = array_merge ($post, $AUTOCONFIG);
115
-		}
109
+    public function loadAutoConfig($post) {
110
+        if( file_exists($this->autoConfigFile)) {
111
+            \OCP\Util::writeLog('core', 'Autoconfig file found, setting up ownCloud…', ILogger::INFO);
112
+            $AUTOCONFIG = array();
113
+            include $this->autoConfigFile;
114
+            $post = array_merge ($post, $AUTOCONFIG);
115
+        }
116 116
 
117
-		$dbIsSet = isset($post['dbtype']);
118
-		$directoryIsSet = isset($post['directory']);
119
-		$adminAccountIsSet = isset($post['adminlogin']);
117
+        $dbIsSet = isset($post['dbtype']);
118
+        $directoryIsSet = isset($post['directory']);
119
+        $adminAccountIsSet = isset($post['adminlogin']);
120 120
 
121
-		if ($dbIsSet AND $directoryIsSet AND $adminAccountIsSet) {
122
-			$post['install'] = 'true';
123
-		}
124
-		$post['dbIsSet'] = $dbIsSet;
125
-		$post['directoryIsSet'] = $directoryIsSet;
121
+        if ($dbIsSet AND $directoryIsSet AND $adminAccountIsSet) {
122
+            $post['install'] = 'true';
123
+        }
124
+        $post['dbIsSet'] = $dbIsSet;
125
+        $post['directoryIsSet'] = $directoryIsSet;
126 126
 
127
-		return $post;
128
-	}
127
+        return $post;
128
+    }
129 129
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -62,12 +62,12 @@  discard block
 block discarded – undo
62 62
 			$post['dbpass'] = $post['dbpassword'];
63 63
 		}
64 64
 
65
-		if(isset($post['install']) AND $post['install']=='true') {
65
+		if (isset($post['install']) AND $post['install'] == 'true') {
66 66
 			// We have to launch the installation process :
67 67
 			$e = $this->setupHelper->install($post);
68 68
 			$errors = array('errors' => $e);
69 69
 
70
-			if(count($e) > 0) {
70
+			if (count($e) > 0) {
71 71
 				$options = array_merge($opts, $post, $errors);
72 72
 				$this->display($options);
73 73
 			} else {
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 	}
100 100
 
101 101
 	public function finishSetup() {
102
-		if( file_exists( $this->autoConfigFile )) {
102
+		if (file_exists($this->autoConfigFile)) {
103 103
 			unlink($this->autoConfigFile);
104 104
 		}
105 105
 		\OC::$server->getIntegrityCodeChecker()->runInstanceVerification();
@@ -107,11 +107,11 @@  discard block
 block discarded – undo
107 107
 	}
108 108
 
109 109
 	public function loadAutoConfig($post) {
110
-		if( file_exists($this->autoConfigFile)) {
110
+		if (file_exists($this->autoConfigFile)) {
111 111
 			\OCP\Util::writeLog('core', 'Autoconfig file found, setting up ownCloud…', ILogger::INFO);
112 112
 			$AUTOCONFIG = array();
113 113
 			include $this->autoConfigFile;
114
-			$post = array_merge ($post, $AUTOCONFIG);
114
+			$post = array_merge($post, $AUTOCONFIG);
115 115
 		}
116 116
 
117 117
 		$dbIsSet = isset($post['dbtype']);
Please login to merge, or discard this patch.
apps/files_trashbin/lib/Storage.php 1 patch
Indentation   +279 added lines, -279 removed lines patch added patch discarded remove patch
@@ -40,284 +40,284 @@
 block discarded – undo
40 40
 
41 41
 class Storage extends Wrapper {
42 42
 
43
-	private $mountPoint;
44
-	// remember already deleted files to avoid infinite loops if the trash bin
45
-	// move files across storages
46
-	private $deletedFiles = array();
47
-
48
-	/**
49
-	 * Disable trash logic
50
-	 *
51
-	 * @var bool
52
-	 */
53
-	private static $disableTrash = false;
54
-
55
-	/**
56
-	 * remember which file/folder was moved out of s shared folder
57
-	 * in this case we want to add a copy to the owners trash bin
58
-	 *
59
-	 * @var array
60
-	 */
61
-	private static $moveOutOfSharedFolder = [];
62
-
63
-	/** @var  IUserManager */
64
-	private $userManager;
65
-
66
-	/** @var ILogger */
67
-	private $logger;
68
-
69
-	/** @var EventDispatcher */
70
-	private $eventDispatcher;
71
-
72
-	/** @var IRootFolder */
73
-	private $rootFolder;
74
-
75
-	/**
76
-	 * Storage constructor.
77
-	 *
78
-	 * @param array $parameters
79
-	 * @param IUserManager|null $userManager
80
-	 * @param ILogger|null $logger
81
-	 * @param EventDispatcher|null $eventDispatcher
82
-	 * @param IRootFolder|null $rootFolder
83
-	 */
84
-	public function __construct($parameters,
85
-								IUserManager $userManager = null,
86
-								ILogger $logger = null,
87
-								EventDispatcher $eventDispatcher = null,
88
-								IRootFolder $rootFolder = null) {
89
-		$this->mountPoint = $parameters['mountPoint'];
90
-		$this->userManager = $userManager;
91
-		$this->logger = $logger;
92
-		$this->eventDispatcher = $eventDispatcher;
93
-		$this->rootFolder = $rootFolder;
94
-		parent::__construct($parameters);
95
-	}
96
-
97
-	/**
98
-	 * @internal
99
-	 */
100
-	public static function preRenameHook($params) {
101
-		// in cross-storage cases, a rename is a copy + unlink,
102
-		// that last unlink must not go to trash, only exception:
103
-		// if the file was moved from a shared storage to a local folder,
104
-		// in this case the owner should get a copy in his trash bin so that
105
-		// they can restore the files again
106
-
107
-		$oldPath = $params['oldpath'];
108
-		$newPath = dirname($params['newpath']);
109
-		$currentUser = \OC::$server->getUserSession()->getUser();
110
-
111
-		$fileMovedOutOfSharedFolder = false;
112
-
113
-		try {
114
-			if ($currentUser) {
115
-				$currentUserId = $currentUser->getUID();
116
-
117
-				$view = new View($currentUserId . '/files');
118
-				$fileInfo = $view->getFileInfo($oldPath);
119
-				if ($fileInfo) {
120
-					$sourceStorage = $fileInfo->getStorage();
121
-					$sourceOwner = $view->getOwner($oldPath);
122
-					$targetOwner = $view->getOwner($newPath);
123
-
124
-					if ($sourceOwner !== $targetOwner
125
-						&& $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
126
-					) {
127
-						$fileMovedOutOfSharedFolder = true;
128
-					}
129
-				}
130
-			}
131
-		} catch (\Exception $e) {
132
-			// do nothing, in this case we just disable the trashbin and continue
133
-			\OC::$server->getLogger()->logException($e, [
134
-				'message' => 'Trashbin storage could not check if a file was moved out of a shared folder.',
135
-				'level' => ILogger::DEBUG,
136
-				'app' => 'files_trashbin',
137
-			]);
138
-		}
139
-
140
-		if($fileMovedOutOfSharedFolder) {
141
-			self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
142
-		} else {
143
-			self::$disableTrash = true;
144
-		}
145
-
146
-	}
147
-
148
-	/**
149
-	 * @internal
150
-	 */
151
-	public static function postRenameHook($params) {
152
-		self::$disableTrash = false;
153
-	}
154
-
155
-	/**
156
-	 * Rename path1 to path2 by calling the wrapped storage.
157
-	 *
158
-	 * @param string $path1 first path
159
-	 * @param string $path2 second path
160
-	 * @return bool
161
-	 */
162
-	public function rename($path1, $path2) {
163
-		$result = $this->storage->rename($path1, $path2);
164
-		if ($result === false) {
165
-			// when rename failed, the post_rename hook isn't triggered,
166
-			// but we still want to reenable the trash logic
167
-			self::$disableTrash = false;
168
-		}
169
-		return $result;
170
-	}
171
-
172
-	/**
173
-	 * Deletes the given file by moving it into the trashbin.
174
-	 *
175
-	 * @param string $path path of file or folder to delete
176
-	 *
177
-	 * @return bool true if the operation succeeded, false otherwise
178
-	 */
179
-	public function unlink($path) {
180
-		try {
181
-			if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
182
-				$result = $this->doDelete($path, 'unlink', true);
183
-				unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
184
-			} else {
185
-				$result = $this->doDelete($path, 'unlink');
186
-			}
187
-		} catch (GenericEncryptionException $e) {
188
-			// in case of a encryption exception we delete the file right away
189
-			$this->logger->info(
190
-				"Can't move file" .  $path .
191
-				"to the trash bin, therefore it was deleted right away");
192
-
193
-			$result = $this->storage->unlink($path);
194
-		}
195
-
196
-		return $result;
197
-	}
198
-
199
-	/**
200
-	 * Deletes the given folder by moving it into the trashbin.
201
-	 *
202
-	 * @param string $path path of folder to delete
203
-	 *
204
-	 * @return bool true if the operation succeeded, false otherwise
205
-	 */
206
-	public function rmdir($path) {
207
-		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
208
-			$result = $this->doDelete($path, 'rmdir', true);
209
-			unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
210
-		} else {
211
-			$result = $this->doDelete($path, 'rmdir');
212
-		}
213
-
214
-		return $result;
215
-	}
216
-
217
-	/**
218
-	 * check if it is a file located in data/user/files only files in the
219
-	 * 'files' directory should be moved to the trash
220
-	 *
221
-	 * @param $path
222
-	 * @return bool
223
-	 */
224
-	protected function shouldMoveToTrash($path){
225
-
226
-		// check if there is a app which want to disable the trash bin for this file
227
-		$fileId = $this->storage->getCache()->getId($path);
228
-		$nodes = $this->rootFolder->getById($fileId);
229
-		foreach ($nodes as $node) {
230
-			$event = $this->createMoveToTrashEvent($node);
231
-			$this->eventDispatcher->dispatch('OCA\Files_Trashbin::moveToTrash', $event);
232
-			if ($event->shouldMoveToTrashBin() === false) {
233
-				return false;
234
-			}
235
-		}
236
-
237
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
238
-		$parts = explode('/', $normalized);
239
-		if (count($parts) < 4) {
240
-			return false;
241
-		}
242
-
243
-		if ($parts[2] === 'files' && $this->userManager->userExists($parts[1])) {
244
-			return true;
245
-		}
246
-
247
-		return false;
248
-	}
249
-
250
-	/**
251
-	 * get move to trash event
252
-	 *
253
-	 * @param Node $node
254
-	 * @return MoveToTrashEvent
255
-	 */
256
-	protected function createMoveToTrashEvent(Node $node) {
257
-		return new MoveToTrashEvent($node);
258
-	}
259
-
260
-	/**
261
-	 * Run the delete operation with the given method
262
-	 *
263
-	 * @param string $path path of file or folder to delete
264
-	 * @param string $method either "unlink" or "rmdir"
265
-	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
266
-	 *
267
-	 * @return bool true if the operation succeeded, false otherwise
268
-	 */
269
-	private function doDelete($path, $method, $ownerOnly = false) {
270
-		if (self::$disableTrash
271
-			|| !\OC::$server->getAppManager()->isEnabledForUser('files_trashbin')
272
-			|| (pathinfo($path, PATHINFO_EXTENSION) === 'part')
273
-			|| $this->shouldMoveToTrash($path) === false
274
-		) {
275
-			return call_user_func_array([$this->storage, $method], [$path]);
276
-		}
277
-
278
-		// check permissions before we continue, this is especially important for
279
-		// shared files
280
-		if (!$this->isDeletable($path)) {
281
-			return false;
282
-		}
283
-
284
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
285
-		$result = true;
286
-		$view = Filesystem::getView();
287
-		if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
288
-			$this->deletedFiles[$normalized] = $normalized;
289
-			if ($filesPath = $view->getRelativePath($normalized)) {
290
-				$filesPath = trim($filesPath, '/');
291
-				$result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
292
-				// in cross-storage cases the file will be copied
293
-				// but not deleted, so we delete it here
294
-				if ($result) {
295
-					call_user_func_array([$this->storage, $method], [$path]);
296
-				}
297
-			} else {
298
-				$result = call_user_func_array([$this->storage, $method], [$path]);
299
-			}
300
-			unset($this->deletedFiles[$normalized]);
301
-		} else if ($this->storage->file_exists($path)) {
302
-			$result = call_user_func_array([$this->storage, $method], [$path]);
303
-		}
304
-
305
-		return $result;
306
-	}
307
-
308
-	/**
309
-	 * Setup the storate wrapper callback
310
-	 */
311
-	public static function setupStorage() {
312
-		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
313
-			return new \OCA\Files_Trashbin\Storage(
314
-				array('storage' => $storage, 'mountPoint' => $mountPoint),
315
-				\OC::$server->getUserManager(),
316
-				\OC::$server->getLogger(),
317
-				\OC::$server->getEventDispatcher(),
318
-				\OC::$server->getLazyRootFolder()
319
-			);
320
-		}, 1);
321
-	}
43
+    private $mountPoint;
44
+    // remember already deleted files to avoid infinite loops if the trash bin
45
+    // move files across storages
46
+    private $deletedFiles = array();
47
+
48
+    /**
49
+     * Disable trash logic
50
+     *
51
+     * @var bool
52
+     */
53
+    private static $disableTrash = false;
54
+
55
+    /**
56
+     * remember which file/folder was moved out of s shared folder
57
+     * in this case we want to add a copy to the owners trash bin
58
+     *
59
+     * @var array
60
+     */
61
+    private static $moveOutOfSharedFolder = [];
62
+
63
+    /** @var  IUserManager */
64
+    private $userManager;
65
+
66
+    /** @var ILogger */
67
+    private $logger;
68
+
69
+    /** @var EventDispatcher */
70
+    private $eventDispatcher;
71
+
72
+    /** @var IRootFolder */
73
+    private $rootFolder;
74
+
75
+    /**
76
+     * Storage constructor.
77
+     *
78
+     * @param array $parameters
79
+     * @param IUserManager|null $userManager
80
+     * @param ILogger|null $logger
81
+     * @param EventDispatcher|null $eventDispatcher
82
+     * @param IRootFolder|null $rootFolder
83
+     */
84
+    public function __construct($parameters,
85
+                                IUserManager $userManager = null,
86
+                                ILogger $logger = null,
87
+                                EventDispatcher $eventDispatcher = null,
88
+                                IRootFolder $rootFolder = null) {
89
+        $this->mountPoint = $parameters['mountPoint'];
90
+        $this->userManager = $userManager;
91
+        $this->logger = $logger;
92
+        $this->eventDispatcher = $eventDispatcher;
93
+        $this->rootFolder = $rootFolder;
94
+        parent::__construct($parameters);
95
+    }
96
+
97
+    /**
98
+     * @internal
99
+     */
100
+    public static function preRenameHook($params) {
101
+        // in cross-storage cases, a rename is a copy + unlink,
102
+        // that last unlink must not go to trash, only exception:
103
+        // if the file was moved from a shared storage to a local folder,
104
+        // in this case the owner should get a copy in his trash bin so that
105
+        // they can restore the files again
106
+
107
+        $oldPath = $params['oldpath'];
108
+        $newPath = dirname($params['newpath']);
109
+        $currentUser = \OC::$server->getUserSession()->getUser();
110
+
111
+        $fileMovedOutOfSharedFolder = false;
112
+
113
+        try {
114
+            if ($currentUser) {
115
+                $currentUserId = $currentUser->getUID();
116
+
117
+                $view = new View($currentUserId . '/files');
118
+                $fileInfo = $view->getFileInfo($oldPath);
119
+                if ($fileInfo) {
120
+                    $sourceStorage = $fileInfo->getStorage();
121
+                    $sourceOwner = $view->getOwner($oldPath);
122
+                    $targetOwner = $view->getOwner($newPath);
123
+
124
+                    if ($sourceOwner !== $targetOwner
125
+                        && $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
126
+                    ) {
127
+                        $fileMovedOutOfSharedFolder = true;
128
+                    }
129
+                }
130
+            }
131
+        } catch (\Exception $e) {
132
+            // do nothing, in this case we just disable the trashbin and continue
133
+            \OC::$server->getLogger()->logException($e, [
134
+                'message' => 'Trashbin storage could not check if a file was moved out of a shared folder.',
135
+                'level' => ILogger::DEBUG,
136
+                'app' => 'files_trashbin',
137
+            ]);
138
+        }
139
+
140
+        if($fileMovedOutOfSharedFolder) {
141
+            self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
142
+        } else {
143
+            self::$disableTrash = true;
144
+        }
145
+
146
+    }
147
+
148
+    /**
149
+     * @internal
150
+     */
151
+    public static function postRenameHook($params) {
152
+        self::$disableTrash = false;
153
+    }
154
+
155
+    /**
156
+     * Rename path1 to path2 by calling the wrapped storage.
157
+     *
158
+     * @param string $path1 first path
159
+     * @param string $path2 second path
160
+     * @return bool
161
+     */
162
+    public function rename($path1, $path2) {
163
+        $result = $this->storage->rename($path1, $path2);
164
+        if ($result === false) {
165
+            // when rename failed, the post_rename hook isn't triggered,
166
+            // but we still want to reenable the trash logic
167
+            self::$disableTrash = false;
168
+        }
169
+        return $result;
170
+    }
171
+
172
+    /**
173
+     * Deletes the given file by moving it into the trashbin.
174
+     *
175
+     * @param string $path path of file or folder to delete
176
+     *
177
+     * @return bool true if the operation succeeded, false otherwise
178
+     */
179
+    public function unlink($path) {
180
+        try {
181
+            if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
182
+                $result = $this->doDelete($path, 'unlink', true);
183
+                unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
184
+            } else {
185
+                $result = $this->doDelete($path, 'unlink');
186
+            }
187
+        } catch (GenericEncryptionException $e) {
188
+            // in case of a encryption exception we delete the file right away
189
+            $this->logger->info(
190
+                "Can't move file" .  $path .
191
+                "to the trash bin, therefore it was deleted right away");
192
+
193
+            $result = $this->storage->unlink($path);
194
+        }
195
+
196
+        return $result;
197
+    }
198
+
199
+    /**
200
+     * Deletes the given folder by moving it into the trashbin.
201
+     *
202
+     * @param string $path path of folder to delete
203
+     *
204
+     * @return bool true if the operation succeeded, false otherwise
205
+     */
206
+    public function rmdir($path) {
207
+        if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
208
+            $result = $this->doDelete($path, 'rmdir', true);
209
+            unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
210
+        } else {
211
+            $result = $this->doDelete($path, 'rmdir');
212
+        }
213
+
214
+        return $result;
215
+    }
216
+
217
+    /**
218
+     * check if it is a file located in data/user/files only files in the
219
+     * 'files' directory should be moved to the trash
220
+     *
221
+     * @param $path
222
+     * @return bool
223
+     */
224
+    protected function shouldMoveToTrash($path){
225
+
226
+        // check if there is a app which want to disable the trash bin for this file
227
+        $fileId = $this->storage->getCache()->getId($path);
228
+        $nodes = $this->rootFolder->getById($fileId);
229
+        foreach ($nodes as $node) {
230
+            $event = $this->createMoveToTrashEvent($node);
231
+            $this->eventDispatcher->dispatch('OCA\Files_Trashbin::moveToTrash', $event);
232
+            if ($event->shouldMoveToTrashBin() === false) {
233
+                return false;
234
+            }
235
+        }
236
+
237
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
238
+        $parts = explode('/', $normalized);
239
+        if (count($parts) < 4) {
240
+            return false;
241
+        }
242
+
243
+        if ($parts[2] === 'files' && $this->userManager->userExists($parts[1])) {
244
+            return true;
245
+        }
246
+
247
+        return false;
248
+    }
249
+
250
+    /**
251
+     * get move to trash event
252
+     *
253
+     * @param Node $node
254
+     * @return MoveToTrashEvent
255
+     */
256
+    protected function createMoveToTrashEvent(Node $node) {
257
+        return new MoveToTrashEvent($node);
258
+    }
259
+
260
+    /**
261
+     * Run the delete operation with the given method
262
+     *
263
+     * @param string $path path of file or folder to delete
264
+     * @param string $method either "unlink" or "rmdir"
265
+     * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
266
+     *
267
+     * @return bool true if the operation succeeded, false otherwise
268
+     */
269
+    private function doDelete($path, $method, $ownerOnly = false) {
270
+        if (self::$disableTrash
271
+            || !\OC::$server->getAppManager()->isEnabledForUser('files_trashbin')
272
+            || (pathinfo($path, PATHINFO_EXTENSION) === 'part')
273
+            || $this->shouldMoveToTrash($path) === false
274
+        ) {
275
+            return call_user_func_array([$this->storage, $method], [$path]);
276
+        }
277
+
278
+        // check permissions before we continue, this is especially important for
279
+        // shared files
280
+        if (!$this->isDeletable($path)) {
281
+            return false;
282
+        }
283
+
284
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
285
+        $result = true;
286
+        $view = Filesystem::getView();
287
+        if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
288
+            $this->deletedFiles[$normalized] = $normalized;
289
+            if ($filesPath = $view->getRelativePath($normalized)) {
290
+                $filesPath = trim($filesPath, '/');
291
+                $result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
292
+                // in cross-storage cases the file will be copied
293
+                // but not deleted, so we delete it here
294
+                if ($result) {
295
+                    call_user_func_array([$this->storage, $method], [$path]);
296
+                }
297
+            } else {
298
+                $result = call_user_func_array([$this->storage, $method], [$path]);
299
+            }
300
+            unset($this->deletedFiles[$normalized]);
301
+        } else if ($this->storage->file_exists($path)) {
302
+            $result = call_user_func_array([$this->storage, $method], [$path]);
303
+        }
304
+
305
+        return $result;
306
+    }
307
+
308
+    /**
309
+     * Setup the storate wrapper callback
310
+     */
311
+    public static function setupStorage() {
312
+        \OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
313
+            return new \OCA\Files_Trashbin\Storage(
314
+                array('storage' => $storage, 'mountPoint' => $mountPoint),
315
+                \OC::$server->getUserManager(),
316
+                \OC::$server->getLogger(),
317
+                \OC::$server->getEventDispatcher(),
318
+                \OC::$server->getLazyRootFolder()
319
+            );
320
+        }, 1);
321
+    }
322 322
 
323 323
 }
Please login to merge, or discard this patch.
apps/files_trashbin/ajax/delete.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -35,19 +35,19 @@  discard block
 block discarded – undo
35 35
 
36 36
 // "empty trash" command
37 37
 if (isset($_POST['allfiles']) && (string)$_POST['allfiles'] === 'true'){
38
-	$deleteAll = true;
39
-	if ($folder === '/' || $folder === '') {
40
-		OCA\Files_Trashbin\Trashbin::deleteAll();
41
-		$list = array();
42
-	} else {
43
-		$list[] = $folder;
44
-		$folder = dirname($folder);
45
-	}
38
+    $deleteAll = true;
39
+    if ($folder === '/' || $folder === '') {
40
+        OCA\Files_Trashbin\Trashbin::deleteAll();
41
+        $list = array();
42
+    } else {
43
+        $list[] = $folder;
44
+        $folder = dirname($folder);
45
+    }
46 46
 }
47 47
 else {
48
-	$deleteAll = false;
49
-	$files = (string)$_POST['files'];
50
-	$list = json_decode($files);
48
+    $deleteAll = false;
49
+    $files = (string)$_POST['files'];
50
+    $list = json_decode($files);
51 51
 }
52 52
 
53 53
 $folder = rtrim($folder, '/') . '/';
@@ -56,38 +56,38 @@  discard block
 block discarded – undo
56 56
 
57 57
 $i = 0;
58 58
 foreach ($list as $file) {
59
-	if ($folder === '/') {
60
-		$file = ltrim($file, '/');
61
-		$delimiter = strrpos($file, '.d');
62
-		$filename = substr($file, 0, $delimiter);
63
-		$timestamp =  substr($file, $delimiter+2);
64
-	} else {
65
-		$filename = $folder . '/' . $file;
66
-		$timestamp = null;
67
-	}
59
+    if ($folder === '/') {
60
+        $file = ltrim($file, '/');
61
+        $delimiter = strrpos($file, '.d');
62
+        $filename = substr($file, 0, $delimiter);
63
+        $timestamp =  substr($file, $delimiter+2);
64
+    } else {
65
+        $filename = $folder . '/' . $file;
66
+        $timestamp = null;
67
+    }
68 68
 
69
-	OCA\Files_Trashbin\Trashbin::delete($filename, \OCP\User::getUser(), $timestamp);
70
-	if (OCA\Files_Trashbin\Trashbin::file_exists($filename, $timestamp)) {
71
-		$error[] = $filename;
72
-		\OCP\Util::writeLog('trashbin','can\'t delete ' . $filename . ' permanently.', ILogger::ERROR);
73
-	}
74
-	// only list deleted files if not deleting everything
75
-	else if (!$deleteAll) {
76
-		$success[$i]['filename'] = $file;
77
-		$success[$i]['timestamp'] = $timestamp;
78
-		$i++;
79
-	}
69
+    OCA\Files_Trashbin\Trashbin::delete($filename, \OCP\User::getUser(), $timestamp);
70
+    if (OCA\Files_Trashbin\Trashbin::file_exists($filename, $timestamp)) {
71
+        $error[] = $filename;
72
+        \OCP\Util::writeLog('trashbin','can\'t delete ' . $filename . ' permanently.', ILogger::ERROR);
73
+    }
74
+    // only list deleted files if not deleting everything
75
+    else if (!$deleteAll) {
76
+        $success[$i]['filename'] = $file;
77
+        $success[$i]['timestamp'] = $timestamp;
78
+        $i++;
79
+    }
80 80
 }
81 81
 
82 82
 if ( $error ) {
83
-	$filelist = '';
84
-	foreach ( $error as $e ) {
85
-		$filelist .= $e.', ';
86
-	}
87
-	$l = \OC::$server->getL10N('files_trashbin');
88
-	$message = $l->t("Couldn't delete %s permanently", array(rtrim($filelist, ', ')));
89
-	\OC_JSON::error(array("data" => array("message" => $message,
90
-			                               "success" => $success, "error" => $error)));
83
+    $filelist = '';
84
+    foreach ( $error as $e ) {
85
+        $filelist .= $e.', ';
86
+    }
87
+    $l = \OC::$server->getL10N('files_trashbin');
88
+    $message = $l->t("Couldn't delete %s permanently", array(rtrim($filelist, ', ')));
89
+    \OC_JSON::error(array("data" => array("message" => $message,
90
+                                            "success" => $success, "error" => $error)));
91 91
 } else {
92
-	\OC_JSON::success(array("data" => array("success" => $success)));
92
+    \OC_JSON::success(array("data" => array("success" => $success)));
93 93
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
 $folder = isset($_POST['dir']) ? $_POST['dir'] : '/';
35 35
 
36 36
 // "empty trash" command
37
-if (isset($_POST['allfiles']) && (string)$_POST['allfiles'] === 'true'){
37
+if (isset($_POST['allfiles']) && (string) $_POST['allfiles'] === 'true') {
38 38
 	$deleteAll = true;
39 39
 	if ($folder === '/' || $folder === '') {
40 40
 		OCA\Files_Trashbin\Trashbin::deleteAll();
@@ -46,11 +46,11 @@  discard block
 block discarded – undo
46 46
 }
47 47
 else {
48 48
 	$deleteAll = false;
49
-	$files = (string)$_POST['files'];
49
+	$files = (string) $_POST['files'];
50 50
 	$list = json_decode($files);
51 51
 }
52 52
 
53
-$folder = rtrim($folder, '/') . '/';
53
+$folder = rtrim($folder, '/').'/';
54 54
 $error = array();
55 55
 $success = array();
56 56
 
@@ -60,16 +60,16 @@  discard block
 block discarded – undo
60 60
 		$file = ltrim($file, '/');
61 61
 		$delimiter = strrpos($file, '.d');
62 62
 		$filename = substr($file, 0, $delimiter);
63
-		$timestamp =  substr($file, $delimiter+2);
63
+		$timestamp = substr($file, $delimiter + 2);
64 64
 	} else {
65
-		$filename = $folder . '/' . $file;
65
+		$filename = $folder.'/'.$file;
66 66
 		$timestamp = null;
67 67
 	}
68 68
 
69 69
 	OCA\Files_Trashbin\Trashbin::delete($filename, \OCP\User::getUser(), $timestamp);
70 70
 	if (OCA\Files_Trashbin\Trashbin::file_exists($filename, $timestamp)) {
71 71
 		$error[] = $filename;
72
-		\OCP\Util::writeLog('trashbin','can\'t delete ' . $filename . ' permanently.', ILogger::ERROR);
72
+		\OCP\Util::writeLog('trashbin', 'can\'t delete '.$filename.' permanently.', ILogger::ERROR);
73 73
 	}
74 74
 	// only list deleted files if not deleting everything
75 75
 	else if (!$deleteAll) {
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
 	}
80 80
 }
81 81
 
82
-if ( $error ) {
82
+if ($error) {
83 83
 	$filelist = '';
84
-	foreach ( $error as $e ) {
84
+	foreach ($error as $e) {
85 85
 		$filelist .= $e.', ';
86 86
 	}
87 87
 	$l = \OC::$server->getL10N('files_trashbin');
Please login to merge, or discard this patch.
apps/files_trashbin/ajax/undelete.php 2 patches
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -35,25 +35,25 @@  discard block
 block discarded – undo
35 35
 
36 36
 $dir = '/';
37 37
 if (isset($_POST['dir'])) {
38
-	$dir = rtrim((string)$_POST['dir'], '/'). '/';
38
+    $dir = rtrim((string)$_POST['dir'], '/'). '/';
39 39
 }
40 40
 $allFiles = false;
41 41
 if (isset($_POST['allfiles']) && (string)$_POST['allfiles'] === 'true') {
42
-	$allFiles = true;
43
-	$list = array();
44
-	$dirListing = true;
45
-	if ($dir === '' || $dir === '/') {
46
-		$dirListing = false;
47
-	}
48
-	foreach (OCA\Files_Trashbin\Helper::getTrashFiles($dir, \OCP\User::getUser()) as $file) {
49
-		$fileName = $file['name'];
50
-		if (!$dirListing) {
51
-			$fileName .= '.d' . $file['mtime'];
52
-		}
53
-		$list[] = $fileName;
54
-	}
42
+    $allFiles = true;
43
+    $list = array();
44
+    $dirListing = true;
45
+    if ($dir === '' || $dir === '/') {
46
+        $dirListing = false;
47
+    }
48
+    foreach (OCA\Files_Trashbin\Helper::getTrashFiles($dir, \OCP\User::getUser()) as $file) {
49
+        $fileName = $file['name'];
50
+        if (!$dirListing) {
51
+            $fileName .= '.d' . $file['mtime'];
52
+        }
53
+        $list[] = $fileName;
54
+    }
55 55
 } else {
56
-	$list = json_decode($_POST['files']);
56
+    $list = json_decode($_POST['files']);
57 57
 }
58 58
 
59 59
 $error = array();
@@ -61,38 +61,38 @@  discard block
 block discarded – undo
61 61
 
62 62
 $i = 0;
63 63
 foreach ($list as $file) {
64
-	$path = $dir . '/' . $file;
65
-	if ($dir === '/') {
66
-		$file = ltrim($file, '/');
67
-		$delimiter = strrpos($file, '.d');
68
-		$filename = substr($file, 0, $delimiter);
69
-		$timestamp =  substr($file, $delimiter+2);
70
-	} else {
71
-		$path_parts = pathinfo($file);
72
-		$filename = $path_parts['basename'];
73
-		$timestamp = null;
74
-	}
64
+    $path = $dir . '/' . $file;
65
+    if ($dir === '/') {
66
+        $file = ltrim($file, '/');
67
+        $delimiter = strrpos($file, '.d');
68
+        $filename = substr($file, 0, $delimiter);
69
+        $timestamp =  substr($file, $delimiter+2);
70
+    } else {
71
+        $path_parts = pathinfo($file);
72
+        $filename = $path_parts['basename'];
73
+        $timestamp = null;
74
+    }
75 75
 
76
-	if ( !OCA\Files_Trashbin\Trashbin::restore($path, $filename, $timestamp) ) {
77
-		$error[] = $filename;
78
-		\OCP\Util::writeLog('trashbin', 'can\'t restore ' . $filename, ILogger::ERROR);
79
-	} else {
80
-		$success[$i]['filename'] = $file;
81
-		$success[$i]['timestamp'] = $timestamp;
82
-		$i++;
83
-	}
76
+    if ( !OCA\Files_Trashbin\Trashbin::restore($path, $filename, $timestamp) ) {
77
+        $error[] = $filename;
78
+        \OCP\Util::writeLog('trashbin', 'can\'t restore ' . $filename, ILogger::ERROR);
79
+    } else {
80
+        $success[$i]['filename'] = $file;
81
+        $success[$i]['timestamp'] = $timestamp;
82
+        $i++;
83
+    }
84 84
 
85 85
 }
86 86
 
87 87
 if ( $error ) {
88
-	$filelist = '';
89
-	foreach ( $error as $e ) {
90
-		$filelist .= $e.', ';
91
-	}
92
-	$l = OC::$server->getL10N('files_trashbin');
93
-	$message = $l->t("Couldn't restore %s", array(rtrim($filelist, ', ')));
94
-	\OC_JSON::error(array("data" => array("message" => $message,
95
-										  "success" => $success, "error" => $error)));
88
+    $filelist = '';
89
+    foreach ( $error as $e ) {
90
+        $filelist .= $e.', ';
91
+    }
92
+    $l = OC::$server->getL10N('files_trashbin');
93
+    $message = $l->t("Couldn't restore %s", array(rtrim($filelist, ', ')));
94
+    \OC_JSON::error(array("data" => array("message" => $message,
95
+                                            "success" => $success, "error" => $error)));
96 96
 } else {
97
-	\OC_JSON::success(array("data" => array("success" => $success)));
97
+    \OC_JSON::success(array("data" => array("success" => $success)));
98 98
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -35,10 +35,10 @@  discard block
 block discarded – undo
35 35
 
36 36
 $dir = '/';
37 37
 if (isset($_POST['dir'])) {
38
-	$dir = rtrim((string)$_POST['dir'], '/'). '/';
38
+	$dir = rtrim((string) $_POST['dir'], '/').'/';
39 39
 }
40 40
 $allFiles = false;
41
-if (isset($_POST['allfiles']) && (string)$_POST['allfiles'] === 'true') {
41
+if (isset($_POST['allfiles']) && (string) $_POST['allfiles'] === 'true') {
42 42
 	$allFiles = true;
43 43
 	$list = array();
44 44
 	$dirListing = true;
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 	foreach (OCA\Files_Trashbin\Helper::getTrashFiles($dir, \OCP\User::getUser()) as $file) {
49 49
 		$fileName = $file['name'];
50 50
 		if (!$dirListing) {
51
-			$fileName .= '.d' . $file['mtime'];
51
+			$fileName .= '.d'.$file['mtime'];
52 52
 		}
53 53
 		$list[] = $fileName;
54 54
 	}
@@ -61,21 +61,21 @@  discard block
 block discarded – undo
61 61
 
62 62
 $i = 0;
63 63
 foreach ($list as $file) {
64
-	$path = $dir . '/' . $file;
64
+	$path = $dir.'/'.$file;
65 65
 	if ($dir === '/') {
66 66
 		$file = ltrim($file, '/');
67 67
 		$delimiter = strrpos($file, '.d');
68 68
 		$filename = substr($file, 0, $delimiter);
69
-		$timestamp =  substr($file, $delimiter+2);
69
+		$timestamp = substr($file, $delimiter + 2);
70 70
 	} else {
71 71
 		$path_parts = pathinfo($file);
72 72
 		$filename = $path_parts['basename'];
73 73
 		$timestamp = null;
74 74
 	}
75 75
 
76
-	if ( !OCA\Files_Trashbin\Trashbin::restore($path, $filename, $timestamp) ) {
76
+	if (!OCA\Files_Trashbin\Trashbin::restore($path, $filename, $timestamp)) {
77 77
 		$error[] = $filename;
78
-		\OCP\Util::writeLog('trashbin', 'can\'t restore ' . $filename, ILogger::ERROR);
78
+		\OCP\Util::writeLog('trashbin', 'can\'t restore '.$filename, ILogger::ERROR);
79 79
 	} else {
80 80
 		$success[$i]['filename'] = $file;
81 81
 		$success[$i]['timestamp'] = $timestamp;
@@ -84,9 +84,9 @@  discard block
 block discarded – undo
84 84
 
85 85
 }
86 86
 
87
-if ( $error ) {
87
+if ($error) {
88 88
 	$filelist = '';
89
-	foreach ( $error as $e ) {
89
+	foreach ($error as $e) {
90 90
 		$filelist .= $e.', ';
91 91
 	}
92 92
 	$l = OC::$server->getL10N('files_trashbin');
Please login to merge, or discard this patch.