Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
apps/files_external/lib/Lib/Storage/Swift.php 2 patches
Indentation   +569 added lines, -569 removed lines patch added patch discarded remove patch
@@ -52,577 +52,577 @@
 block discarded – undo
52 52
 use OpenStack\ObjectStore\v1\Models\StorageObject;
53 53
 
54 54
 class Swift extends \OC\Files\Storage\Common {
55
-	/** @var SwiftFactory */
56
-	private $connectionFactory;
57
-	/**
58
-	 * @var \OpenStack\ObjectStore\v1\Models\Container
59
-	 */
60
-	private $container;
61
-	/**
62
-	 * @var string
63
-	 */
64
-	private $bucket;
65
-	/**
66
-	 * Connection parameters
67
-	 *
68
-	 * @var array
69
-	 */
70
-	private $params;
71
-
72
-	/** @var string */
73
-	private $id;
74
-
75
-	/** @var \OC\Files\ObjectStore\Swift */
76
-	private $objectStore;
77
-
78
-	/**
79
-	 * Key value cache mapping path to data object. Maps path to
80
-	 * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
81
-	 * paths and path to false for not existing paths.
82
-	 *
83
-	 * @var \OCP\ICache
84
-	 */
85
-	private $objectCache;
86
-
87
-	/**
88
-	 * @param string $path
89
-	 * @return mixed|string
90
-	 */
91
-	private function normalizePath(string $path) {
92
-		$path = trim($path, '/');
93
-
94
-		if (!$path) {
95
-			$path = '.';
96
-		}
97
-
98
-		$path = str_replace('#', '%23', $path);
99
-
100
-		return $path;
101
-	}
102
-
103
-	const SUBCONTAINER_FILE = '.subcontainers';
104
-
105
-	/**
106
-	 * translate directory path to container name
107
-	 *
108
-	 * @param string $path
109
-	 * @return string
110
-	 */
111
-
112
-	/**
113
-	 * Fetches an object from the API.
114
-	 * If the object is cached already or a
115
-	 * failed "doesn't exist" response was cached,
116
-	 * that one will be returned.
117
-	 *
118
-	 * @param string $path
119
-	 * @return StorageObject|bool object
120
-	 * or false if the object did not exist
121
-	 * @throws \OCP\Files\StorageAuthException
122
-	 * @throws \OCP\Files\StorageNotAvailableException
123
-	 */
124
-	private function fetchObject(string $path) {
125
-		if ($this->objectCache->hasKey($path)) {
126
-			// might be "false" if object did not exist from last check
127
-			return $this->objectCache->get($path);
128
-		}
129
-		try {
130
-			$object = $this->getContainer()->getObject($path);
131
-			$object->retrieve();
132
-			$this->objectCache->set($path, $object);
133
-			return $object;
134
-		} catch (BadResponseError $e) {
135
-			// Expected response is "404 Not Found", so only log if it isn't
136
-			if ($e->getResponse()->getStatusCode() !== 404) {
137
-				\OC::$server->getLogger()->logException($e, [
138
-					'level' => ILogger::ERROR,
139
-					'app' => 'files_external',
140
-				]);
141
-			}
142
-			$this->objectCache->set($path, false);
143
-			return false;
144
-		}
145
-	}
146
-
147
-	/**
148
-	 * Returns whether the given path exists.
149
-	 *
150
-	 * @param string $path
151
-	 *
152
-	 * @return bool true if the object exist, false otherwise
153
-	 * @throws \OCP\Files\StorageAuthException
154
-	 * @throws \OCP\Files\StorageNotAvailableException
155
-	 */
156
-	private function doesObjectExist($path) {
157
-		return $this->fetchObject($path) !== false;
158
-	}
159
-
160
-	public function __construct($params) {
161
-		if ((empty($params['key']) and empty($params['password']))
162
-			or (empty($params['user']) && empty($params['userid'])) or empty($params['bucket'])
163
-			or empty($params['region'])
164
-		) {
165
-			throw new StorageBadConfigException("API Key or password, Username, Bucket and Region have to be configured.");
166
-		}
167
-
168
-		$user = $params['user'];
169
-		$this->id = 'swift::' . $user . md5($params['bucket']);
170
-
171
-		$bucketUrl = new Uri($params['bucket']);
172
-		if ($bucketUrl->getHost()) {
173
-			$params['bucket'] = basename($bucketUrl->getPath());
174
-			$params['endpoint_url'] = (string)$bucketUrl->withPath(dirname($bucketUrl->getPath()));
175
-		}
176
-
177
-		if (empty($params['url'])) {
178
-			$params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
179
-		}
180
-
181
-		if (empty($params['service_name'])) {
182
-			$params['service_name'] = 'cloudFiles';
183
-		}
184
-
185
-		$params['autocreate'] = true;
186
-
187
-		if (isset($params['domain'])) {
188
-			$params['user'] = [
189
-				'name' => $params['user'],
190
-				'password' => $params['password'],
191
-				'domain' => [
192
-					'name' => $params['domain'],
193
-				]
194
-			];
195
-		}
196
-
197
-		$this->params = $params;
198
-		// FIXME: private class...
199
-		$this->objectCache = new \OC\Cache\CappedMemoryCache();
200
-		$this->connectionFactory = new SwiftFactory(
201
-			\OC::$server->getMemCacheFactory()->createDistributed('swift/'),
202
-			$this->params,
203
-			\OC::$server->getLogger()
204
-		);
205
-		$this->objectStore = new \OC\Files\ObjectStore\Swift($this->params, $this->connectionFactory);
206
-		$this->bucket = $params['bucket'];
207
-	}
208
-
209
-	public function mkdir($path) {
210
-		$path = $this->normalizePath($path);
211
-
212
-		if ($this->is_dir($path)) {
213
-			return false;
214
-		}
215
-
216
-		if ($path !== '.') {
217
-			$path .= '/';
218
-		}
219
-
220
-		try {
221
-			$this->getContainer()->createObject([
222
-				'name' => $path,
223
-				'content' => '',
224
-				'headers' => ['content-type' => 'httpd/unix-directory']
225
-			]);
226
-			// invalidate so that the next access gets the real object
227
-			// with all properties
228
-			$this->objectCache->remove($path);
229
-		} catch (BadResponseError $e) {
230
-			\OC::$server->getLogger()->logException($e, [
231
-				'level' => ILogger::ERROR,
232
-				'app' => 'files_external',
233
-			]);
234
-			return false;
235
-		}
236
-
237
-		return true;
238
-	}
239
-
240
-	public function file_exists($path) {
241
-		$path = $this->normalizePath($path);
242
-
243
-		if ($path !== '.' && $this->is_dir($path)) {
244
-			$path .= '/';
245
-		}
246
-
247
-		return $this->doesObjectExist($path);
248
-	}
249
-
250
-	public function rmdir($path) {
251
-		$path = $this->normalizePath($path);
252
-
253
-		if (!$this->is_dir($path) || !$this->isDeletable($path)) {
254
-			return false;
255
-		}
256
-
257
-		$dh = $this->opendir($path);
258
-		while ($file = readdir($dh)) {
259
-			if (\OC\Files\Filesystem::isIgnoredDir($file)) {
260
-				continue;
261
-			}
262
-
263
-			if ($this->is_dir($path . '/' . $file)) {
264
-				$this->rmdir($path . '/' . $file);
265
-			} else {
266
-				$this->unlink($path . '/' . $file);
267
-			}
268
-		}
269
-
270
-		try {
271
-			$this->objectStore->deleteObject($path . '/');
272
-			$this->objectCache->remove($path . '/');
273
-		} catch (BadResponseError $e) {
274
-			\OC::$server->getLogger()->logException($e, [
275
-				'level' => ILogger::ERROR,
276
-				'app' => 'files_external',
277
-			]);
278
-			return false;
279
-		}
280
-
281
-		return true;
282
-	}
283
-
284
-	public function opendir($path) {
285
-		$path = $this->normalizePath($path);
286
-
287
-		if ($path === '.') {
288
-			$path = '';
289
-		} else {
290
-			$path .= '/';
291
-		}
55
+    /** @var SwiftFactory */
56
+    private $connectionFactory;
57
+    /**
58
+     * @var \OpenStack\ObjectStore\v1\Models\Container
59
+     */
60
+    private $container;
61
+    /**
62
+     * @var string
63
+     */
64
+    private $bucket;
65
+    /**
66
+     * Connection parameters
67
+     *
68
+     * @var array
69
+     */
70
+    private $params;
71
+
72
+    /** @var string */
73
+    private $id;
74
+
75
+    /** @var \OC\Files\ObjectStore\Swift */
76
+    private $objectStore;
77
+
78
+    /**
79
+     * Key value cache mapping path to data object. Maps path to
80
+     * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
81
+     * paths and path to false for not existing paths.
82
+     *
83
+     * @var \OCP\ICache
84
+     */
85
+    private $objectCache;
86
+
87
+    /**
88
+     * @param string $path
89
+     * @return mixed|string
90
+     */
91
+    private function normalizePath(string $path) {
92
+        $path = trim($path, '/');
93
+
94
+        if (!$path) {
95
+            $path = '.';
96
+        }
97
+
98
+        $path = str_replace('#', '%23', $path);
99
+
100
+        return $path;
101
+    }
102
+
103
+    const SUBCONTAINER_FILE = '.subcontainers';
104
+
105
+    /**
106
+     * translate directory path to container name
107
+     *
108
+     * @param string $path
109
+     * @return string
110
+     */
111
+
112
+    /**
113
+     * Fetches an object from the API.
114
+     * If the object is cached already or a
115
+     * failed "doesn't exist" response was cached,
116
+     * that one will be returned.
117
+     *
118
+     * @param string $path
119
+     * @return StorageObject|bool object
120
+     * or false if the object did not exist
121
+     * @throws \OCP\Files\StorageAuthException
122
+     * @throws \OCP\Files\StorageNotAvailableException
123
+     */
124
+    private function fetchObject(string $path) {
125
+        if ($this->objectCache->hasKey($path)) {
126
+            // might be "false" if object did not exist from last check
127
+            return $this->objectCache->get($path);
128
+        }
129
+        try {
130
+            $object = $this->getContainer()->getObject($path);
131
+            $object->retrieve();
132
+            $this->objectCache->set($path, $object);
133
+            return $object;
134
+        } catch (BadResponseError $e) {
135
+            // Expected response is "404 Not Found", so only log if it isn't
136
+            if ($e->getResponse()->getStatusCode() !== 404) {
137
+                \OC::$server->getLogger()->logException($e, [
138
+                    'level' => ILogger::ERROR,
139
+                    'app' => 'files_external',
140
+                ]);
141
+            }
142
+            $this->objectCache->set($path, false);
143
+            return false;
144
+        }
145
+    }
146
+
147
+    /**
148
+     * Returns whether the given path exists.
149
+     *
150
+     * @param string $path
151
+     *
152
+     * @return bool true if the object exist, false otherwise
153
+     * @throws \OCP\Files\StorageAuthException
154
+     * @throws \OCP\Files\StorageNotAvailableException
155
+     */
156
+    private function doesObjectExist($path) {
157
+        return $this->fetchObject($path) !== false;
158
+    }
159
+
160
+    public function __construct($params) {
161
+        if ((empty($params['key']) and empty($params['password']))
162
+            or (empty($params['user']) && empty($params['userid'])) or empty($params['bucket'])
163
+            or empty($params['region'])
164
+        ) {
165
+            throw new StorageBadConfigException("API Key or password, Username, Bucket and Region have to be configured.");
166
+        }
167
+
168
+        $user = $params['user'];
169
+        $this->id = 'swift::' . $user . md5($params['bucket']);
170
+
171
+        $bucketUrl = new Uri($params['bucket']);
172
+        if ($bucketUrl->getHost()) {
173
+            $params['bucket'] = basename($bucketUrl->getPath());
174
+            $params['endpoint_url'] = (string)$bucketUrl->withPath(dirname($bucketUrl->getPath()));
175
+        }
176
+
177
+        if (empty($params['url'])) {
178
+            $params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
179
+        }
180
+
181
+        if (empty($params['service_name'])) {
182
+            $params['service_name'] = 'cloudFiles';
183
+        }
184
+
185
+        $params['autocreate'] = true;
186
+
187
+        if (isset($params['domain'])) {
188
+            $params['user'] = [
189
+                'name' => $params['user'],
190
+                'password' => $params['password'],
191
+                'domain' => [
192
+                    'name' => $params['domain'],
193
+                ]
194
+            ];
195
+        }
196
+
197
+        $this->params = $params;
198
+        // FIXME: private class...
199
+        $this->objectCache = new \OC\Cache\CappedMemoryCache();
200
+        $this->connectionFactory = new SwiftFactory(
201
+            \OC::$server->getMemCacheFactory()->createDistributed('swift/'),
202
+            $this->params,
203
+            \OC::$server->getLogger()
204
+        );
205
+        $this->objectStore = new \OC\Files\ObjectStore\Swift($this->params, $this->connectionFactory);
206
+        $this->bucket = $params['bucket'];
207
+    }
208
+
209
+    public function mkdir($path) {
210
+        $path = $this->normalizePath($path);
211
+
212
+        if ($this->is_dir($path)) {
213
+            return false;
214
+        }
215
+
216
+        if ($path !== '.') {
217
+            $path .= '/';
218
+        }
219
+
220
+        try {
221
+            $this->getContainer()->createObject([
222
+                'name' => $path,
223
+                'content' => '',
224
+                'headers' => ['content-type' => 'httpd/unix-directory']
225
+            ]);
226
+            // invalidate so that the next access gets the real object
227
+            // with all properties
228
+            $this->objectCache->remove($path);
229
+        } catch (BadResponseError $e) {
230
+            \OC::$server->getLogger()->logException($e, [
231
+                'level' => ILogger::ERROR,
232
+                'app' => 'files_external',
233
+            ]);
234
+            return false;
235
+        }
236
+
237
+        return true;
238
+    }
239
+
240
+    public function file_exists($path) {
241
+        $path = $this->normalizePath($path);
242
+
243
+        if ($path !== '.' && $this->is_dir($path)) {
244
+            $path .= '/';
245
+        }
246
+
247
+        return $this->doesObjectExist($path);
248
+    }
249
+
250
+    public function rmdir($path) {
251
+        $path = $this->normalizePath($path);
252
+
253
+        if (!$this->is_dir($path) || !$this->isDeletable($path)) {
254
+            return false;
255
+        }
256
+
257
+        $dh = $this->opendir($path);
258
+        while ($file = readdir($dh)) {
259
+            if (\OC\Files\Filesystem::isIgnoredDir($file)) {
260
+                continue;
261
+            }
262
+
263
+            if ($this->is_dir($path . '/' . $file)) {
264
+                $this->rmdir($path . '/' . $file);
265
+            } else {
266
+                $this->unlink($path . '/' . $file);
267
+            }
268
+        }
269
+
270
+        try {
271
+            $this->objectStore->deleteObject($path . '/');
272
+            $this->objectCache->remove($path . '/');
273
+        } catch (BadResponseError $e) {
274
+            \OC::$server->getLogger()->logException($e, [
275
+                'level' => ILogger::ERROR,
276
+                'app' => 'files_external',
277
+            ]);
278
+            return false;
279
+        }
280
+
281
+        return true;
282
+    }
283
+
284
+    public function opendir($path) {
285
+        $path = $this->normalizePath($path);
286
+
287
+        if ($path === '.') {
288
+            $path = '';
289
+        } else {
290
+            $path .= '/';
291
+        }
292 292
 
293 293
 //		$path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #
294 294
 
295
-		try {
296
-			$files = [];
297
-			$objects = $this->getContainer()->listObjects([
298
-				'prefix' => $path,
299
-				'delimiter' => '/'
300
-			]);
301
-
302
-			/** @var StorageObject $object */
303
-			foreach ($objects as $object) {
304
-				$file = basename($object->name);
305
-				if ($file !== basename($path) && $file !== '.') {
306
-					$files[] = $file;
307
-				}
308
-			}
309
-
310
-			return IteratorDirectory::wrap($files);
311
-		} catch (\Exception $e) {
312
-			\OC::$server->getLogger()->logException($e, [
313
-				'level' => ILogger::ERROR,
314
-				'app' => 'files_external',
315
-			]);
316
-			return false;
317
-		}
318
-
319
-	}
320
-
321
-	public function stat($path) {
322
-		$path = $this->normalizePath($path);
323
-
324
-		if ($path === '.') {
325
-			$path = '';
326
-		} else if ($this->is_dir($path)) {
327
-			$path .= '/';
328
-		}
329
-
330
-		try {
331
-			$object = $this->fetchObject($path);
332
-			if (!$object) {
333
-				return false;
334
-			}
335
-		} catch (BadResponseError $e) {
336
-			\OC::$server->getLogger()->logException($e, [
337
-				'level' => ILogger::ERROR,
338
-				'app' => 'files_external',
339
-			]);
340
-			return false;
341
-		}
342
-
343
-		$dateTime = $object->lastModified ? \DateTime::createFromFormat(\DateTime::RFC1123, $object->lastModified) : false;
344
-		$mtime = $dateTime ? $dateTime->getTimestamp() : null;
345
-		$objectMetadata = $object->getMetadata();
346
-		if (isset($objectMetadata['timestamp'])) {
347
-			$mtime = $objectMetadata['timestamp'];
348
-		}
349
-
350
-		if (!empty($mtime)) {
351
-			$mtime = floor($mtime);
352
-		}
353
-
354
-		$stat = [];
355
-		$stat['size'] = (int)$object->contentLength;
356
-		$stat['mtime'] = $mtime;
357
-		$stat['atime'] = time();
358
-		return $stat;
359
-	}
360
-
361
-	public function filetype($path) {
362
-		$path = $this->normalizePath($path);
363
-
364
-		if ($path !== '.' && $this->doesObjectExist($path)) {
365
-			return 'file';
366
-		}
367
-
368
-		if ($path !== '.') {
369
-			$path .= '/';
370
-		}
371
-
372
-		if ($this->doesObjectExist($path)) {
373
-			return 'dir';
374
-		}
375
-	}
376
-
377
-	public function unlink($path) {
378
-		$path = $this->normalizePath($path);
379
-
380
-		if ($this->is_dir($path)) {
381
-			return $this->rmdir($path);
382
-		}
383
-
384
-		try {
385
-			$this->objectStore->deleteObject($path);
386
-			$this->objectCache->remove($path);
387
-			$this->objectCache->remove($path . '/');
388
-		} catch (BadResponseError $e) {
389
-			if ($e->getResponse()->getStatusCode() !== 404) {
390
-				\OC::$server->getLogger()->logException($e, [
391
-					'level' => ILogger::ERROR,
392
-					'app' => 'files_external',
393
-				]);
394
-				throw $e;
395
-			}
396
-		}
397
-
398
-		return true;
399
-	}
400
-
401
-	public function fopen($path, $mode) {
402
-		$path = $this->normalizePath($path);
403
-
404
-		switch ($mode) {
405
-			case 'a':
406
-			case 'ab':
407
-			case 'a+':
408
-				return false;
409
-			case 'r':
410
-			case 'rb':
411
-				try {
412
-					return $this->objectStore->readObject($path);
413
-				} catch (BadResponseError $e) {
414
-					\OC::$server->getLogger()->logException($e, [
415
-						'level' => ILogger::ERROR,
416
-						'app' => 'files_external',
417
-					]);
418
-					return false;
419
-				}
420
-			case 'w':
421
-			case 'wb':
422
-			case 'r+':
423
-			case 'w+':
424
-			case 'wb+':
425
-			case 'x':
426
-			case 'x+':
427
-			case 'c':
428
-			case 'c+':
429
-				if (strrpos($path, '.') !== false) {
430
-					$ext = substr($path, strrpos($path, '.'));
431
-				} else {
432
-					$ext = '';
433
-				}
434
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
435
-				// Fetch existing file if required
436
-				if ($mode[0] !== 'w' && $this->file_exists($path)) {
437
-					if ($mode[0] === 'x') {
438
-						// File cannot already exist
439
-						return false;
440
-					}
441
-					$source = $this->fopen($path, 'r');
442
-					file_put_contents($tmpFile, $source);
443
-				}
444
-				$handle = fopen($tmpFile, $mode);
445
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
446
-					$this->writeBack($tmpFile, $path);
447
-				});
448
-		}
449
-	}
450
-
451
-	public function touch($path, $mtime = null) {
452
-		$path = $this->normalizePath($path);
453
-		if (is_null($mtime)) {
454
-			$mtime = time();
455
-		}
456
-		$metadata = ['timestamp' => (string)$mtime];
457
-		if ($this->file_exists($path)) {
458
-			if ($this->is_dir($path) && $path !== '.') {
459
-				$path .= '/';
460
-			}
461
-
462
-			$object = $this->fetchObject($path);
463
-			if ($object->mergeMetadata($metadata)) {
464
-				// invalidate target object to force repopulation on fetch
465
-				$this->objectCache->remove($path);
466
-			}
467
-			return true;
468
-		} else {
469
-			$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
470
-			$this->getContainer()->createObject([
471
-				'name' => $path,
472
-				'content' => '',
473
-				'headers' => ['content-type' => 'httpd/unix-directory']
474
-			]);
475
-			// invalidate target object to force repopulation on fetch
476
-			$this->objectCache->remove($path);
477
-			return true;
478
-		}
479
-	}
480
-
481
-	public function copy($path1, $path2) {
482
-		$path1 = $this->normalizePath($path1);
483
-		$path2 = $this->normalizePath($path2);
484
-
485
-		$fileType = $this->filetype($path1);
486
-		if ($fileType) {
487
-			// make way
488
-			$this->unlink($path2);
489
-		}
490
-
491
-		if ($fileType === 'file') {
492
-			try {
493
-				$source = $this->fetchObject($path1);
494
-				$source->copy([
495
-					'destination' => $this->bucket . '/' . $path2
496
-				]);
497
-				// invalidate target object to force repopulation on fetch
498
-				$this->objectCache->remove($path2);
499
-				$this->objectCache->remove($path2 . '/');
500
-			} catch (BadResponseError $e) {
501
-				\OC::$server->getLogger()->logException($e, [
502
-					'level' => ILogger::ERROR,
503
-					'app' => 'files_external',
504
-				]);
505
-				return false;
506
-			}
507
-
508
-		} else if ($fileType === 'dir') {
509
-			try {
510
-				$source = $this->fetchObject($path1 . '/');
511
-				$source->copy([
512
-					'destination' => $this->bucket . '/' . $path2 . '/'
513
-				]);
514
-				// invalidate target object to force repopulation on fetch
515
-				$this->objectCache->remove($path2);
516
-				$this->objectCache->remove($path2 . '/');
517
-			} catch (BadResponseError $e) {
518
-				\OC::$server->getLogger()->logException($e, [
519
-					'level' => ILogger::ERROR,
520
-					'app' => 'files_external',
521
-				]);
522
-				return false;
523
-			}
524
-
525
-			$dh = $this->opendir($path1);
526
-			while ($file = readdir($dh)) {
527
-				if (\OC\Files\Filesystem::isIgnoredDir($file)) {
528
-					continue;
529
-				}
530
-
531
-				$source = $path1 . '/' . $file;
532
-				$target = $path2 . '/' . $file;
533
-				$this->copy($source, $target);
534
-			}
535
-
536
-		} else {
537
-			//file does not exist
538
-			return false;
539
-		}
540
-
541
-		return true;
542
-	}
543
-
544
-	public function rename($path1, $path2) {
545
-		$path1 = $this->normalizePath($path1);
546
-		$path2 = $this->normalizePath($path2);
547
-
548
-		$fileType = $this->filetype($path1);
549
-
550
-		if ($fileType === 'dir' || $fileType === 'file') {
551
-			// copy
552
-			if ($this->copy($path1, $path2) === false) {
553
-				return false;
554
-			}
555
-
556
-			// cleanup
557
-			if ($this->unlink($path1) === false) {
558
-				throw new \Exception('failed to remove original');
559
-				$this->unlink($path2);
560
-				return false;
561
-			}
562
-
563
-			return true;
564
-		}
565
-
566
-		return false;
567
-	}
568
-
569
-	public function getId() {
570
-		return $this->id;
571
-	}
572
-
573
-	/**
574
-	 * Returns the initialized object store container.
575
-	 *
576
-	 * @return \OpenStack\ObjectStore\v1\Models\Container
577
-	 * @throws \OCP\Files\StorageAuthException
578
-	 * @throws \OCP\Files\StorageNotAvailableException
579
-	 */
580
-	public function getContainer() {
581
-		if (is_null($this->container)) {
582
-			$this->container = $this->connectionFactory->getContainer();
583
-
584
-			if (!$this->file_exists('.')) {
585
-				$this->mkdir('.');
586
-			}
587
-		}
588
-		return $this->container;
589
-	}
590
-
591
-	public function writeBack($tmpFile, $path) {
592
-		$fileData = fopen($tmpFile, 'r');
593
-		$this->objectStore->writeObject($path, $fileData);
594
-		// invalidate target object to force repopulation on fetch
595
-		$this->objectCache->remove($path);
596
-		unlink($tmpFile);
597
-	}
598
-
599
-	public function hasUpdated($path, $time) {
600
-		if ($this->is_file($path)) {
601
-			return parent::hasUpdated($path, $time);
602
-		}
603
-		$path = $this->normalizePath($path);
604
-		$dh = $this->opendir($path);
605
-		$content = [];
606
-		while (($file = readdir($dh)) !== false) {
607
-			$content[] = $file;
608
-		}
609
-		if ($path === '.') {
610
-			$path = '';
611
-		}
612
-		$cachedContent = $this->getCache()->getFolderContents($path);
613
-		$cachedNames = array_map(function ($content) {
614
-			return $content['name'];
615
-		}, $cachedContent);
616
-		sort($cachedNames);
617
-		sort($content);
618
-		return $cachedNames !== $content;
619
-	}
620
-
621
-	/**
622
-	 * check if curl is installed
623
-	 */
624
-	public static function checkDependencies() {
625
-		return true;
626
-	}
295
+        try {
296
+            $files = [];
297
+            $objects = $this->getContainer()->listObjects([
298
+                'prefix' => $path,
299
+                'delimiter' => '/'
300
+            ]);
301
+
302
+            /** @var StorageObject $object */
303
+            foreach ($objects as $object) {
304
+                $file = basename($object->name);
305
+                if ($file !== basename($path) && $file !== '.') {
306
+                    $files[] = $file;
307
+                }
308
+            }
309
+
310
+            return IteratorDirectory::wrap($files);
311
+        } catch (\Exception $e) {
312
+            \OC::$server->getLogger()->logException($e, [
313
+                'level' => ILogger::ERROR,
314
+                'app' => 'files_external',
315
+            ]);
316
+            return false;
317
+        }
318
+
319
+    }
320
+
321
+    public function stat($path) {
322
+        $path = $this->normalizePath($path);
323
+
324
+        if ($path === '.') {
325
+            $path = '';
326
+        } else if ($this->is_dir($path)) {
327
+            $path .= '/';
328
+        }
329
+
330
+        try {
331
+            $object = $this->fetchObject($path);
332
+            if (!$object) {
333
+                return false;
334
+            }
335
+        } catch (BadResponseError $e) {
336
+            \OC::$server->getLogger()->logException($e, [
337
+                'level' => ILogger::ERROR,
338
+                'app' => 'files_external',
339
+            ]);
340
+            return false;
341
+        }
342
+
343
+        $dateTime = $object->lastModified ? \DateTime::createFromFormat(\DateTime::RFC1123, $object->lastModified) : false;
344
+        $mtime = $dateTime ? $dateTime->getTimestamp() : null;
345
+        $objectMetadata = $object->getMetadata();
346
+        if (isset($objectMetadata['timestamp'])) {
347
+            $mtime = $objectMetadata['timestamp'];
348
+        }
349
+
350
+        if (!empty($mtime)) {
351
+            $mtime = floor($mtime);
352
+        }
353
+
354
+        $stat = [];
355
+        $stat['size'] = (int)$object->contentLength;
356
+        $stat['mtime'] = $mtime;
357
+        $stat['atime'] = time();
358
+        return $stat;
359
+    }
360
+
361
+    public function filetype($path) {
362
+        $path = $this->normalizePath($path);
363
+
364
+        if ($path !== '.' && $this->doesObjectExist($path)) {
365
+            return 'file';
366
+        }
367
+
368
+        if ($path !== '.') {
369
+            $path .= '/';
370
+        }
371
+
372
+        if ($this->doesObjectExist($path)) {
373
+            return 'dir';
374
+        }
375
+    }
376
+
377
+    public function unlink($path) {
378
+        $path = $this->normalizePath($path);
379
+
380
+        if ($this->is_dir($path)) {
381
+            return $this->rmdir($path);
382
+        }
383
+
384
+        try {
385
+            $this->objectStore->deleteObject($path);
386
+            $this->objectCache->remove($path);
387
+            $this->objectCache->remove($path . '/');
388
+        } catch (BadResponseError $e) {
389
+            if ($e->getResponse()->getStatusCode() !== 404) {
390
+                \OC::$server->getLogger()->logException($e, [
391
+                    'level' => ILogger::ERROR,
392
+                    'app' => 'files_external',
393
+                ]);
394
+                throw $e;
395
+            }
396
+        }
397
+
398
+        return true;
399
+    }
400
+
401
+    public function fopen($path, $mode) {
402
+        $path = $this->normalizePath($path);
403
+
404
+        switch ($mode) {
405
+            case 'a':
406
+            case 'ab':
407
+            case 'a+':
408
+                return false;
409
+            case 'r':
410
+            case 'rb':
411
+                try {
412
+                    return $this->objectStore->readObject($path);
413
+                } catch (BadResponseError $e) {
414
+                    \OC::$server->getLogger()->logException($e, [
415
+                        'level' => ILogger::ERROR,
416
+                        'app' => 'files_external',
417
+                    ]);
418
+                    return false;
419
+                }
420
+            case 'w':
421
+            case 'wb':
422
+            case 'r+':
423
+            case 'w+':
424
+            case 'wb+':
425
+            case 'x':
426
+            case 'x+':
427
+            case 'c':
428
+            case 'c+':
429
+                if (strrpos($path, '.') !== false) {
430
+                    $ext = substr($path, strrpos($path, '.'));
431
+                } else {
432
+                    $ext = '';
433
+                }
434
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
435
+                // Fetch existing file if required
436
+                if ($mode[0] !== 'w' && $this->file_exists($path)) {
437
+                    if ($mode[0] === 'x') {
438
+                        // File cannot already exist
439
+                        return false;
440
+                    }
441
+                    $source = $this->fopen($path, 'r');
442
+                    file_put_contents($tmpFile, $source);
443
+                }
444
+                $handle = fopen($tmpFile, $mode);
445
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
446
+                    $this->writeBack($tmpFile, $path);
447
+                });
448
+        }
449
+    }
450
+
451
+    public function touch($path, $mtime = null) {
452
+        $path = $this->normalizePath($path);
453
+        if (is_null($mtime)) {
454
+            $mtime = time();
455
+        }
456
+        $metadata = ['timestamp' => (string)$mtime];
457
+        if ($this->file_exists($path)) {
458
+            if ($this->is_dir($path) && $path !== '.') {
459
+                $path .= '/';
460
+            }
461
+
462
+            $object = $this->fetchObject($path);
463
+            if ($object->mergeMetadata($metadata)) {
464
+                // invalidate target object to force repopulation on fetch
465
+                $this->objectCache->remove($path);
466
+            }
467
+            return true;
468
+        } else {
469
+            $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
470
+            $this->getContainer()->createObject([
471
+                'name' => $path,
472
+                'content' => '',
473
+                'headers' => ['content-type' => 'httpd/unix-directory']
474
+            ]);
475
+            // invalidate target object to force repopulation on fetch
476
+            $this->objectCache->remove($path);
477
+            return true;
478
+        }
479
+    }
480
+
481
+    public function copy($path1, $path2) {
482
+        $path1 = $this->normalizePath($path1);
483
+        $path2 = $this->normalizePath($path2);
484
+
485
+        $fileType = $this->filetype($path1);
486
+        if ($fileType) {
487
+            // make way
488
+            $this->unlink($path2);
489
+        }
490
+
491
+        if ($fileType === 'file') {
492
+            try {
493
+                $source = $this->fetchObject($path1);
494
+                $source->copy([
495
+                    'destination' => $this->bucket . '/' . $path2
496
+                ]);
497
+                // invalidate target object to force repopulation on fetch
498
+                $this->objectCache->remove($path2);
499
+                $this->objectCache->remove($path2 . '/');
500
+            } catch (BadResponseError $e) {
501
+                \OC::$server->getLogger()->logException($e, [
502
+                    'level' => ILogger::ERROR,
503
+                    'app' => 'files_external',
504
+                ]);
505
+                return false;
506
+            }
507
+
508
+        } else if ($fileType === 'dir') {
509
+            try {
510
+                $source = $this->fetchObject($path1 . '/');
511
+                $source->copy([
512
+                    'destination' => $this->bucket . '/' . $path2 . '/'
513
+                ]);
514
+                // invalidate target object to force repopulation on fetch
515
+                $this->objectCache->remove($path2);
516
+                $this->objectCache->remove($path2 . '/');
517
+            } catch (BadResponseError $e) {
518
+                \OC::$server->getLogger()->logException($e, [
519
+                    'level' => ILogger::ERROR,
520
+                    'app' => 'files_external',
521
+                ]);
522
+                return false;
523
+            }
524
+
525
+            $dh = $this->opendir($path1);
526
+            while ($file = readdir($dh)) {
527
+                if (\OC\Files\Filesystem::isIgnoredDir($file)) {
528
+                    continue;
529
+                }
530
+
531
+                $source = $path1 . '/' . $file;
532
+                $target = $path2 . '/' . $file;
533
+                $this->copy($source, $target);
534
+            }
535
+
536
+        } else {
537
+            //file does not exist
538
+            return false;
539
+        }
540
+
541
+        return true;
542
+    }
543
+
544
+    public function rename($path1, $path2) {
545
+        $path1 = $this->normalizePath($path1);
546
+        $path2 = $this->normalizePath($path2);
547
+
548
+        $fileType = $this->filetype($path1);
549
+
550
+        if ($fileType === 'dir' || $fileType === 'file') {
551
+            // copy
552
+            if ($this->copy($path1, $path2) === false) {
553
+                return false;
554
+            }
555
+
556
+            // cleanup
557
+            if ($this->unlink($path1) === false) {
558
+                throw new \Exception('failed to remove original');
559
+                $this->unlink($path2);
560
+                return false;
561
+            }
562
+
563
+            return true;
564
+        }
565
+
566
+        return false;
567
+    }
568
+
569
+    public function getId() {
570
+        return $this->id;
571
+    }
572
+
573
+    /**
574
+     * Returns the initialized object store container.
575
+     *
576
+     * @return \OpenStack\ObjectStore\v1\Models\Container
577
+     * @throws \OCP\Files\StorageAuthException
578
+     * @throws \OCP\Files\StorageNotAvailableException
579
+     */
580
+    public function getContainer() {
581
+        if (is_null($this->container)) {
582
+            $this->container = $this->connectionFactory->getContainer();
583
+
584
+            if (!$this->file_exists('.')) {
585
+                $this->mkdir('.');
586
+            }
587
+        }
588
+        return $this->container;
589
+    }
590
+
591
+    public function writeBack($tmpFile, $path) {
592
+        $fileData = fopen($tmpFile, 'r');
593
+        $this->objectStore->writeObject($path, $fileData);
594
+        // invalidate target object to force repopulation on fetch
595
+        $this->objectCache->remove($path);
596
+        unlink($tmpFile);
597
+    }
598
+
599
+    public function hasUpdated($path, $time) {
600
+        if ($this->is_file($path)) {
601
+            return parent::hasUpdated($path, $time);
602
+        }
603
+        $path = $this->normalizePath($path);
604
+        $dh = $this->opendir($path);
605
+        $content = [];
606
+        while (($file = readdir($dh)) !== false) {
607
+            $content[] = $file;
608
+        }
609
+        if ($path === '.') {
610
+            $path = '';
611
+        }
612
+        $cachedContent = $this->getCache()->getFolderContents($path);
613
+        $cachedNames = array_map(function ($content) {
614
+            return $content['name'];
615
+        }, $cachedContent);
616
+        sort($cachedNames);
617
+        sort($content);
618
+        return $cachedNames !== $content;
619
+    }
620
+
621
+    /**
622
+     * check if curl is installed
623
+     */
624
+    public static function checkDependencies() {
625
+        return true;
626
+    }
627 627
 
628 628
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -166,12 +166,12 @@  discard block
 block discarded – undo
166 166
 		}
167 167
 
168 168
 		$user = $params['user'];
169
-		$this->id = 'swift::' . $user . md5($params['bucket']);
169
+		$this->id = 'swift::'.$user.md5($params['bucket']);
170 170
 
171 171
 		$bucketUrl = new Uri($params['bucket']);
172 172
 		if ($bucketUrl->getHost()) {
173 173
 			$params['bucket'] = basename($bucketUrl->getPath());
174
-			$params['endpoint_url'] = (string)$bucketUrl->withPath(dirname($bucketUrl->getPath()));
174
+			$params['endpoint_url'] = (string) $bucketUrl->withPath(dirname($bucketUrl->getPath()));
175 175
 		}
176 176
 
177 177
 		if (empty($params['url'])) {
@@ -260,16 +260,16 @@  discard block
 block discarded – undo
260 260
 				continue;
261 261
 			}
262 262
 
263
-			if ($this->is_dir($path . '/' . $file)) {
264
-				$this->rmdir($path . '/' . $file);
263
+			if ($this->is_dir($path.'/'.$file)) {
264
+				$this->rmdir($path.'/'.$file);
265 265
 			} else {
266
-				$this->unlink($path . '/' . $file);
266
+				$this->unlink($path.'/'.$file);
267 267
 			}
268 268
 		}
269 269
 
270 270
 		try {
271
-			$this->objectStore->deleteObject($path . '/');
272
-			$this->objectCache->remove($path . '/');
271
+			$this->objectStore->deleteObject($path.'/');
272
+			$this->objectCache->remove($path.'/');
273 273
 		} catch (BadResponseError $e) {
274 274
 			\OC::$server->getLogger()->logException($e, [
275 275
 				'level' => ILogger::ERROR,
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
 		}
353 353
 
354 354
 		$stat = [];
355
-		$stat['size'] = (int)$object->contentLength;
355
+		$stat['size'] = (int) $object->contentLength;
356 356
 		$stat['mtime'] = $mtime;
357 357
 		$stat['atime'] = time();
358 358
 		return $stat;
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
 		try {
385 385
 			$this->objectStore->deleteObject($path);
386 386
 			$this->objectCache->remove($path);
387
-			$this->objectCache->remove($path . '/');
387
+			$this->objectCache->remove($path.'/');
388 388
 		} catch (BadResponseError $e) {
389 389
 			if ($e->getResponse()->getStatusCode() !== 404) {
390 390
 				\OC::$server->getLogger()->logException($e, [
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 					file_put_contents($tmpFile, $source);
443 443
 				}
444 444
 				$handle = fopen($tmpFile, $mode);
445
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
445
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
446 446
 					$this->writeBack($tmpFile, $path);
447 447
 				});
448 448
 		}
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
 		if (is_null($mtime)) {
454 454
 			$mtime = time();
455 455
 		}
456
-		$metadata = ['timestamp' => (string)$mtime];
456
+		$metadata = ['timestamp' => (string) $mtime];
457 457
 		if ($this->file_exists($path)) {
458 458
 			if ($this->is_dir($path) && $path !== '.') {
459 459
 				$path .= '/';
@@ -492,11 +492,11 @@  discard block
 block discarded – undo
492 492
 			try {
493 493
 				$source = $this->fetchObject($path1);
494 494
 				$source->copy([
495
-					'destination' => $this->bucket . '/' . $path2
495
+					'destination' => $this->bucket.'/'.$path2
496 496
 				]);
497 497
 				// invalidate target object to force repopulation on fetch
498 498
 				$this->objectCache->remove($path2);
499
-				$this->objectCache->remove($path2 . '/');
499
+				$this->objectCache->remove($path2.'/');
500 500
 			} catch (BadResponseError $e) {
501 501
 				\OC::$server->getLogger()->logException($e, [
502 502
 					'level' => ILogger::ERROR,
@@ -507,13 +507,13 @@  discard block
 block discarded – undo
507 507
 
508 508
 		} else if ($fileType === 'dir') {
509 509
 			try {
510
-				$source = $this->fetchObject($path1 . '/');
510
+				$source = $this->fetchObject($path1.'/');
511 511
 				$source->copy([
512
-					'destination' => $this->bucket . '/' . $path2 . '/'
512
+					'destination' => $this->bucket.'/'.$path2.'/'
513 513
 				]);
514 514
 				// invalidate target object to force repopulation on fetch
515 515
 				$this->objectCache->remove($path2);
516
-				$this->objectCache->remove($path2 . '/');
516
+				$this->objectCache->remove($path2.'/');
517 517
 			} catch (BadResponseError $e) {
518 518
 				\OC::$server->getLogger()->logException($e, [
519 519
 					'level' => ILogger::ERROR,
@@ -528,8 +528,8 @@  discard block
 block discarded – undo
528 528
 					continue;
529 529
 				}
530 530
 
531
-				$source = $path1 . '/' . $file;
532
-				$target = $path2 . '/' . $file;
531
+				$source = $path1.'/'.$file;
532
+				$target = $path2.'/'.$file;
533 533
 				$this->copy($source, $target);
534 534
 			}
535 535
 
@@ -610,7 +610,7 @@  discard block
 block discarded – undo
610 610
 			$path = '';
611 611
 		}
612 612
 		$cachedContent = $this->getCache()->getFolderContents($path);
613
-		$cachedNames = array_map(function ($content) {
613
+		$cachedNames = array_map(function($content) {
614 614
 			return $content['name'];
615 615
 		}, $cachedContent);
616 616
 		sort($cachedNames);
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/SFTP.php 2 patches
Indentation   +437 added lines, -437 removed lines patch added patch discarded remove patch
@@ -44,441 +44,441 @@
 block discarded – undo
44 44
 * provide access to SFTP servers.
45 45
 */
46 46
 class SFTP extends \OC\Files\Storage\Common {
47
-	private $host;
48
-	private $user;
49
-	private $root;
50
-	private $port = 22;
51
-
52
-	private $auth = [];
53
-
54
-	/**
55
-	 * @var \phpseclib\Net\SFTP
56
-	 */
57
-	protected $client;
58
-
59
-	/**
60
-	 * @param string $host protocol://server:port
61
-	 * @return array [$server, $port]
62
-	 */
63
-	private function splitHost($host) {
64
-		$input = $host;
65
-		if (strpos($host, '://') === false) {
66
-			// add a protocol to fix parse_url behavior with ipv6
67
-			$host = 'http://' . $host;
68
-		}
69
-
70
-		$parsed = parse_url($host);
71
-		if(is_array($parsed) && isset($parsed['port'])) {
72
-			return [$parsed['host'], $parsed['port']];
73
-		} else if (is_array($parsed)) {
74
-			return [$parsed['host'], 22];
75
-		} else {
76
-			return [$input, 22];
77
-		}
78
-	}
79
-
80
-	/**
81
-	 * {@inheritdoc}
82
-	 */
83
-	public function __construct($params) {
84
-		// Register sftp://
85
-		Stream::register();
86
-
87
-		$parsedHost =  $this->splitHost($params['host']);
88
-
89
-		$this->host = $parsedHost[0];
90
-		$this->port = $parsedHost[1];
91
-
92
-		if (!isset($params['user'])) {
93
-			throw new \UnexpectedValueException('no authentication parameters specified');
94
-		}
95
-		$this->user = $params['user'];
96
-
97
-		if (isset($params['public_key_auth'])) {
98
-			$this->auth[] = $params['public_key_auth'];
99
-		}
100
-		if (isset($params['password']) && $params['password'] !== '') {
101
-			$this->auth[] = $params['password'];
102
-		}
103
-
104
-		if ($this->auth === []) {
105
-			throw new \UnexpectedValueException('no authentication parameters specified');
106
-		}
107
-
108
-		$this->root
109
-			= isset($params['root']) ? $this->cleanPath($params['root']) : '/';
110
-
111
-		$this->root = '/' . ltrim($this->root, '/');
112
-		$this->root = rtrim($this->root, '/') . '/';
113
-	}
114
-
115
-	/**
116
-	 * Returns the connection.
117
-	 *
118
-	 * @return \phpseclib\Net\SFTP connected client instance
119
-	 * @throws \Exception when the connection failed
120
-	 */
121
-	public function getConnection() {
122
-		if (!is_null($this->client)) {
123
-			return $this->client;
124
-		}
125
-
126
-		$hostKeys = $this->readHostKeys();
127
-		$this->client = new \phpseclib\Net\SFTP($this->host, $this->port);
128
-
129
-		// The SSH Host Key MUST be verified before login().
130
-		$currentHostKey = $this->client->getServerPublicHostKey();
131
-		if (array_key_exists($this->host, $hostKeys)) {
132
-			if ($hostKeys[$this->host] !== $currentHostKey) {
133
-				throw new \Exception('Host public key does not match known key');
134
-			}
135
-		} else {
136
-			$hostKeys[$this->host] = $currentHostKey;
137
-			$this->writeHostKeys($hostKeys);
138
-		}
139
-
140
-		$login = false;
141
-		foreach ($this->auth as $auth) {
142
-			$login = $this->client->login($this->user, $auth);
143
-			if ($login === true) {
144
-				break;
145
-			}
146
-		}
147
-
148
-		if ($login === false) {
149
-			throw new \Exception('Login failed');
150
-		}
151
-		return $this->client;
152
-	}
153
-
154
-	/**
155
-	 * {@inheritdoc}
156
-	 */
157
-	public function test() {
158
-		if (
159
-			!isset($this->host)
160
-			|| !isset($this->user)
161
-		) {
162
-			return false;
163
-		}
164
-		return $this->getConnection()->nlist() !== false;
165
-	}
166
-
167
-	/**
168
-	 * {@inheritdoc}
169
-	 */
170
-	public function getId(){
171
-		$id = 'sftp::' . $this->user . '@' . $this->host;
172
-		if ($this->port !== 22) {
173
-			$id .= ':' . $this->port;
174
-		}
175
-		// note: this will double the root slash,
176
-		// we should not change it to keep compatible with
177
-		// old storage ids
178
-		$id .= '/' . $this->root;
179
-		return $id;
180
-	}
181
-
182
-	/**
183
-	 * @return string
184
-	 */
185
-	public function getHost() {
186
-		return $this->host;
187
-	}
188
-
189
-	/**
190
-	 * @return string
191
-	 */
192
-	public function getRoot() {
193
-		return $this->root;
194
-	}
195
-
196
-	/**
197
-	 * @return mixed
198
-	 */
199
-	public function getUser() {
200
-		return $this->user;
201
-	}
202
-
203
-	/**
204
-	 * @param string $path
205
-	 * @return string
206
-	 */
207
-	private function absPath($path) {
208
-		return $this->root . $this->cleanPath($path);
209
-	}
210
-
211
-	/**
212
-	 * @return string|false
213
-	 */
214
-	private function hostKeysPath() {
215
-		try {
216
-			$storage_view = \OCP\Files::getStorage('files_external');
217
-			if ($storage_view) {
218
-				return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') .
219
-					$storage_view->getAbsolutePath('') .
220
-					'ssh_hostKeys';
221
-			}
222
-		} catch (\Exception $e) {
223
-		}
224
-		return false;
225
-	}
226
-
227
-	/**
228
-	 * @param $keys
229
-	 * @return bool
230
-	 */
231
-	protected function writeHostKeys($keys) {
232
-		try {
233
-			$keyPath = $this->hostKeysPath();
234
-			if ($keyPath && file_exists($keyPath)) {
235
-				$fp = fopen($keyPath, 'w');
236
-				foreach ($keys as $host => $key) {
237
-					fwrite($fp, $host . '::' . $key . "\n");
238
-				}
239
-				fclose($fp);
240
-				return true;
241
-			}
242
-		} catch (\Exception $e) {
243
-		}
244
-		return false;
245
-	}
246
-
247
-	/**
248
-	 * @return array
249
-	 */
250
-	protected function readHostKeys() {
251
-		try {
252
-			$keyPath = $this->hostKeysPath();
253
-			if (file_exists($keyPath)) {
254
-				$hosts = [];
255
-				$keys = [];
256
-				$lines = file($keyPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
257
-				if ($lines) {
258
-					foreach ($lines as $line) {
259
-						$hostKeyArray = explode("::", $line, 2);
260
-						if (count($hostKeyArray) === 2) {
261
-							$hosts[] = $hostKeyArray[0];
262
-							$keys[] = $hostKeyArray[1];
263
-						}
264
-					}
265
-					return array_combine($hosts, $keys);
266
-				}
267
-			}
268
-		} catch (\Exception $e) {
269
-		}
270
-		return [];
271
-	}
272
-
273
-	/**
274
-	 * {@inheritdoc}
275
-	 */
276
-	public function mkdir($path) {
277
-		try {
278
-			return $this->getConnection()->mkdir($this->absPath($path));
279
-		} catch (\Exception $e) {
280
-			return false;
281
-		}
282
-	}
283
-
284
-	/**
285
-	 * {@inheritdoc}
286
-	 */
287
-	public function rmdir($path) {
288
-		try {
289
-			$result = $this->getConnection()->delete($this->absPath($path), true);
290
-			// workaround: stray stat cache entry when deleting empty folders
291
-			// see https://github.com/phpseclib/phpseclib/issues/706
292
-			$this->getConnection()->clearStatCache();
293
-			return $result;
294
-		} catch (\Exception $e) {
295
-			return false;
296
-		}
297
-	}
298
-
299
-	/**
300
-	 * {@inheritdoc}
301
-	 */
302
-	public function opendir($path) {
303
-		try {
304
-			$list = $this->getConnection()->nlist($this->absPath($path));
305
-			if ($list === false) {
306
-				return false;
307
-			}
308
-
309
-			$id = md5('sftp:' . $path);
310
-			$dirStream = [];
311
-			foreach($list as $file) {
312
-				if ($file !== '.' && $file !== '..') {
313
-					$dirStream[] = $file;
314
-				}
315
-			}
316
-			return IteratorDirectory::wrap($dirStream);
317
-		} catch(\Exception $e) {
318
-			return false;
319
-		}
320
-	}
321
-
322
-	/**
323
-	 * {@inheritdoc}
324
-	 */
325
-	public function filetype($path) {
326
-		try {
327
-			$stat = $this->getConnection()->stat($this->absPath($path));
328
-			if ((int) $stat['type'] === NET_SFTP_TYPE_REGULAR) {
329
-				return 'file';
330
-			}
331
-
332
-			if ((int) $stat['type'] === NET_SFTP_TYPE_DIRECTORY) {
333
-				return 'dir';
334
-			}
335
-		} catch (\Exception $e) {
336
-
337
-		}
338
-		return false;
339
-	}
340
-
341
-	/**
342
-	 * {@inheritdoc}
343
-	 */
344
-	public function file_exists($path) {
345
-		try {
346
-			return $this->getConnection()->stat($this->absPath($path)) !== false;
347
-		} catch (\Exception $e) {
348
-			return false;
349
-		}
350
-	}
351
-
352
-	/**
353
-	 * {@inheritdoc}
354
-	 */
355
-	public function unlink($path) {
356
-		try {
357
-			return $this->getConnection()->delete($this->absPath($path), true);
358
-		} catch (\Exception $e) {
359
-			return false;
360
-		}
361
-	}
362
-
363
-	/**
364
-	 * {@inheritdoc}
365
-	 */
366
-	public function fopen($path, $mode) {
367
-		try {
368
-			$absPath = $this->absPath($path);
369
-			switch($mode) {
370
-				case 'r':
371
-				case 'rb':
372
-					if ( !$this->file_exists($path)) {
373
-						return false;
374
-					}
375
-					SFTPReadStream::register();
376
-					$context = stream_context_create(['sftp' => ['session' => $this->getConnection()]]);
377
-					$handle = fopen('sftpread://' . trim($absPath, '/'), 'r', false, $context);
378
-					return RetryWrapper::wrap($handle);
379
-				case 'w':
380
-				case 'wb':
381
-					SFTPWriteStream::register();
382
-					$context = stream_context_create(['sftp' => ['session' => $this->getConnection()]]);
383
-					return fopen('sftpwrite://' . trim($absPath, '/'), 'w', false, $context);
384
-				case 'a':
385
-				case 'ab':
386
-				case 'r+':
387
-				case 'w+':
388
-				case 'wb+':
389
-				case 'a+':
390
-				case 'x':
391
-				case 'x+':
392
-				case 'c':
393
-				case 'c+':
394
-					$context = stream_context_create(['sftp' => ['session' => $this->getConnection()]]);
395
-					$handle = fopen($this->constructUrl($path), $mode, false, $context);
396
-					return RetryWrapper::wrap($handle);
397
-			}
398
-		} catch (\Exception $e) {
399
-		}
400
-		return false;
401
-	}
402
-
403
-	/**
404
-	 * {@inheritdoc}
405
-	 */
406
-	public function touch($path, $mtime=null) {
407
-		try {
408
-			if (!is_null($mtime)) {
409
-				return false;
410
-			}
411
-			if (!$this->file_exists($path)) {
412
-				$this->getConnection()->put($this->absPath($path), '');
413
-			} else {
414
-				return false;
415
-			}
416
-		} catch (\Exception $e) {
417
-			return false;
418
-		}
419
-		return true;
420
-	}
421
-
422
-	/**
423
-	 * @param string $path
424
-	 * @param string $target
425
-	 * @throws \Exception
426
-	 */
427
-	public function getFile($path, $target) {
428
-		$this->getConnection()->get($path, $target);
429
-	}
430
-
431
-	/**
432
-	 * @param string $path
433
-	 * @param string $target
434
-	 * @throws \Exception
435
-	 */
436
-	public function uploadFile($path, $target) {
437
-		$this->getConnection()->put($target, $path, NET_SFTP_LOCAL_FILE);
438
-	}
439
-
440
-	/**
441
-	 * {@inheritdoc}
442
-	 */
443
-	public function rename($source, $target) {
444
-		try {
445
-			if ($this->file_exists($target)) {
446
-				$this->unlink($target);
447
-			}
448
-			return $this->getConnection()->rename(
449
-				$this->absPath($source),
450
-				$this->absPath($target)
451
-			);
452
-		} catch (\Exception $e) {
453
-			return false;
454
-		}
455
-	}
456
-
457
-	/**
458
-	 * {@inheritdoc}
459
-	 */
460
-	public function stat($path) {
461
-		try {
462
-			$stat = $this->getConnection()->stat($this->absPath($path));
463
-
464
-			$mtime = $stat ? $stat['mtime'] : -1;
465
-			$size = $stat ? $stat['size'] : 0;
466
-
467
-			return ['mtime' => $mtime, 'size' => $size, 'ctime' => -1];
468
-		} catch (\Exception $e) {
469
-			return false;
470
-		}
471
-	}
472
-
473
-	/**
474
-	 * @param string $path
475
-	 * @return string
476
-	 */
477
-	public function constructUrl($path) {
478
-		// Do not pass the password here. We want to use the Net_SFTP object
479
-		// supplied via stream context or fail. We only supply username and
480
-		// hostname because this might show up in logs (they are not used).
481
-		$url = 'sftp://' . urlencode($this->user) . '@' . $this->host . ':' . $this->port . $this->root . $path;
482
-		return $url;
483
-	}
47
+    private $host;
48
+    private $user;
49
+    private $root;
50
+    private $port = 22;
51
+
52
+    private $auth = [];
53
+
54
+    /**
55
+     * @var \phpseclib\Net\SFTP
56
+     */
57
+    protected $client;
58
+
59
+    /**
60
+     * @param string $host protocol://server:port
61
+     * @return array [$server, $port]
62
+     */
63
+    private function splitHost($host) {
64
+        $input = $host;
65
+        if (strpos($host, '://') === false) {
66
+            // add a protocol to fix parse_url behavior with ipv6
67
+            $host = 'http://' . $host;
68
+        }
69
+
70
+        $parsed = parse_url($host);
71
+        if(is_array($parsed) && isset($parsed['port'])) {
72
+            return [$parsed['host'], $parsed['port']];
73
+        } else if (is_array($parsed)) {
74
+            return [$parsed['host'], 22];
75
+        } else {
76
+            return [$input, 22];
77
+        }
78
+    }
79
+
80
+    /**
81
+     * {@inheritdoc}
82
+     */
83
+    public function __construct($params) {
84
+        // Register sftp://
85
+        Stream::register();
86
+
87
+        $parsedHost =  $this->splitHost($params['host']);
88
+
89
+        $this->host = $parsedHost[0];
90
+        $this->port = $parsedHost[1];
91
+
92
+        if (!isset($params['user'])) {
93
+            throw new \UnexpectedValueException('no authentication parameters specified');
94
+        }
95
+        $this->user = $params['user'];
96
+
97
+        if (isset($params['public_key_auth'])) {
98
+            $this->auth[] = $params['public_key_auth'];
99
+        }
100
+        if (isset($params['password']) && $params['password'] !== '') {
101
+            $this->auth[] = $params['password'];
102
+        }
103
+
104
+        if ($this->auth === []) {
105
+            throw new \UnexpectedValueException('no authentication parameters specified');
106
+        }
107
+
108
+        $this->root
109
+            = isset($params['root']) ? $this->cleanPath($params['root']) : '/';
110
+
111
+        $this->root = '/' . ltrim($this->root, '/');
112
+        $this->root = rtrim($this->root, '/') . '/';
113
+    }
114
+
115
+    /**
116
+     * Returns the connection.
117
+     *
118
+     * @return \phpseclib\Net\SFTP connected client instance
119
+     * @throws \Exception when the connection failed
120
+     */
121
+    public function getConnection() {
122
+        if (!is_null($this->client)) {
123
+            return $this->client;
124
+        }
125
+
126
+        $hostKeys = $this->readHostKeys();
127
+        $this->client = new \phpseclib\Net\SFTP($this->host, $this->port);
128
+
129
+        // The SSH Host Key MUST be verified before login().
130
+        $currentHostKey = $this->client->getServerPublicHostKey();
131
+        if (array_key_exists($this->host, $hostKeys)) {
132
+            if ($hostKeys[$this->host] !== $currentHostKey) {
133
+                throw new \Exception('Host public key does not match known key');
134
+            }
135
+        } else {
136
+            $hostKeys[$this->host] = $currentHostKey;
137
+            $this->writeHostKeys($hostKeys);
138
+        }
139
+
140
+        $login = false;
141
+        foreach ($this->auth as $auth) {
142
+            $login = $this->client->login($this->user, $auth);
143
+            if ($login === true) {
144
+                break;
145
+            }
146
+        }
147
+
148
+        if ($login === false) {
149
+            throw new \Exception('Login failed');
150
+        }
151
+        return $this->client;
152
+    }
153
+
154
+    /**
155
+     * {@inheritdoc}
156
+     */
157
+    public function test() {
158
+        if (
159
+            !isset($this->host)
160
+            || !isset($this->user)
161
+        ) {
162
+            return false;
163
+        }
164
+        return $this->getConnection()->nlist() !== false;
165
+    }
166
+
167
+    /**
168
+     * {@inheritdoc}
169
+     */
170
+    public function getId(){
171
+        $id = 'sftp::' . $this->user . '@' . $this->host;
172
+        if ($this->port !== 22) {
173
+            $id .= ':' . $this->port;
174
+        }
175
+        // note: this will double the root slash,
176
+        // we should not change it to keep compatible with
177
+        // old storage ids
178
+        $id .= '/' . $this->root;
179
+        return $id;
180
+    }
181
+
182
+    /**
183
+     * @return string
184
+     */
185
+    public function getHost() {
186
+        return $this->host;
187
+    }
188
+
189
+    /**
190
+     * @return string
191
+     */
192
+    public function getRoot() {
193
+        return $this->root;
194
+    }
195
+
196
+    /**
197
+     * @return mixed
198
+     */
199
+    public function getUser() {
200
+        return $this->user;
201
+    }
202
+
203
+    /**
204
+     * @param string $path
205
+     * @return string
206
+     */
207
+    private function absPath($path) {
208
+        return $this->root . $this->cleanPath($path);
209
+    }
210
+
211
+    /**
212
+     * @return string|false
213
+     */
214
+    private function hostKeysPath() {
215
+        try {
216
+            $storage_view = \OCP\Files::getStorage('files_external');
217
+            if ($storage_view) {
218
+                return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') .
219
+                    $storage_view->getAbsolutePath('') .
220
+                    'ssh_hostKeys';
221
+            }
222
+        } catch (\Exception $e) {
223
+        }
224
+        return false;
225
+    }
226
+
227
+    /**
228
+     * @param $keys
229
+     * @return bool
230
+     */
231
+    protected function writeHostKeys($keys) {
232
+        try {
233
+            $keyPath = $this->hostKeysPath();
234
+            if ($keyPath && file_exists($keyPath)) {
235
+                $fp = fopen($keyPath, 'w');
236
+                foreach ($keys as $host => $key) {
237
+                    fwrite($fp, $host . '::' . $key . "\n");
238
+                }
239
+                fclose($fp);
240
+                return true;
241
+            }
242
+        } catch (\Exception $e) {
243
+        }
244
+        return false;
245
+    }
246
+
247
+    /**
248
+     * @return array
249
+     */
250
+    protected function readHostKeys() {
251
+        try {
252
+            $keyPath = $this->hostKeysPath();
253
+            if (file_exists($keyPath)) {
254
+                $hosts = [];
255
+                $keys = [];
256
+                $lines = file($keyPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
257
+                if ($lines) {
258
+                    foreach ($lines as $line) {
259
+                        $hostKeyArray = explode("::", $line, 2);
260
+                        if (count($hostKeyArray) === 2) {
261
+                            $hosts[] = $hostKeyArray[0];
262
+                            $keys[] = $hostKeyArray[1];
263
+                        }
264
+                    }
265
+                    return array_combine($hosts, $keys);
266
+                }
267
+            }
268
+        } catch (\Exception $e) {
269
+        }
270
+        return [];
271
+    }
272
+
273
+    /**
274
+     * {@inheritdoc}
275
+     */
276
+    public function mkdir($path) {
277
+        try {
278
+            return $this->getConnection()->mkdir($this->absPath($path));
279
+        } catch (\Exception $e) {
280
+            return false;
281
+        }
282
+    }
283
+
284
+    /**
285
+     * {@inheritdoc}
286
+     */
287
+    public function rmdir($path) {
288
+        try {
289
+            $result = $this->getConnection()->delete($this->absPath($path), true);
290
+            // workaround: stray stat cache entry when deleting empty folders
291
+            // see https://github.com/phpseclib/phpseclib/issues/706
292
+            $this->getConnection()->clearStatCache();
293
+            return $result;
294
+        } catch (\Exception $e) {
295
+            return false;
296
+        }
297
+    }
298
+
299
+    /**
300
+     * {@inheritdoc}
301
+     */
302
+    public function opendir($path) {
303
+        try {
304
+            $list = $this->getConnection()->nlist($this->absPath($path));
305
+            if ($list === false) {
306
+                return false;
307
+            }
308
+
309
+            $id = md5('sftp:' . $path);
310
+            $dirStream = [];
311
+            foreach($list as $file) {
312
+                if ($file !== '.' && $file !== '..') {
313
+                    $dirStream[] = $file;
314
+                }
315
+            }
316
+            return IteratorDirectory::wrap($dirStream);
317
+        } catch(\Exception $e) {
318
+            return false;
319
+        }
320
+    }
321
+
322
+    /**
323
+     * {@inheritdoc}
324
+     */
325
+    public function filetype($path) {
326
+        try {
327
+            $stat = $this->getConnection()->stat($this->absPath($path));
328
+            if ((int) $stat['type'] === NET_SFTP_TYPE_REGULAR) {
329
+                return 'file';
330
+            }
331
+
332
+            if ((int) $stat['type'] === NET_SFTP_TYPE_DIRECTORY) {
333
+                return 'dir';
334
+            }
335
+        } catch (\Exception $e) {
336
+
337
+        }
338
+        return false;
339
+    }
340
+
341
+    /**
342
+     * {@inheritdoc}
343
+     */
344
+    public function file_exists($path) {
345
+        try {
346
+            return $this->getConnection()->stat($this->absPath($path)) !== false;
347
+        } catch (\Exception $e) {
348
+            return false;
349
+        }
350
+    }
351
+
352
+    /**
353
+     * {@inheritdoc}
354
+     */
355
+    public function unlink($path) {
356
+        try {
357
+            return $this->getConnection()->delete($this->absPath($path), true);
358
+        } catch (\Exception $e) {
359
+            return false;
360
+        }
361
+    }
362
+
363
+    /**
364
+     * {@inheritdoc}
365
+     */
366
+    public function fopen($path, $mode) {
367
+        try {
368
+            $absPath = $this->absPath($path);
369
+            switch($mode) {
370
+                case 'r':
371
+                case 'rb':
372
+                    if ( !$this->file_exists($path)) {
373
+                        return false;
374
+                    }
375
+                    SFTPReadStream::register();
376
+                    $context = stream_context_create(['sftp' => ['session' => $this->getConnection()]]);
377
+                    $handle = fopen('sftpread://' . trim($absPath, '/'), 'r', false, $context);
378
+                    return RetryWrapper::wrap($handle);
379
+                case 'w':
380
+                case 'wb':
381
+                    SFTPWriteStream::register();
382
+                    $context = stream_context_create(['sftp' => ['session' => $this->getConnection()]]);
383
+                    return fopen('sftpwrite://' . trim($absPath, '/'), 'w', false, $context);
384
+                case 'a':
385
+                case 'ab':
386
+                case 'r+':
387
+                case 'w+':
388
+                case 'wb+':
389
+                case 'a+':
390
+                case 'x':
391
+                case 'x+':
392
+                case 'c':
393
+                case 'c+':
394
+                    $context = stream_context_create(['sftp' => ['session' => $this->getConnection()]]);
395
+                    $handle = fopen($this->constructUrl($path), $mode, false, $context);
396
+                    return RetryWrapper::wrap($handle);
397
+            }
398
+        } catch (\Exception $e) {
399
+        }
400
+        return false;
401
+    }
402
+
403
+    /**
404
+     * {@inheritdoc}
405
+     */
406
+    public function touch($path, $mtime=null) {
407
+        try {
408
+            if (!is_null($mtime)) {
409
+                return false;
410
+            }
411
+            if (!$this->file_exists($path)) {
412
+                $this->getConnection()->put($this->absPath($path), '');
413
+            } else {
414
+                return false;
415
+            }
416
+        } catch (\Exception $e) {
417
+            return false;
418
+        }
419
+        return true;
420
+    }
421
+
422
+    /**
423
+     * @param string $path
424
+     * @param string $target
425
+     * @throws \Exception
426
+     */
427
+    public function getFile($path, $target) {
428
+        $this->getConnection()->get($path, $target);
429
+    }
430
+
431
+    /**
432
+     * @param string $path
433
+     * @param string $target
434
+     * @throws \Exception
435
+     */
436
+    public function uploadFile($path, $target) {
437
+        $this->getConnection()->put($target, $path, NET_SFTP_LOCAL_FILE);
438
+    }
439
+
440
+    /**
441
+     * {@inheritdoc}
442
+     */
443
+    public function rename($source, $target) {
444
+        try {
445
+            if ($this->file_exists($target)) {
446
+                $this->unlink($target);
447
+            }
448
+            return $this->getConnection()->rename(
449
+                $this->absPath($source),
450
+                $this->absPath($target)
451
+            );
452
+        } catch (\Exception $e) {
453
+            return false;
454
+        }
455
+    }
456
+
457
+    /**
458
+     * {@inheritdoc}
459
+     */
460
+    public function stat($path) {
461
+        try {
462
+            $stat = $this->getConnection()->stat($this->absPath($path));
463
+
464
+            $mtime = $stat ? $stat['mtime'] : -1;
465
+            $size = $stat ? $stat['size'] : 0;
466
+
467
+            return ['mtime' => $mtime, 'size' => $size, 'ctime' => -1];
468
+        } catch (\Exception $e) {
469
+            return false;
470
+        }
471
+    }
472
+
473
+    /**
474
+     * @param string $path
475
+     * @return string
476
+     */
477
+    public function constructUrl($path) {
478
+        // Do not pass the password here. We want to use the Net_SFTP object
479
+        // supplied via stream context or fail. We only supply username and
480
+        // hostname because this might show up in logs (they are not used).
481
+        $url = 'sftp://' . urlencode($this->user) . '@' . $this->host . ':' . $this->port . $this->root . $path;
482
+        return $url;
483
+    }
484 484
 }
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -64,11 +64,11 @@  discard block
 block discarded – undo
64 64
 		$input = $host;
65 65
 		if (strpos($host, '://') === false) {
66 66
 			// add a protocol to fix parse_url behavior with ipv6
67
-			$host = 'http://' . $host;
67
+			$host = 'http://'.$host;
68 68
 		}
69 69
 
70 70
 		$parsed = parse_url($host);
71
-		if(is_array($parsed) && isset($parsed['port'])) {
71
+		if (is_array($parsed) && isset($parsed['port'])) {
72 72
 			return [$parsed['host'], $parsed['port']];
73 73
 		} else if (is_array($parsed)) {
74 74
 			return [$parsed['host'], 22];
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 		// Register sftp://
85 85
 		Stream::register();
86 86
 
87
-		$parsedHost =  $this->splitHost($params['host']);
87
+		$parsedHost = $this->splitHost($params['host']);
88 88
 
89 89
 		$this->host = $parsedHost[0];
90 90
 		$this->port = $parsedHost[1];
@@ -108,8 +108,8 @@  discard block
 block discarded – undo
108 108
 		$this->root
109 109
 			= isset($params['root']) ? $this->cleanPath($params['root']) : '/';
110 110
 
111
-		$this->root = '/' . ltrim($this->root, '/');
112
-		$this->root = rtrim($this->root, '/') . '/';
111
+		$this->root = '/'.ltrim($this->root, '/');
112
+		$this->root = rtrim($this->root, '/').'/';
113 113
 	}
114 114
 
115 115
 	/**
@@ -167,15 +167,15 @@  discard block
 block discarded – undo
167 167
 	/**
168 168
 	 * {@inheritdoc}
169 169
 	 */
170
-	public function getId(){
171
-		$id = 'sftp::' . $this->user . '@' . $this->host;
170
+	public function getId() {
171
+		$id = 'sftp::'.$this->user.'@'.$this->host;
172 172
 		if ($this->port !== 22) {
173
-			$id .= ':' . $this->port;
173
+			$id .= ':'.$this->port;
174 174
 		}
175 175
 		// note: this will double the root slash,
176 176
 		// we should not change it to keep compatible with
177 177
 		// old storage ids
178
-		$id .= '/' . $this->root;
178
+		$id .= '/'.$this->root;
179 179
 		return $id;
180 180
 	}
181 181
 
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 	 * @return string
206 206
 	 */
207 207
 	private function absPath($path) {
208
-		return $this->root . $this->cleanPath($path);
208
+		return $this->root.$this->cleanPath($path);
209 209
 	}
210 210
 
211 211
 	/**
@@ -215,8 +215,8 @@  discard block
 block discarded – undo
215 215
 		try {
216 216
 			$storage_view = \OCP\Files::getStorage('files_external');
217 217
 			if ($storage_view) {
218
-				return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') .
219
-					$storage_view->getAbsolutePath('') .
218
+				return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').
219
+					$storage_view->getAbsolutePath('').
220 220
 					'ssh_hostKeys';
221 221
 			}
222 222
 		} catch (\Exception $e) {
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
 			if ($keyPath && file_exists($keyPath)) {
235 235
 				$fp = fopen($keyPath, 'w');
236 236
 				foreach ($keys as $host => $key) {
237
-					fwrite($fp, $host . '::' . $key . "\n");
237
+					fwrite($fp, $host.'::'.$key."\n");
238 238
 				}
239 239
 				fclose($fp);
240 240
 				return true;
@@ -306,15 +306,15 @@  discard block
 block discarded – undo
306 306
 				return false;
307 307
 			}
308 308
 
309
-			$id = md5('sftp:' . $path);
309
+			$id = md5('sftp:'.$path);
310 310
 			$dirStream = [];
311
-			foreach($list as $file) {
311
+			foreach ($list as $file) {
312 312
 				if ($file !== '.' && $file !== '..') {
313 313
 					$dirStream[] = $file;
314 314
 				}
315 315
 			}
316 316
 			return IteratorDirectory::wrap($dirStream);
317
-		} catch(\Exception $e) {
317
+		} catch (\Exception $e) {
318 318
 			return false;
319 319
 		}
320 320
 	}
@@ -366,21 +366,21 @@  discard block
 block discarded – undo
366 366
 	public function fopen($path, $mode) {
367 367
 		try {
368 368
 			$absPath = $this->absPath($path);
369
-			switch($mode) {
369
+			switch ($mode) {
370 370
 				case 'r':
371 371
 				case 'rb':
372
-					if ( !$this->file_exists($path)) {
372
+					if (!$this->file_exists($path)) {
373 373
 						return false;
374 374
 					}
375 375
 					SFTPReadStream::register();
376 376
 					$context = stream_context_create(['sftp' => ['session' => $this->getConnection()]]);
377
-					$handle = fopen('sftpread://' . trim($absPath, '/'), 'r', false, $context);
377
+					$handle = fopen('sftpread://'.trim($absPath, '/'), 'r', false, $context);
378 378
 					return RetryWrapper::wrap($handle);
379 379
 				case 'w':
380 380
 				case 'wb':
381 381
 					SFTPWriteStream::register();
382 382
 					$context = stream_context_create(['sftp' => ['session' => $this->getConnection()]]);
383
-					return fopen('sftpwrite://' . trim($absPath, '/'), 'w', false, $context);
383
+					return fopen('sftpwrite://'.trim($absPath, '/'), 'w', false, $context);
384 384
 				case 'a':
385 385
 				case 'ab':
386 386
 				case 'r+':
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
 	/**
404 404
 	 * {@inheritdoc}
405 405
 	 */
406
-	public function touch($path, $mtime=null) {
406
+	public function touch($path, $mtime = null) {
407 407
 		try {
408 408
 			if (!is_null($mtime)) {
409 409
 				return false;
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
 		// Do not pass the password here. We want to use the Net_SFTP object
479 479
 		// supplied via stream context or fail. We only supply username and
480 480
 		// hostname because this might show up in logs (they are not used).
481
-		$url = 'sftp://' . urlencode($this->user) . '@' . $this->host . ':' . $this->port . $this->root . $path;
481
+		$url = 'sftp://'.urlencode($this->user).'@'.$this->host.':'.$this->port.$this->root.$path;
482 482
 		return $url;
483 483
 	}
484 484
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/ApiController.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -36,73 +36,73 @@
 block discarded – undo
36 36
 
37 37
 class ApiController extends OCSController {
38 38
 
39
-	/** @var IUserSession */
40
-	private $userSession;
41
-
42
-	public function __construct(string $appName,
43
-								IRequest $request,
44
-								IUserSession $userSession) {
45
-		parent::__construct($appName, $request);
46
-
47
-		$this->userSession = $userSession;
48
-	}
49
-
50
-	/**
51
-	 * Formats the given mount config to a mount entry.
52
-	 *
53
-	 * @param string $mountPoint mount point name, relative to the data dir
54
-	 * @param array $mountConfig mount config to format
55
-	 *
56
-	 * @return array entry
57
-	 */
58
-	private function formatMount(string $mountPoint, array $mountConfig): array {
59
-		// strip "/$user/files" from mount point
60
-		$mountPoint = explode('/', trim($mountPoint, '/'), 3);
61
-		$mountPoint = $mountPoint[2] ?? '';
62
-
63
-		// split path from mount point
64
-		$path = \dirname($mountPoint);
65
-		if ($path === '.') {
66
-			$path = '';
67
-		}
68
-
69
-		$isSystemMount = !$mountConfig['personal'];
70
-
71
-		$permissions = \OCP\Constants::PERMISSION_READ;
72
-		// personal mounts can be deleted
73
-		if (!$isSystemMount) {
74
-			$permissions |= \OCP\Constants::PERMISSION_DELETE;
75
-		}
76
-
77
-		$entry = [
78
-			'name' => basename($mountPoint),
79
-			'path' => $path,
80
-			'type' => 'dir',
81
-			'backend' => $mountConfig['backend'],
82
-			'scope' => $isSystemMount ? 'system' : 'personal',
83
-			'permissions' => $permissions,
84
-			'id' => $mountConfig['id'],
85
-			'class' => $mountConfig['class']
86
-		];
87
-		return $entry;
88
-	}
89
-
90
-	/**
91
-	 * @NoAdminRequired
92
-	 *
93
-	 * Returns the mount points visible for this user.
94
-	 *
95
-	 * @return DataResponse share information
96
-	 */
97
-	public function getUserMounts(): DataResponse {
98
-		$entries = [];
99
-		$user = $this->userSession->getUser()->getUID();
100
-
101
-		$mounts = \OC_Mount_Config::getAbsoluteMountPoints($user);
102
-		foreach($mounts as $mountPoint => $mount) {
103
-			$entries[] = $this->formatMount($mountPoint, $mount);
104
-		}
105
-
106
-		return new DataResponse($entries);
107
-	}
39
+    /** @var IUserSession */
40
+    private $userSession;
41
+
42
+    public function __construct(string $appName,
43
+                                IRequest $request,
44
+                                IUserSession $userSession) {
45
+        parent::__construct($appName, $request);
46
+
47
+        $this->userSession = $userSession;
48
+    }
49
+
50
+    /**
51
+     * Formats the given mount config to a mount entry.
52
+     *
53
+     * @param string $mountPoint mount point name, relative to the data dir
54
+     * @param array $mountConfig mount config to format
55
+     *
56
+     * @return array entry
57
+     */
58
+    private function formatMount(string $mountPoint, array $mountConfig): array {
59
+        // strip "/$user/files" from mount point
60
+        $mountPoint = explode('/', trim($mountPoint, '/'), 3);
61
+        $mountPoint = $mountPoint[2] ?? '';
62
+
63
+        // split path from mount point
64
+        $path = \dirname($mountPoint);
65
+        if ($path === '.') {
66
+            $path = '';
67
+        }
68
+
69
+        $isSystemMount = !$mountConfig['personal'];
70
+
71
+        $permissions = \OCP\Constants::PERMISSION_READ;
72
+        // personal mounts can be deleted
73
+        if (!$isSystemMount) {
74
+            $permissions |= \OCP\Constants::PERMISSION_DELETE;
75
+        }
76
+
77
+        $entry = [
78
+            'name' => basename($mountPoint),
79
+            'path' => $path,
80
+            'type' => 'dir',
81
+            'backend' => $mountConfig['backend'],
82
+            'scope' => $isSystemMount ? 'system' : 'personal',
83
+            'permissions' => $permissions,
84
+            'id' => $mountConfig['id'],
85
+            'class' => $mountConfig['class']
86
+        ];
87
+        return $entry;
88
+    }
89
+
90
+    /**
91
+     * @NoAdminRequired
92
+     *
93
+     * Returns the mount points visible for this user.
94
+     *
95
+     * @return DataResponse share information
96
+     */
97
+    public function getUserMounts(): DataResponse {
98
+        $entries = [];
99
+        $user = $this->userSession->getUser()->getUID();
100
+
101
+        $mounts = \OC_Mount_Config::getAbsoluteMountPoints($user);
102
+        foreach($mounts as $mountPoint => $mount) {
103
+            $entries[] = $this->formatMount($mountPoint, $mount);
104
+        }
105
+
106
+        return new DataResponse($entries);
107
+    }
108 108
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/AjaxController.php 1 patch
Indentation   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -37,84 +37,84 @@
 block discarded – undo
37 37
 use OCP\IUserSession;
38 38
 
39 39
 class AjaxController extends Controller {
40
-	/** @var RSA */
41
-	private $rsaMechanism;
42
-	/** @var GlobalAuth  */
43
-	private $globalAuth;
44
-	/** @var IUserSession */
45
-	private $userSession;
46
-	/** @var IGroupManager */
47
-	private $groupManager;
40
+    /** @var RSA */
41
+    private $rsaMechanism;
42
+    /** @var GlobalAuth  */
43
+    private $globalAuth;
44
+    /** @var IUserSession */
45
+    private $userSession;
46
+    /** @var IGroupManager */
47
+    private $groupManager;
48 48
 
49
-	/**
50
-	 * @param string $appName
51
-	 * @param IRequest $request
52
-	 * @param RSA $rsaMechanism
53
-	 * @param GlobalAuth $globalAuth
54
-	 * @param IUserSession $userSession
55
-	 * @param IGroupManager $groupManager
56
-	 */
57
-	public function __construct($appName,
58
-								IRequest $request,
59
-								RSA $rsaMechanism,
60
-								GlobalAuth $globalAuth,
61
-								IUserSession $userSession,
62
-								IGroupManager $groupManager) {
63
-		parent::__construct($appName, $request);
64
-		$this->rsaMechanism = $rsaMechanism;
65
-		$this->globalAuth = $globalAuth;
66
-		$this->userSession = $userSession;
67
-		$this->groupManager = $groupManager;
68
-	}
49
+    /**
50
+     * @param string $appName
51
+     * @param IRequest $request
52
+     * @param RSA $rsaMechanism
53
+     * @param GlobalAuth $globalAuth
54
+     * @param IUserSession $userSession
55
+     * @param IGroupManager $groupManager
56
+     */
57
+    public function __construct($appName,
58
+                                IRequest $request,
59
+                                RSA $rsaMechanism,
60
+                                GlobalAuth $globalAuth,
61
+                                IUserSession $userSession,
62
+                                IGroupManager $groupManager) {
63
+        parent::__construct($appName, $request);
64
+        $this->rsaMechanism = $rsaMechanism;
65
+        $this->globalAuth = $globalAuth;
66
+        $this->userSession = $userSession;
67
+        $this->groupManager = $groupManager;
68
+    }
69 69
 
70
-	/**
71
-	 * @param int $keyLength
72
-	 * @return array
73
-	 */
74
-	private function generateSshKeys($keyLength) {
75
-		$key = $this->rsaMechanism->createKey($keyLength);
76
-		// Replace the placeholder label with a more meaningful one
77
-		$key['publickey'] = str_replace('phpseclib-generated-key', gethostname(), $key['publickey']);
70
+    /**
71
+     * @param int $keyLength
72
+     * @return array
73
+     */
74
+    private function generateSshKeys($keyLength) {
75
+        $key = $this->rsaMechanism->createKey($keyLength);
76
+        // Replace the placeholder label with a more meaningful one
77
+        $key['publickey'] = str_replace('phpseclib-generated-key', gethostname(), $key['publickey']);
78 78
 
79
-		return $key;
80
-	}
79
+        return $key;
80
+    }
81 81
 
82
-	/**
83
-	 * Generates an SSH public/private key pair.
84
-	 *
85
-	 * @NoAdminRequired
86
-	 * @param int $keyLength
87
-	 */
88
-	public function getSshKeys($keyLength = 1024) {
89
-		$key = $this->generateSshKeys($keyLength);
90
-		return new JSONResponse(
91
-			['data' => [
92
-				'private_key' => $key['privatekey'],
93
-				'public_key' => $key['publickey']
94
-			],
95
-			'status' => 'success'
96
-		]);
97
-	}
82
+    /**
83
+     * Generates an SSH public/private key pair.
84
+     *
85
+     * @NoAdminRequired
86
+     * @param int $keyLength
87
+     */
88
+    public function getSshKeys($keyLength = 1024) {
89
+        $key = $this->generateSshKeys($keyLength);
90
+        return new JSONResponse(
91
+            ['data' => [
92
+                'private_key' => $key['privatekey'],
93
+                'public_key' => $key['publickey']
94
+            ],
95
+            'status' => 'success'
96
+        ]);
97
+    }
98 98
 
99
-	/**
100
-	 * @NoAdminRequired
101
-	 *
102
-	 * @param string $uid
103
-	 * @param string $user
104
-	 * @param string $password
105
-	 * @return bool
106
-	 */
107
-	public function saveGlobalCredentials($uid, $user, $password) {
108
-		$currentUser = $this->userSession->getUser();
99
+    /**
100
+     * @NoAdminRequired
101
+     *
102
+     * @param string $uid
103
+     * @param string $user
104
+     * @param string $password
105
+     * @return bool
106
+     */
107
+    public function saveGlobalCredentials($uid, $user, $password) {
108
+        $currentUser = $this->userSession->getUser();
109 109
 
110
-		// Non-admins can only edit their own credentials
111
-		$allowedToEdit = ($this->groupManager->isAdmin($currentUser->getUID()) || $currentUser->getUID() === $uid);
110
+        // Non-admins can only edit their own credentials
111
+        $allowedToEdit = ($this->groupManager->isAdmin($currentUser->getUID()) || $currentUser->getUID() === $uid);
112 112
 
113
-		if ($allowedToEdit) {
114
-			$this->globalAuth->saveAuth($uid, $user, $password);
115
-			return true;
116
-		} else {
117
-			return false;
118
-		}
119
-	}
113
+        if ($allowedToEdit) {
114
+            $this->globalAuth->saveAuth($uid, $user, $password);
115
+            return true;
116
+        } else {
117
+            return false;
118
+        }
119
+    }
120 120
 }
Please login to merge, or discard this patch.
apps/files_external/lib/config.php 1 patch
Indentation   +383 added lines, -383 removed lines patch added patch discarded remove patch
@@ -58,387 +58,387 @@
 block discarded – undo
58 58
  * Class to configure mount.json globally and for users
59 59
  */
60 60
 class OC_Mount_Config {
61
-	// TODO: make this class non-static and give it a proper namespace
62
-
63
-	const MOUNT_TYPE_GLOBAL = 'global';
64
-	const MOUNT_TYPE_GROUP = 'group';
65
-	const MOUNT_TYPE_USER = 'user';
66
-	const MOUNT_TYPE_PERSONAL = 'personal';
67
-
68
-	// whether to skip backend test (for unit tests, as this static class is not mockable)
69
-	public static $skipTest = false;
70
-
71
-	/** @var Application */
72
-	public static $app;
73
-
74
-	/**
75
-	 * @param string $class
76
-	 * @param array $definition
77
-	 * @return bool
78
-	 * @deprecated 8.2.0 use \OCA\Files_External\Service\BackendService::registerBackend()
79
-	 */
80
-	public static function registerBackend($class, $definition) {
81
-		$backendService = self::$app->getContainer()->query(BackendService::class);
82
-		$auth = self::$app->getContainer()->query(Builtin::class);
83
-
84
-		$backendService->registerBackend(new LegacyBackend($class, $definition, $auth));
85
-
86
-		return true;
87
-	}
88
-
89
-	/**
90
-	 * Returns the mount points for the given user.
91
-	 * The mount point is relative to the data directory.
92
-	 *
93
-	 * @param string $uid user
94
-	 * @return array of mount point string as key, mountpoint config as value
95
-	 *
96
-	 * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
97
-	 */
98
-	public static function getAbsoluteMountPoints($uid) {
99
-		$mountPoints = [];
100
-
101
-		$userGlobalStoragesService = self::$app->getContainer()->query(UserGlobalStoragesService::class);
102
-		$userStoragesService = self::$app->getContainer()->query(UserStoragesService::class);
103
-		$user = self::$app->getContainer()->query(IUserManager::class)->get($uid);
104
-
105
-		$userGlobalStoragesService->setUser($user);
106
-		$userStoragesService->setUser($user);
107
-
108
-		foreach ($userGlobalStoragesService->getStorages() as $storage) {
109
-			/** @var \OCA\Files_External\Lib\StorageConfig $storage */
110
-			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
111
-			$mountEntry = self::prepareMountPointEntry($storage, false);
112
-			foreach ($mountEntry['options'] as &$option) {
113
-				$option = self::substitutePlaceholdersInConfig($option, $uid);
114
-			}
115
-			$mountPoints[$mountPoint] = $mountEntry;
116
-		}
117
-
118
-		foreach ($userStoragesService->getStorages() as $storage) {
119
-			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
120
-			$mountEntry = self::prepareMountPointEntry($storage, true);
121
-			foreach ($mountEntry['options'] as &$option) {
122
-				$option = self::substitutePlaceholdersInConfig($option, $uid);
123
-			}
124
-			$mountPoints[$mountPoint] = $mountEntry;
125
-		}
126
-
127
-		$userGlobalStoragesService->resetUser();
128
-		$userStoragesService->resetUser();
129
-
130
-		return $mountPoints;
131
-	}
132
-
133
-	/**
134
-	 * Get the system mount points
135
-	 *
136
-	 * @return array
137
-	 *
138
-	 * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
139
-	 */
140
-	public static function getSystemMountPoints() {
141
-		$mountPoints = [];
142
-		$service = self::$app->getContainer()->query(GlobalStoragesService::class);
143
-
144
-		foreach ($service->getStorages() as $storage) {
145
-			$mountPoints[] = self::prepareMountPointEntry($storage, false);
146
-		}
147
-
148
-		return $mountPoints;
149
-	}
150
-
151
-	/**
152
-	 * Get the personal mount points of the current user
153
-	 *
154
-	 * @return array
155
-	 *
156
-	 * @deprecated 8.2.0 use UserStoragesService::getStorages()
157
-	 */
158
-	public static function getPersonalMountPoints() {
159
-		$mountPoints = [];
160
-		$service = self::$app->getContainer()->query(UserStoragesService::class);
161
-
162
-		foreach ($service->getStorages() as $storage) {
163
-			$mountPoints[] = self::prepareMountPointEntry($storage, true);
164
-		}
165
-
166
-		return $mountPoints;
167
-	}
168
-
169
-	/**
170
-	 * Convert a StorageConfig to the legacy mountPoints array format
171
-	 * There's a lot of extra information in here, to satisfy all of the legacy functions
172
-	 *
173
-	 * @param StorageConfig $storage
174
-	 * @param bool $isPersonal
175
-	 * @return array
176
-	 */
177
-	private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
178
-		$mountEntry = [];
179
-
180
-		$mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
181
-		$mountEntry['class'] = $storage->getBackend()->getIdentifier();
182
-		$mountEntry['backend'] = $storage->getBackend()->getText();
183
-		$mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
184
-		$mountEntry['personal'] = $isPersonal;
185
-		$mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
186
-		$mountEntry['mountOptions'] = $storage->getMountOptions();
187
-		$mountEntry['priority'] = $storage->getPriority();
188
-		$mountEntry['applicable'] = [
189
-			'groups' => $storage->getApplicableGroups(),
190
-			'users' => $storage->getApplicableUsers(),
191
-		];
192
-		// if mountpoint is applicable to all users the old API expects ['all']
193
-		if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
194
-			$mountEntry['applicable']['users'] = ['all'];
195
-		}
196
-
197
-		$mountEntry['id'] = $storage->getId();
198
-
199
-		return $mountEntry;
200
-	}
201
-
202
-	/**
203
-	 * fill in the correct values for $user
204
-	 *
205
-	 * @param string $user user value
206
-	 * @param string|array $input
207
-	 * @return string
208
-	 * @deprecated use self::substitutePlaceholdersInConfig($input)
209
-	 */
210
-	public static function setUserVars($user, $input) {
211
-		$handler = self::$app->getContainer()->query(UserPlaceholderHandler::class);
212
-		return $handler->handle($input);
213
-	}
214
-
215
-	/**
216
-	 * @param mixed $input
217
-	 * @param string|null $userId
218
-	 * @return mixed
219
-	 * @throws \OCP\AppFramework\QueryException
220
-	 * @since 16.0.0
221
-	 */
222
-	public static function substitutePlaceholdersInConfig($input, string $userId = null) {
223
-		/** @var BackendService $backendService */
224
-		$backendService = self::$app->getContainer()->query(BackendService::class);
225
-		/** @var IConfigHandler[] $handlers */
226
-		$handlers = $backendService->getConfigHandlers();
227
-		foreach ($handlers as $handler) {
228
-			if ($handler instanceof UserContext && $userId !== null) {
229
-				$handler->setUserId($userId);
230
-			}
231
-			$input = $handler->handle($input);
232
-		}
233
-		return $input;
234
-	}
235
-
236
-	/**
237
-	 * Test connecting using the given backend configuration
238
-	 *
239
-	 * @param string $class backend class name
240
-	 * @param array $options backend configuration options
241
-	 * @param boolean $isPersonal
242
-	 * @return int see self::STATUS_*
243
-	 * @throws Exception
244
-	 */
245
-	public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
246
-		if (self::$skipTest) {
247
-			return StorageNotAvailableException::STATUS_SUCCESS;
248
-		}
249
-		foreach ($options as $key => &$option) {
250
-			if($key === 'password') {
251
-				// no replacements in passwords
252
-				continue;
253
-			}
254
-			$option = self::substitutePlaceholdersInConfig($option);
255
-		}
256
-		if (class_exists($class)) {
257
-			try {
258
-				/** @var \OC\Files\Storage\Common $storage */
259
-				$storage = new $class($options);
260
-
261
-				try {
262
-					$result = $storage->test($isPersonal, $testOnly);
263
-					$storage->setAvailability($result);
264
-					if ($result) {
265
-						return StorageNotAvailableException::STATUS_SUCCESS;
266
-					}
267
-				} catch (\Exception $e) {
268
-					$storage->setAvailability(false);
269
-					throw $e;
270
-				}
271
-			} catch (Exception $exception) {
272
-				\OC::$server->getLogger()->logException($exception, ['app' => 'files_external']);
273
-				throw $exception;
274
-			}
275
-		}
276
-		return StorageNotAvailableException::STATUS_ERROR;
277
-	}
278
-
279
-	/**
280
-	 * Read the mount points in the config file into an array
281
-	 *
282
-	 * @param string|null $user If not null, personal for $user, otherwise system
283
-	 * @return array
284
-	 */
285
-	public static function readData($user = null) {
286
-		if (isset($user)) {
287
-			$jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
288
-		} else {
289
-			$config = \OC::$server->getConfig();
290
-			$datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
291
-			$jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
292
-		}
293
-		if (is_file($jsonFile)) {
294
-			$mountPoints = json_decode(file_get_contents($jsonFile), true);
295
-			if (is_array($mountPoints)) {
296
-				return $mountPoints;
297
-			}
298
-		}
299
-		return [];
300
-	}
301
-
302
-	/**
303
-	 * Get backend dependency message
304
-	 * TODO: move into AppFramework along with templates
305
-	 *
306
-	 * @param Backend[] $backends
307
-	 * @return string
308
-	 */
309
-	public static function dependencyMessage($backends) {
310
-		$l = \OC::$server->getL10N('files_external');
311
-		$message = '';
312
-		$dependencyGroups = [];
313
-
314
-		foreach ($backends as $backend) {
315
-			foreach ($backend->checkDependencies() as $dependency) {
316
-				if ($message = $dependency->getMessage()) {
317
-					$message .= '<p>' . $message . '</p>';
318
-				} else {
319
-					$dependencyGroups[$dependency->getDependency()][] = $backend;
320
-				}
321
-			}
322
-		}
323
-
324
-		foreach ($dependencyGroups as $module => $dependants) {
325
-			$backends = implode(', ', array_map(function($backend) {
326
-				return '"' . $backend->getText() . '"';
327
-			}, $dependants));
328
-			$message .= '<p>' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends) . '</p>';
329
-		}
330
-
331
-		return $message;
332
-	}
333
-
334
-	/**
335
-	 * Returns a dependency missing message
336
-	 *
337
-	 * @param \OCP\IL10N $l
338
-	 * @param string $module
339
-	 * @param string $backend
340
-	 * @return string
341
-	 */
342
-	private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
343
-		switch (strtolower($module)) {
344
-			case 'curl':
345
-				return (string)$l->t('The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
346
-			case 'ftp':
347
-				return (string)$l->t('The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
348
-			default:
349
-				return (string)$l->t('"%1$s" is not installed. Mounting of %2$s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
350
-		}
351
-	}
352
-
353
-	/**
354
-	 * Encrypt passwords in the given config options
355
-	 *
356
-	 * @param array $options mount options
357
-	 * @return array updated options
358
-	 */
359
-	public static function encryptPasswords($options) {
360
-		if (isset($options['password'])) {
361
-			$options['password_encrypted'] = self::encryptPassword($options['password']);
362
-			// do not unset the password, we want to keep the keys order
363
-			// on load... because that's how the UI currently works
364
-			$options['password'] = '';
365
-		}
366
-		return $options;
367
-	}
368
-
369
-	/**
370
-	 * Decrypt passwords in the given config options
371
-	 *
372
-	 * @param array $options mount options
373
-	 * @return array updated options
374
-	 */
375
-	public static function decryptPasswords($options) {
376
-		// note: legacy options might still have the unencrypted password in the "password" field
377
-		if (isset($options['password_encrypted'])) {
378
-			$options['password'] = self::decryptPassword($options['password_encrypted']);
379
-			unset($options['password_encrypted']);
380
-		}
381
-		return $options;
382
-	}
383
-
384
-	/**
385
-	 * Encrypt a single password
386
-	 *
387
-	 * @param string $password plain text password
388
-	 * @return string encrypted password
389
-	 */
390
-	private static function encryptPassword($password) {
391
-		$cipher = self::getCipher();
392
-		$iv = \OC::$server->getSecureRandom()->generate(16);
393
-		$cipher->setIV($iv);
394
-		return base64_encode($iv . $cipher->encrypt($password));
395
-	}
396
-
397
-	/**
398
-	 * Decrypts a single password
399
-	 *
400
-	 * @param string $encryptedPassword encrypted password
401
-	 * @return string plain text password
402
-	 */
403
-	private static function decryptPassword($encryptedPassword) {
404
-		$cipher = self::getCipher();
405
-		$binaryPassword = base64_decode($encryptedPassword);
406
-		$iv = substr($binaryPassword, 0, 16);
407
-		$cipher->setIV($iv);
408
-		$binaryPassword = substr($binaryPassword, 16);
409
-		return $cipher->decrypt($binaryPassword);
410
-	}
411
-
412
-	/**
413
-	 * Returns the encryption cipher
414
-	 *
415
-	 * @return AES
416
-	 */
417
-	private static function getCipher() {
418
-		$cipher = new AES(AES::MODE_CBC);
419
-		$cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
420
-		return $cipher;
421
-	}
422
-
423
-	/**
424
-	 * Computes a hash based on the given configuration.
425
-	 * This is mostly used to find out whether configurations
426
-	 * are the same.
427
-	 *
428
-	 * @param array $config
429
-	 * @return string
430
-	 */
431
-	public static function makeConfigHash($config) {
432
-		$data = json_encode(
433
-			[
434
-				'c' => $config['backend'],
435
-				'a' => $config['authMechanism'],
436
-				'm' => $config['mountpoint'],
437
-				'o' => $config['options'],
438
-				'p' => isset($config['priority']) ? $config['priority'] : -1,
439
-				'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
440
-			]
441
-		);
442
-		return hash('md5', $data);
443
-	}
61
+    // TODO: make this class non-static and give it a proper namespace
62
+
63
+    const MOUNT_TYPE_GLOBAL = 'global';
64
+    const MOUNT_TYPE_GROUP = 'group';
65
+    const MOUNT_TYPE_USER = 'user';
66
+    const MOUNT_TYPE_PERSONAL = 'personal';
67
+
68
+    // whether to skip backend test (for unit tests, as this static class is not mockable)
69
+    public static $skipTest = false;
70
+
71
+    /** @var Application */
72
+    public static $app;
73
+
74
+    /**
75
+     * @param string $class
76
+     * @param array $definition
77
+     * @return bool
78
+     * @deprecated 8.2.0 use \OCA\Files_External\Service\BackendService::registerBackend()
79
+     */
80
+    public static function registerBackend($class, $definition) {
81
+        $backendService = self::$app->getContainer()->query(BackendService::class);
82
+        $auth = self::$app->getContainer()->query(Builtin::class);
83
+
84
+        $backendService->registerBackend(new LegacyBackend($class, $definition, $auth));
85
+
86
+        return true;
87
+    }
88
+
89
+    /**
90
+     * Returns the mount points for the given user.
91
+     * The mount point is relative to the data directory.
92
+     *
93
+     * @param string $uid user
94
+     * @return array of mount point string as key, mountpoint config as value
95
+     *
96
+     * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
97
+     */
98
+    public static function getAbsoluteMountPoints($uid) {
99
+        $mountPoints = [];
100
+
101
+        $userGlobalStoragesService = self::$app->getContainer()->query(UserGlobalStoragesService::class);
102
+        $userStoragesService = self::$app->getContainer()->query(UserStoragesService::class);
103
+        $user = self::$app->getContainer()->query(IUserManager::class)->get($uid);
104
+
105
+        $userGlobalStoragesService->setUser($user);
106
+        $userStoragesService->setUser($user);
107
+
108
+        foreach ($userGlobalStoragesService->getStorages() as $storage) {
109
+            /** @var \OCA\Files_External\Lib\StorageConfig $storage */
110
+            $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
111
+            $mountEntry = self::prepareMountPointEntry($storage, false);
112
+            foreach ($mountEntry['options'] as &$option) {
113
+                $option = self::substitutePlaceholdersInConfig($option, $uid);
114
+            }
115
+            $mountPoints[$mountPoint] = $mountEntry;
116
+        }
117
+
118
+        foreach ($userStoragesService->getStorages() as $storage) {
119
+            $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
120
+            $mountEntry = self::prepareMountPointEntry($storage, true);
121
+            foreach ($mountEntry['options'] as &$option) {
122
+                $option = self::substitutePlaceholdersInConfig($option, $uid);
123
+            }
124
+            $mountPoints[$mountPoint] = $mountEntry;
125
+        }
126
+
127
+        $userGlobalStoragesService->resetUser();
128
+        $userStoragesService->resetUser();
129
+
130
+        return $mountPoints;
131
+    }
132
+
133
+    /**
134
+     * Get the system mount points
135
+     *
136
+     * @return array
137
+     *
138
+     * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
139
+     */
140
+    public static function getSystemMountPoints() {
141
+        $mountPoints = [];
142
+        $service = self::$app->getContainer()->query(GlobalStoragesService::class);
143
+
144
+        foreach ($service->getStorages() as $storage) {
145
+            $mountPoints[] = self::prepareMountPointEntry($storage, false);
146
+        }
147
+
148
+        return $mountPoints;
149
+    }
150
+
151
+    /**
152
+     * Get the personal mount points of the current user
153
+     *
154
+     * @return array
155
+     *
156
+     * @deprecated 8.2.0 use UserStoragesService::getStorages()
157
+     */
158
+    public static function getPersonalMountPoints() {
159
+        $mountPoints = [];
160
+        $service = self::$app->getContainer()->query(UserStoragesService::class);
161
+
162
+        foreach ($service->getStorages() as $storage) {
163
+            $mountPoints[] = self::prepareMountPointEntry($storage, true);
164
+        }
165
+
166
+        return $mountPoints;
167
+    }
168
+
169
+    /**
170
+     * Convert a StorageConfig to the legacy mountPoints array format
171
+     * There's a lot of extra information in here, to satisfy all of the legacy functions
172
+     *
173
+     * @param StorageConfig $storage
174
+     * @param bool $isPersonal
175
+     * @return array
176
+     */
177
+    private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
178
+        $mountEntry = [];
179
+
180
+        $mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
181
+        $mountEntry['class'] = $storage->getBackend()->getIdentifier();
182
+        $mountEntry['backend'] = $storage->getBackend()->getText();
183
+        $mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
184
+        $mountEntry['personal'] = $isPersonal;
185
+        $mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
186
+        $mountEntry['mountOptions'] = $storage->getMountOptions();
187
+        $mountEntry['priority'] = $storage->getPriority();
188
+        $mountEntry['applicable'] = [
189
+            'groups' => $storage->getApplicableGroups(),
190
+            'users' => $storage->getApplicableUsers(),
191
+        ];
192
+        // if mountpoint is applicable to all users the old API expects ['all']
193
+        if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
194
+            $mountEntry['applicable']['users'] = ['all'];
195
+        }
196
+
197
+        $mountEntry['id'] = $storage->getId();
198
+
199
+        return $mountEntry;
200
+    }
201
+
202
+    /**
203
+     * fill in the correct values for $user
204
+     *
205
+     * @param string $user user value
206
+     * @param string|array $input
207
+     * @return string
208
+     * @deprecated use self::substitutePlaceholdersInConfig($input)
209
+     */
210
+    public static function setUserVars($user, $input) {
211
+        $handler = self::$app->getContainer()->query(UserPlaceholderHandler::class);
212
+        return $handler->handle($input);
213
+    }
214
+
215
+    /**
216
+     * @param mixed $input
217
+     * @param string|null $userId
218
+     * @return mixed
219
+     * @throws \OCP\AppFramework\QueryException
220
+     * @since 16.0.0
221
+     */
222
+    public static function substitutePlaceholdersInConfig($input, string $userId = null) {
223
+        /** @var BackendService $backendService */
224
+        $backendService = self::$app->getContainer()->query(BackendService::class);
225
+        /** @var IConfigHandler[] $handlers */
226
+        $handlers = $backendService->getConfigHandlers();
227
+        foreach ($handlers as $handler) {
228
+            if ($handler instanceof UserContext && $userId !== null) {
229
+                $handler->setUserId($userId);
230
+            }
231
+            $input = $handler->handle($input);
232
+        }
233
+        return $input;
234
+    }
235
+
236
+    /**
237
+     * Test connecting using the given backend configuration
238
+     *
239
+     * @param string $class backend class name
240
+     * @param array $options backend configuration options
241
+     * @param boolean $isPersonal
242
+     * @return int see self::STATUS_*
243
+     * @throws Exception
244
+     */
245
+    public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
246
+        if (self::$skipTest) {
247
+            return StorageNotAvailableException::STATUS_SUCCESS;
248
+        }
249
+        foreach ($options as $key => &$option) {
250
+            if($key === 'password') {
251
+                // no replacements in passwords
252
+                continue;
253
+            }
254
+            $option = self::substitutePlaceholdersInConfig($option);
255
+        }
256
+        if (class_exists($class)) {
257
+            try {
258
+                /** @var \OC\Files\Storage\Common $storage */
259
+                $storage = new $class($options);
260
+
261
+                try {
262
+                    $result = $storage->test($isPersonal, $testOnly);
263
+                    $storage->setAvailability($result);
264
+                    if ($result) {
265
+                        return StorageNotAvailableException::STATUS_SUCCESS;
266
+                    }
267
+                } catch (\Exception $e) {
268
+                    $storage->setAvailability(false);
269
+                    throw $e;
270
+                }
271
+            } catch (Exception $exception) {
272
+                \OC::$server->getLogger()->logException($exception, ['app' => 'files_external']);
273
+                throw $exception;
274
+            }
275
+        }
276
+        return StorageNotAvailableException::STATUS_ERROR;
277
+    }
278
+
279
+    /**
280
+     * Read the mount points in the config file into an array
281
+     *
282
+     * @param string|null $user If not null, personal for $user, otherwise system
283
+     * @return array
284
+     */
285
+    public static function readData($user = null) {
286
+        if (isset($user)) {
287
+            $jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
288
+        } else {
289
+            $config = \OC::$server->getConfig();
290
+            $datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
291
+            $jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
292
+        }
293
+        if (is_file($jsonFile)) {
294
+            $mountPoints = json_decode(file_get_contents($jsonFile), true);
295
+            if (is_array($mountPoints)) {
296
+                return $mountPoints;
297
+            }
298
+        }
299
+        return [];
300
+    }
301
+
302
+    /**
303
+     * Get backend dependency message
304
+     * TODO: move into AppFramework along with templates
305
+     *
306
+     * @param Backend[] $backends
307
+     * @return string
308
+     */
309
+    public static function dependencyMessage($backends) {
310
+        $l = \OC::$server->getL10N('files_external');
311
+        $message = '';
312
+        $dependencyGroups = [];
313
+
314
+        foreach ($backends as $backend) {
315
+            foreach ($backend->checkDependencies() as $dependency) {
316
+                if ($message = $dependency->getMessage()) {
317
+                    $message .= '<p>' . $message . '</p>';
318
+                } else {
319
+                    $dependencyGroups[$dependency->getDependency()][] = $backend;
320
+                }
321
+            }
322
+        }
323
+
324
+        foreach ($dependencyGroups as $module => $dependants) {
325
+            $backends = implode(', ', array_map(function($backend) {
326
+                return '"' . $backend->getText() . '"';
327
+            }, $dependants));
328
+            $message .= '<p>' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends) . '</p>';
329
+        }
330
+
331
+        return $message;
332
+    }
333
+
334
+    /**
335
+     * Returns a dependency missing message
336
+     *
337
+     * @param \OCP\IL10N $l
338
+     * @param string $module
339
+     * @param string $backend
340
+     * @return string
341
+     */
342
+    private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
343
+        switch (strtolower($module)) {
344
+            case 'curl':
345
+                return (string)$l->t('The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
346
+            case 'ftp':
347
+                return (string)$l->t('The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
348
+            default:
349
+                return (string)$l->t('"%1$s" is not installed. Mounting of %2$s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
350
+        }
351
+    }
352
+
353
+    /**
354
+     * Encrypt passwords in the given config options
355
+     *
356
+     * @param array $options mount options
357
+     * @return array updated options
358
+     */
359
+    public static function encryptPasswords($options) {
360
+        if (isset($options['password'])) {
361
+            $options['password_encrypted'] = self::encryptPassword($options['password']);
362
+            // do not unset the password, we want to keep the keys order
363
+            // on load... because that's how the UI currently works
364
+            $options['password'] = '';
365
+        }
366
+        return $options;
367
+    }
368
+
369
+    /**
370
+     * Decrypt passwords in the given config options
371
+     *
372
+     * @param array $options mount options
373
+     * @return array updated options
374
+     */
375
+    public static function decryptPasswords($options) {
376
+        // note: legacy options might still have the unencrypted password in the "password" field
377
+        if (isset($options['password_encrypted'])) {
378
+            $options['password'] = self::decryptPassword($options['password_encrypted']);
379
+            unset($options['password_encrypted']);
380
+        }
381
+        return $options;
382
+    }
383
+
384
+    /**
385
+     * Encrypt a single password
386
+     *
387
+     * @param string $password plain text password
388
+     * @return string encrypted password
389
+     */
390
+    private static function encryptPassword($password) {
391
+        $cipher = self::getCipher();
392
+        $iv = \OC::$server->getSecureRandom()->generate(16);
393
+        $cipher->setIV($iv);
394
+        return base64_encode($iv . $cipher->encrypt($password));
395
+    }
396
+
397
+    /**
398
+     * Decrypts a single password
399
+     *
400
+     * @param string $encryptedPassword encrypted password
401
+     * @return string plain text password
402
+     */
403
+    private static function decryptPassword($encryptedPassword) {
404
+        $cipher = self::getCipher();
405
+        $binaryPassword = base64_decode($encryptedPassword);
406
+        $iv = substr($binaryPassword, 0, 16);
407
+        $cipher->setIV($iv);
408
+        $binaryPassword = substr($binaryPassword, 16);
409
+        return $cipher->decrypt($binaryPassword);
410
+    }
411
+
412
+    /**
413
+     * Returns the encryption cipher
414
+     *
415
+     * @return AES
416
+     */
417
+    private static function getCipher() {
418
+        $cipher = new AES(AES::MODE_CBC);
419
+        $cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
420
+        return $cipher;
421
+    }
422
+
423
+    /**
424
+     * Computes a hash based on the given configuration.
425
+     * This is mostly used to find out whether configurations
426
+     * are the same.
427
+     *
428
+     * @param array $config
429
+     * @return string
430
+     */
431
+    public static function makeConfigHash($config) {
432
+        $data = json_encode(
433
+            [
434
+                'c' => $config['backend'],
435
+                'a' => $config['authMechanism'],
436
+                'm' => $config['mountpoint'],
437
+                'o' => $config['options'],
438
+                'p' => isset($config['priority']) ? $config['priority'] : -1,
439
+                'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
440
+            ]
441
+        );
442
+        return hash('md5', $data);
443
+    }
444 444
 }
Please login to merge, or discard this patch.
apps/comments/lib/AppInfo/Application.php 2 patches
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -42,55 +42,55 @@
 block discarded – undo
42 42
 
43 43
 class Application extends App {
44 44
 
45
-	const APP_ID = 'comments';
45
+    const APP_ID = 'comments';
46 46
 
47
-	public function __construct (array $urlParams = []) {
48
-		parent::__construct(self::APP_ID, $urlParams);
49
-		$container = $this->getContainer();
47
+    public function __construct (array $urlParams = []) {
48
+        parent::__construct(self::APP_ID, $urlParams);
49
+        $container = $this->getContainer();
50 50
 
51
-		$container->registerAlias('NotificationsController', Notifications::class);
51
+        $container->registerAlias('NotificationsController', Notifications::class);
52 52
 
53
-		$jsSettingsHelper = new JSSettingsHelper($container->getServer());
54
-		Util::connectHook('\OCP\Config', 'js', $jsSettingsHelper, 'extend');
53
+        $jsSettingsHelper = new JSSettingsHelper($container->getServer());
54
+        Util::connectHook('\OCP\Config', 'js', $jsSettingsHelper, 'extend');
55 55
 
56
-		$this->register();
57
-	}
56
+        $this->register();
57
+    }
58 58
 
59
-	private function register() {
60
-		$server = $this->getContainer()->getServer();
59
+    private function register() {
60
+        $server = $this->getContainer()->getServer();
61 61
 
62
-		/** @var IEventDispatcher $newDispatcher */
63
-		$dispatcher = $server->query(IEventDispatcher::class);
62
+        /** @var IEventDispatcher $newDispatcher */
63
+        $dispatcher = $server->query(IEventDispatcher::class);
64 64
 
65
-		$this->registerEventsScripts($dispatcher);
66
-		$this->registerDavEntity($dispatcher);
67
-		$this->registerNotifier();
68
-		$this->registerCommentsEventHandler();
65
+        $this->registerEventsScripts($dispatcher);
66
+        $this->registerDavEntity($dispatcher);
67
+        $this->registerNotifier();
68
+        $this->registerCommentsEventHandler();
69 69
 
70
-		$server->getSearch()->registerProvider(Provider::class, ['apps' => ['files']]);
71
-	}
70
+        $server->getSearch()->registerProvider(Provider::class, ['apps' => ['files']]);
71
+    }
72 72
 
73
-	protected function registerEventsScripts(IEventDispatcher $dispatcher) {
74
-		$dispatcher->addServiceListener(LoadAdditionalScriptsEvent::class, LoadAdditionalScripts::class);
75
-		$dispatcher->addServiceListener(LoadSidebar::class, LoadSidebarScripts::class);
76
-	}
73
+    protected function registerEventsScripts(IEventDispatcher $dispatcher) {
74
+        $dispatcher->addServiceListener(LoadAdditionalScriptsEvent::class, LoadAdditionalScripts::class);
75
+        $dispatcher->addServiceListener(LoadSidebar::class, LoadSidebarScripts::class);
76
+    }
77 77
 
78
-	protected function registerDavEntity(IEventDispatcher $dispatcher) {
79
-		$dispatcher->addListener(CommentsEntityEvent::EVENT_ENTITY, function(CommentsEntityEvent $event) {
80
-			$event->addEntityCollection('files', function($name) {
81
-				$nodes = \OC::$server->getUserFolder()->getById((int)$name);
82
-				return !empty($nodes);
83
-			});
84
-		});
85
-	}
78
+    protected function registerDavEntity(IEventDispatcher $dispatcher) {
79
+        $dispatcher->addListener(CommentsEntityEvent::EVENT_ENTITY, function(CommentsEntityEvent $event) {
80
+            $event->addEntityCollection('files', function($name) {
81
+                $nodes = \OC::$server->getUserFolder()->getById((int)$name);
82
+                return !empty($nodes);
83
+            });
84
+        });
85
+    }
86 86
 
87
-	protected function registerNotifier() {
88
-		$this->getContainer()->getServer()->getNotificationManager()->registerNotifierService(Notifier::class);
89
-	}
87
+    protected function registerNotifier() {
88
+        $this->getContainer()->getServer()->getNotificationManager()->registerNotifierService(Notifier::class);
89
+    }
90 90
 
91
-	protected function registerCommentsEventHandler() {
92
-		$this->getContainer()->getServer()->getCommentsManager()->registerEventHandler(function () {
93
-			return $this->getContainer()->query(EventHandler::class);
94
-		});
95
-	}
91
+    protected function registerCommentsEventHandler() {
92
+        $this->getContainer()->getServer()->getCommentsManager()->registerEventHandler(function () {
93
+            return $this->getContainer()->query(EventHandler::class);
94
+        });
95
+    }
96 96
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 
45 45
 	const APP_ID = 'comments';
46 46
 
47
-	public function __construct (array $urlParams = []) {
47
+	public function __construct(array $urlParams = []) {
48 48
 		parent::__construct(self::APP_ID, $urlParams);
49 49
 		$container = $this->getContainer();
50 50
 
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 	protected function registerDavEntity(IEventDispatcher $dispatcher) {
79 79
 		$dispatcher->addListener(CommentsEntityEvent::EVENT_ENTITY, function(CommentsEntityEvent $event) {
80 80
 			$event->addEntityCollection('files', function($name) {
81
-				$nodes = \OC::$server->getUserFolder()->getById((int)$name);
81
+				$nodes = \OC::$server->getUserFolder()->getById((int) $name);
82 82
 				return !empty($nodes);
83 83
 			});
84 84
 		});
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	}
90 90
 
91 91
 	protected function registerCommentsEventHandler() {
92
-		$this->getContainer()->getServer()->getCommentsManager()->registerEventHandler(function () {
92
+		$this->getContainer()->getServer()->getCommentsManager()->registerEventHandler(function() {
93 93
 			return $this->getContainer()->query(EventHandler::class);
94 94
 		});
95 95
 	}
Please login to merge, or discard this patch.
apps/dav/appinfo/v1/caldav.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -35,22 +35,22 @@  discard block
 block discarded – undo
35 35
 use OCA\DAV\Connector\Sabre\Principal;
36 36
 
37 37
 $authBackend = new Auth(
38
-	\OC::$server->getSession(),
39
-	\OC::$server->getUserSession(),
40
-	\OC::$server->getRequest(),
41
-	\OC::$server->getTwoFactorAuthManager(),
42
-	\OC::$server->getBruteForceThrottler(),
43
-	'principals/'
38
+    \OC::$server->getSession(),
39
+    \OC::$server->getUserSession(),
40
+    \OC::$server->getRequest(),
41
+    \OC::$server->getTwoFactorAuthManager(),
42
+    \OC::$server->getBruteForceThrottler(),
43
+    'principals/'
44 44
 );
45 45
 $principalBackend = new Principal(
46
-	\OC::$server->getUserManager(),
47
-	\OC::$server->getGroupManager(),
48
-	\OC::$server->getShareManager(),
49
-	\OC::$server->getUserSession(),
50
-	\OC::$server->getAppManager(),
51
-	\OC::$server->query(\OCA\DAV\CalDAV\Proxy\ProxyMapper::class),
52
-	\OC::$server->getConfig(),
53
-	'principals/'
46
+    \OC::$server->getUserManager(),
47
+    \OC::$server->getGroupManager(),
48
+    \OC::$server->getShareManager(),
49
+    \OC::$server->getUserSession(),
50
+    \OC::$server->getAppManager(),
51
+    \OC::$server->query(\OCA\DAV\CalDAV\Proxy\ProxyMapper::class),
52
+    \OC::$server->getConfig(),
53
+    'principals/'
54 54
 );
55 55
 $db = \OC::$server->getDatabaseConnection();
56 56
 $userManager = \OC::$server->getUserManager();
@@ -70,8 +70,8 @@  discard block
 block discarded – undo
70 70
 $addressBookRoot->disableListing = !$debugging; // Disable listing
71 71
 
72 72
 $nodes = [
73
-	$principalCollection,
74
-	$addressBookRoot,
73
+    $principalCollection,
74
+    $addressBookRoot,
75 75
 ];
76 76
 
77 77
 // Fire up server
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 
88 88
 $server->addPlugin(new LegacyDAVACL());
89 89
 if ($debugging) {
90
-	$server->addPlugin(new Sabre\DAV\Browser\Plugin());
90
+    $server->addPlugin(new Sabre\DAV\Browser\Plugin());
91 91
 }
92 92
 
93 93
 $server->addPlugin(new \Sabre\DAV\Sync\Plugin());
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 $server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin());
96 96
 
97 97
 if ($sendInvitations) {
98
-	$server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class));
98
+    $server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class));
99 99
 }
100 100
 $server->addPlugin(new ExceptionLoggerPlugin('caldav', \OC::$server->getLogger()));
101 101
 
Please login to merge, or discard this patch.
apps/dav/appinfo/v1/carddav.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -39,22 +39,22 @@  discard block
 block discarded – undo
39 39
 use Sabre\CardDAV\Plugin;
40 40
 
41 41
 $authBackend = new Auth(
42
-	\OC::$server->getSession(),
43
-	\OC::$server->getUserSession(),
44
-	\OC::$server->getRequest(),
45
-	\OC::$server->getTwoFactorAuthManager(),
46
-	\OC::$server->getBruteForceThrottler(),
47
-	'principals/'
42
+    \OC::$server->getSession(),
43
+    \OC::$server->getUserSession(),
44
+    \OC::$server->getRequest(),
45
+    \OC::$server->getTwoFactorAuthManager(),
46
+    \OC::$server->getBruteForceThrottler(),
47
+    'principals/'
48 48
 );
49 49
 $principalBackend = new Principal(
50
-	\OC::$server->getUserManager(),
51
-	\OC::$server->getGroupManager(),
52
-	\OC::$server->getShareManager(),
53
-	\OC::$server->getUserSession(),
54
-	\OC::$server->getAppManager(),
55
-	\OC::$server->query(\OCA\DAV\CalDAV\Proxy\ProxyMapper::class),
56
-	\OC::$server->getConfig(),
57
-	'principals/'
50
+    \OC::$server->getUserManager(),
51
+    \OC::$server->getGroupManager(),
52
+    \OC::$server->getShareManager(),
53
+    \OC::$server->getUserSession(),
54
+    \OC::$server->getAppManager(),
55
+    \OC::$server->query(\OCA\DAV\CalDAV\Proxy\ProxyMapper::class),
56
+    \OC::$server->getConfig(),
57
+    'principals/'
58 58
 );
59 59
 $db = \OC::$server->getDatabaseConnection();
60 60
 $cardDavBackend = new CardDavBackend($db, $principalBackend, \OC::$server->getUserManager(), \OC::$server->getGroupManager(), \OC::$server->getEventDispatcher());
@@ -70,8 +70,8 @@  discard block
 block discarded – undo
70 70
 $addressBookRoot->disableListing = !$debugging; // Disable listing
71 71
 
72 72
 $nodes = [
73
-	$principalCollection,
74
-	$addressBookRoot,
73
+    $principalCollection,
74
+    $addressBookRoot,
75 75
 ];
76 76
 
77 77
 // Fire up server
@@ -86,14 +86,14 @@  discard block
 block discarded – undo
86 86
 
87 87
 $server->addPlugin(new LegacyDAVACL());
88 88
 if ($debugging) {
89
-	$server->addPlugin(new Sabre\DAV\Browser\Plugin());
89
+    $server->addPlugin(new Sabre\DAV\Browser\Plugin());
90 90
 }
91 91
 
92 92
 $server->addPlugin(new \Sabre\DAV\Sync\Plugin());
93 93
 $server->addPlugin(new \Sabre\CardDAV\VCFExportPlugin());
94 94
 $server->addPlugin(new \OCA\DAV\CardDAV\ImageExportPlugin(new \OCA\DAV\CardDAV\PhotoCache(
95
-	\OC::$server->getAppDataDir('dav-photocache'),
96
-	\OC::$server->getLogger()
95
+    \OC::$server->getAppDataDir('dav-photocache'),
96
+    \OC::$server->getLogger()
97 97
 )));
98 98
 $server->addPlugin(new ExceptionLoggerPlugin('carddav', \OC::$server->getLogger()));
99 99
 
Please login to merge, or discard this patch.
apps/dav/lib/Files/BrowserErrorPagePlugin.php 1 patch
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -32,86 +32,86 @@
 block discarded – undo
32 32
 use Sabre\DAV\ServerPlugin;
33 33
 
34 34
 class BrowserErrorPagePlugin extends ServerPlugin {
35
-	/** @var Server */
36
-	private $server;
35
+    /** @var Server */
36
+    private $server;
37 37
 
38
-	/**
39
-	 * This initializes the plugin.
40
-	 *
41
-	 * This function is called by Sabre\DAV\Server, after
42
-	 * addPlugin is called.
43
-	 *
44
-	 * This method should set up the required event subscriptions.
45
-	 *
46
-	 * @param Server $server
47
-	 * @return void
48
-	 */
49
-	function initialize(Server $server) {
50
-		$this->server = $server;
51
-		$server->on('exception', [$this, 'logException'], 1000);
52
-	}
38
+    /**
39
+     * This initializes the plugin.
40
+     *
41
+     * This function is called by Sabre\DAV\Server, after
42
+     * addPlugin is called.
43
+     *
44
+     * This method should set up the required event subscriptions.
45
+     *
46
+     * @param Server $server
47
+     * @return void
48
+     */
49
+    function initialize(Server $server) {
50
+        $this->server = $server;
51
+        $server->on('exception', [$this, 'logException'], 1000);
52
+    }
53 53
 
54
-	/**
55
-	 * @param IRequest $request
56
-	 * @return bool
57
-	 */
58
-	public static function isBrowserRequest(IRequest $request) {
59
-		if ($request->getMethod() !== 'GET') {
60
-			return false;
61
-		}
62
-		return $request->isUserAgent([
63
-			Request::USER_AGENT_IE,
64
-			Request::USER_AGENT_MS_EDGE,
65
-			Request::USER_AGENT_CHROME,
66
-			Request::USER_AGENT_FIREFOX,
67
-			Request::USER_AGENT_SAFARI,
68
-		]);
69
-	}
54
+    /**
55
+     * @param IRequest $request
56
+     * @return bool
57
+     */
58
+    public static function isBrowserRequest(IRequest $request) {
59
+        if ($request->getMethod() !== 'GET') {
60
+            return false;
61
+        }
62
+        return $request->isUserAgent([
63
+            Request::USER_AGENT_IE,
64
+            Request::USER_AGENT_MS_EDGE,
65
+            Request::USER_AGENT_CHROME,
66
+            Request::USER_AGENT_FIREFOX,
67
+            Request::USER_AGENT_SAFARI,
68
+        ]);
69
+    }
70 70
 
71
-	/**
72
-	 * @param \Exception $ex
73
-	 */
74
-	public function logException(\Exception $ex) {
75
-		if ($ex instanceof Exception) {
76
-			$httpCode = $ex->getHTTPCode();
77
-			$headers = $ex->getHTTPHeaders($this->server);
78
-		} else {
79
-			$httpCode = 500;
80
-			$headers = [];
81
-		}
82
-		$this->server->httpResponse->addHeaders($headers);
83
-		$this->server->httpResponse->setStatus($httpCode);
84
-		$body = $this->generateBody($httpCode);
85
-		$this->server->httpResponse->setBody($body);
86
-		$csp = new ContentSecurityPolicy();
87
-		$this->server->httpResponse->addHeader('Content-Security-Policy', $csp->buildPolicy());
88
-		$this->sendResponse();
89
-	}
71
+    /**
72
+     * @param \Exception $ex
73
+     */
74
+    public function logException(\Exception $ex) {
75
+        if ($ex instanceof Exception) {
76
+            $httpCode = $ex->getHTTPCode();
77
+            $headers = $ex->getHTTPHeaders($this->server);
78
+        } else {
79
+            $httpCode = 500;
80
+            $headers = [];
81
+        }
82
+        $this->server->httpResponse->addHeaders($headers);
83
+        $this->server->httpResponse->setStatus($httpCode);
84
+        $body = $this->generateBody($httpCode);
85
+        $this->server->httpResponse->setBody($body);
86
+        $csp = new ContentSecurityPolicy();
87
+        $this->server->httpResponse->addHeader('Content-Security-Policy', $csp->buildPolicy());
88
+        $this->sendResponse();
89
+    }
90 90
 
91
-	/**
92
-	 * @codeCoverageIgnore
93
-	 * @return bool|string
94
-	 */
95
-	public function generateBody(int $httpCode) {
96
-		$request = \OC::$server->getRequest();
91
+    /**
92
+     * @codeCoverageIgnore
93
+     * @return bool|string
94
+     */
95
+    public function generateBody(int $httpCode) {
96
+        $request = \OC::$server->getRequest();
97 97
 
98
-		$templateName = 'exception';
99
-		if($httpCode === 403 || $httpCode === 404) {
100
-			$templateName = (string)$httpCode;
101
-		}
98
+        $templateName = 'exception';
99
+        if($httpCode === 403 || $httpCode === 404) {
100
+            $templateName = (string)$httpCode;
101
+        }
102 102
 
103
-		$content = new OC_Template('core', $templateName, 'guest');
104
-		$content->assign('title', $this->server->httpResponse->getStatusText());
105
-		$content->assign('remoteAddr', $request->getRemoteAddress());
106
-		$content->assign('requestID', $request->getId());
107
-		return $content->fetchPage();
108
-	}
103
+        $content = new OC_Template('core', $templateName, 'guest');
104
+        $content->assign('title', $this->server->httpResponse->getStatusText());
105
+        $content->assign('remoteAddr', $request->getRemoteAddress());
106
+        $content->assign('requestID', $request->getId());
107
+        return $content->fetchPage();
108
+    }
109 109
 
110
-	/**
111
-	 * @codeCoverageIgnore
112
-	 */
113
-	public function sendResponse() {
114
-		$this->server->sapi->sendResponse($this->server->httpResponse);
115
-		exit();
116
-	}
110
+    /**
111
+     * @codeCoverageIgnore
112
+     */
113
+    public function sendResponse() {
114
+        $this->server->sapi->sendResponse($this->server->httpResponse);
115
+        exit();
116
+    }
117 117
 }
Please login to merge, or discard this patch.