Completed
Pull Request — master (#3590)
by Individual IT
11:38
created
apps/files_external/lib/Controller/UserStoragesController.php 1 patch
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -43,185 +43,185 @@
 block discarded – undo
43 43
  * User storages controller
44 44
  */
45 45
 class UserStoragesController extends StoragesController {
46
-	/**
47
-	 * @var IUserSession
48
-	 */
49
-	private $userSession;
50
-
51
-	/**
52
-	 * Creates a new user storages controller.
53
-	 *
54
-	 * @param string $AppName application name
55
-	 * @param IRequest $request request object
56
-	 * @param IL10N $l10n l10n service
57
-	 * @param UserStoragesService $userStoragesService storage service
58
-	 * @param IUserSession $userSession
59
-	 * @param ILogger $logger
60
-	 */
61
-	public function __construct(
62
-		$AppName,
63
-		IRequest $request,
64
-		IL10N $l10n,
65
-		UserStoragesService $userStoragesService,
66
-		IUserSession $userSession,
67
-		ILogger $logger
68
-	) {
69
-		parent::__construct(
70
-			$AppName,
71
-			$request,
72
-			$l10n,
73
-			$userStoragesService,
74
-			$logger
75
-		);
76
-		$this->userSession = $userSession;
77
-	}
78
-
79
-	protected function manipulateStorageConfig(StorageConfig $storage) {
80
-		/** @var AuthMechanism */
81
-		$authMechanism = $storage->getAuthMechanism();
82
-		$authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
83
-		/** @var Backend */
84
-		$backend = $storage->getBackend();
85
-		$backend->manipulateStorageConfig($storage, $this->userSession->getUser());
86
-	}
87
-
88
-	/**
89
-	 * Get all storage entries
90
-	 *
91
-	 * @NoAdminRequired
92
-	 *
93
-	 * @return DataResponse
94
-	 */
95
-	public function index() {
96
-		return parent::index();
97
-	}
98
-
99
-	/**
100
-	 * Return storage
101
-	 *
102
-	 * @NoAdminRequired
103
-	 *
104
-	 * {@inheritdoc}
105
-	 */
106
-	public function show($id, $testOnly = true) {
107
-		return parent::show($id, $testOnly);
108
-	}
109
-
110
-	/**
111
-	 * Create an external storage entry.
112
-	 *
113
-	 * @param string $mountPoint storage mount point
114
-	 * @param string $backend backend identifier
115
-	 * @param string $authMechanism authentication mechanism identifier
116
-	 * @param array $backendOptions backend-specific options
117
-	 * @param array $mountOptions backend-specific mount options
118
-	 *
119
-	 * @return DataResponse
120
-	 *
121
-	 * @NoAdminRequired
122
-	 */
123
-	public function create(
124
-		$mountPoint,
125
-		$backend,
126
-		$authMechanism,
127
-		$backendOptions,
128
-		$mountOptions
129
-	) {
130
-		$newStorage = $this->createStorage(
131
-			$mountPoint,
132
-			$backend,
133
-			$authMechanism,
134
-			$backendOptions,
135
-			$mountOptions
136
-		);
137
-		if ($newStorage instanceOf DataResponse) {
138
-			return $newStorage;
139
-		}
140
-
141
-		$response = $this->validate($newStorage);
142
-		if (!empty($response)) {
143
-			return $response;
144
-		}
145
-
146
-		$newStorage = $this->service->addStorage($newStorage);
147
-		$this->updateStorageStatus($newStorage);
148
-
149
-		return new DataResponse(
150
-			$newStorage,
151
-			Http::STATUS_CREATED
152
-		);
153
-	}
154
-
155
-	/**
156
-	 * Update an external storage entry.
157
-	 *
158
-	 * @param int $id storage id
159
-	 * @param string $mountPoint storage mount point
160
-	 * @param string $backend backend identifier
161
-	 * @param string $authMechanism authentication mechanism identifier
162
-	 * @param array $backendOptions backend-specific options
163
-	 * @param array $mountOptions backend-specific mount options
164
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
165
-	 *
166
-	 * @return DataResponse
167
-	 *
168
-	 * @NoAdminRequired
169
-	 */
170
-	public function update(
171
-		$id,
172
-		$mountPoint,
173
-		$backend,
174
-		$authMechanism,
175
-		$backendOptions,
176
-		$mountOptions,
177
-		$testOnly = true
178
-	) {
179
-		$storage = $this->createStorage(
180
-			$mountPoint,
181
-			$backend,
182
-			$authMechanism,
183
-			$backendOptions,
184
-			$mountOptions
185
-		);
186
-		if ($storage instanceOf DataResponse) {
187
-			return $storage;
188
-		}
189
-		$storage->setId($id);
190
-
191
-		$response = $this->validate($storage);
192
-		if (!empty($response)) {
193
-			return $response;
194
-		}
195
-
196
-		try {
197
-			$storage = $this->service->updateStorage($storage);
198
-		} catch (NotFoundException $e) {
199
-			return new DataResponse(
200
-				[
201
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
202
-				],
203
-				Http::STATUS_NOT_FOUND
204
-			);
205
-		}
206
-
207
-		$this->updateStorageStatus($storage, $testOnly);
208
-
209
-		return new DataResponse(
210
-			$storage,
211
-			Http::STATUS_OK
212
-		);
213
-
214
-	}
215
-
216
-	/**
217
-	 * Delete storage
218
-	 *
219
-	 * @NoAdminRequired
220
-	 *
221
-	 * {@inheritdoc}
222
-	 */
223
-	public function destroy($id) {
224
-		return parent::destroy($id);
225
-	}
46
+    /**
47
+     * @var IUserSession
48
+     */
49
+    private $userSession;
50
+
51
+    /**
52
+     * Creates a new user storages controller.
53
+     *
54
+     * @param string $AppName application name
55
+     * @param IRequest $request request object
56
+     * @param IL10N $l10n l10n service
57
+     * @param UserStoragesService $userStoragesService storage service
58
+     * @param IUserSession $userSession
59
+     * @param ILogger $logger
60
+     */
61
+    public function __construct(
62
+        $AppName,
63
+        IRequest $request,
64
+        IL10N $l10n,
65
+        UserStoragesService $userStoragesService,
66
+        IUserSession $userSession,
67
+        ILogger $logger
68
+    ) {
69
+        parent::__construct(
70
+            $AppName,
71
+            $request,
72
+            $l10n,
73
+            $userStoragesService,
74
+            $logger
75
+        );
76
+        $this->userSession = $userSession;
77
+    }
78
+
79
+    protected function manipulateStorageConfig(StorageConfig $storage) {
80
+        /** @var AuthMechanism */
81
+        $authMechanism = $storage->getAuthMechanism();
82
+        $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
83
+        /** @var Backend */
84
+        $backend = $storage->getBackend();
85
+        $backend->manipulateStorageConfig($storage, $this->userSession->getUser());
86
+    }
87
+
88
+    /**
89
+     * Get all storage entries
90
+     *
91
+     * @NoAdminRequired
92
+     *
93
+     * @return DataResponse
94
+     */
95
+    public function index() {
96
+        return parent::index();
97
+    }
98
+
99
+    /**
100
+     * Return storage
101
+     *
102
+     * @NoAdminRequired
103
+     *
104
+     * {@inheritdoc}
105
+     */
106
+    public function show($id, $testOnly = true) {
107
+        return parent::show($id, $testOnly);
108
+    }
109
+
110
+    /**
111
+     * Create an external storage entry.
112
+     *
113
+     * @param string $mountPoint storage mount point
114
+     * @param string $backend backend identifier
115
+     * @param string $authMechanism authentication mechanism identifier
116
+     * @param array $backendOptions backend-specific options
117
+     * @param array $mountOptions backend-specific mount options
118
+     *
119
+     * @return DataResponse
120
+     *
121
+     * @NoAdminRequired
122
+     */
123
+    public function create(
124
+        $mountPoint,
125
+        $backend,
126
+        $authMechanism,
127
+        $backendOptions,
128
+        $mountOptions
129
+    ) {
130
+        $newStorage = $this->createStorage(
131
+            $mountPoint,
132
+            $backend,
133
+            $authMechanism,
134
+            $backendOptions,
135
+            $mountOptions
136
+        );
137
+        if ($newStorage instanceOf DataResponse) {
138
+            return $newStorage;
139
+        }
140
+
141
+        $response = $this->validate($newStorage);
142
+        if (!empty($response)) {
143
+            return $response;
144
+        }
145
+
146
+        $newStorage = $this->service->addStorage($newStorage);
147
+        $this->updateStorageStatus($newStorage);
148
+
149
+        return new DataResponse(
150
+            $newStorage,
151
+            Http::STATUS_CREATED
152
+        );
153
+    }
154
+
155
+    /**
156
+     * Update an external storage entry.
157
+     *
158
+     * @param int $id storage id
159
+     * @param string $mountPoint storage mount point
160
+     * @param string $backend backend identifier
161
+     * @param string $authMechanism authentication mechanism identifier
162
+     * @param array $backendOptions backend-specific options
163
+     * @param array $mountOptions backend-specific mount options
164
+     * @param bool $testOnly whether to storage should only test the connection or do more things
165
+     *
166
+     * @return DataResponse
167
+     *
168
+     * @NoAdminRequired
169
+     */
170
+    public function update(
171
+        $id,
172
+        $mountPoint,
173
+        $backend,
174
+        $authMechanism,
175
+        $backendOptions,
176
+        $mountOptions,
177
+        $testOnly = true
178
+    ) {
179
+        $storage = $this->createStorage(
180
+            $mountPoint,
181
+            $backend,
182
+            $authMechanism,
183
+            $backendOptions,
184
+            $mountOptions
185
+        );
186
+        if ($storage instanceOf DataResponse) {
187
+            return $storage;
188
+        }
189
+        $storage->setId($id);
190
+
191
+        $response = $this->validate($storage);
192
+        if (!empty($response)) {
193
+            return $response;
194
+        }
195
+
196
+        try {
197
+            $storage = $this->service->updateStorage($storage);
198
+        } catch (NotFoundException $e) {
199
+            return new DataResponse(
200
+                [
201
+                    'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
202
+                ],
203
+                Http::STATUS_NOT_FOUND
204
+            );
205
+        }
206
+
207
+        $this->updateStorageStatus($storage, $testOnly);
208
+
209
+        return new DataResponse(
210
+            $storage,
211
+            Http::STATUS_OK
212
+        );
213
+
214
+    }
215
+
216
+    /**
217
+     * Delete storage
218
+     *
219
+     * @NoAdminRequired
220
+     *
221
+     * {@inheritdoc}
222
+     */
223
+    public function destroy($id) {
224
+        return parent::destroy($id);
225
+    }
226 226
 
227 227
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/GlobalStoragesController.php 1 patch
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -39,151 +39,151 @@
 block discarded – undo
39 39
  * Global storages controller
40 40
  */
41 41
 class GlobalStoragesController extends StoragesController {
42
-	/**
43
-	 * Creates a new global storages controller.
44
-	 *
45
-	 * @param string $AppName application name
46
-	 * @param IRequest $request request object
47
-	 * @param IL10N $l10n l10n service
48
-	 * @param GlobalStoragesService $globalStoragesService storage service
49
-	 * @param ILogger $logger
50
-	 */
51
-	public function __construct(
52
-		$AppName,
53
-		IRequest $request,
54
-		IL10N $l10n,
55
-		GlobalStoragesService $globalStoragesService,
56
-		ILogger $logger
57
-	) {
58
-		parent::__construct(
59
-			$AppName,
60
-			$request,
61
-			$l10n,
62
-			$globalStoragesService,
63
-			$logger
64
-		);
65
-	}
66
-
67
-	/**
68
-	 * Create an external storage entry.
69
-	 *
70
-	 * @param string $mountPoint storage mount point
71
-	 * @param string $backend backend identifier
72
-	 * @param string $authMechanism authentication mechanism identifier
73
-	 * @param array $backendOptions backend-specific options
74
-	 * @param array $mountOptions mount-specific options
75
-	 * @param array $applicableUsers users for which to mount the storage
76
-	 * @param array $applicableGroups groups for which to mount the storage
77
-	 * @param int $priority priority
78
-	 *
79
-	 * @return DataResponse
80
-	 */
81
-	public function create(
82
-		$mountPoint,
83
-		$backend,
84
-		$authMechanism,
85
-		$backendOptions,
86
-		$mountOptions,
87
-		$applicableUsers,
88
-		$applicableGroups,
89
-		$priority
90
-	) {
91
-		$newStorage = $this->createStorage(
92
-			$mountPoint,
93
-			$backend,
94
-			$authMechanism,
95
-			$backendOptions,
96
-			$mountOptions,
97
-			$applicableUsers,
98
-			$applicableGroups,
99
-			$priority
100
-		);
101
-		if ($newStorage instanceof DataResponse) {
102
-			return $newStorage;
103
-		}
104
-
105
-		$response = $this->validate($newStorage);
106
-		if (!empty($response)) {
107
-			return $response;
108
-		}
109
-
110
-		$newStorage = $this->service->addStorage($newStorage);
111
-
112
-		$this->updateStorageStatus($newStorage);
113
-
114
-		return new DataResponse(
115
-			$newStorage,
116
-			Http::STATUS_CREATED
117
-		);
118
-	}
119
-
120
-	/**
121
-	 * Update an external storage entry.
122
-	 *
123
-	 * @param int $id storage id
124
-	 * @param string $mountPoint storage mount point
125
-	 * @param string $backend backend identifier
126
-	 * @param string $authMechanism authentication mechansim identifier
127
-	 * @param array $backendOptions backend-specific options
128
-	 * @param array $mountOptions mount-specific options
129
-	 * @param array $applicableUsers users for which to mount the storage
130
-	 * @param array $applicableGroups groups for which to mount the storage
131
-	 * @param int $priority priority
132
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
133
-	 *
134
-	 * @return DataResponse
135
-	 */
136
-	public function update(
137
-		$id,
138
-		$mountPoint,
139
-		$backend,
140
-		$authMechanism,
141
-		$backendOptions,
142
-		$mountOptions,
143
-		$applicableUsers,
144
-		$applicableGroups,
145
-		$priority,
146
-		$testOnly = true
147
-	) {
148
-		$storage = $this->createStorage(
149
-			$mountPoint,
150
-			$backend,
151
-			$authMechanism,
152
-			$backendOptions,
153
-			$mountOptions,
154
-			$applicableUsers,
155
-			$applicableGroups,
156
-			$priority
157
-		);
158
-		if ($storage instanceof DataResponse) {
159
-			return $storage;
160
-		}
161
-		$storage->setId($id);
162
-
163
-		$response = $this->validate($storage);
164
-		if (!empty($response)) {
165
-			return $response;
166
-		}
167
-
168
-		try {
169
-			$storage = $this->service->updateStorage($storage);
170
-		} catch (NotFoundException $e) {
171
-			return new DataResponse(
172
-				[
173
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
174
-				],
175
-				Http::STATUS_NOT_FOUND
176
-			);
177
-		}
178
-
179
-		$this->updateStorageStatus($storage, $testOnly);
180
-
181
-		return new DataResponse(
182
-			$storage,
183
-			Http::STATUS_OK
184
-		);
185
-
186
-	}
42
+    /**
43
+     * Creates a new global storages controller.
44
+     *
45
+     * @param string $AppName application name
46
+     * @param IRequest $request request object
47
+     * @param IL10N $l10n l10n service
48
+     * @param GlobalStoragesService $globalStoragesService storage service
49
+     * @param ILogger $logger
50
+     */
51
+    public function __construct(
52
+        $AppName,
53
+        IRequest $request,
54
+        IL10N $l10n,
55
+        GlobalStoragesService $globalStoragesService,
56
+        ILogger $logger
57
+    ) {
58
+        parent::__construct(
59
+            $AppName,
60
+            $request,
61
+            $l10n,
62
+            $globalStoragesService,
63
+            $logger
64
+        );
65
+    }
66
+
67
+    /**
68
+     * Create an external storage entry.
69
+     *
70
+     * @param string $mountPoint storage mount point
71
+     * @param string $backend backend identifier
72
+     * @param string $authMechanism authentication mechanism identifier
73
+     * @param array $backendOptions backend-specific options
74
+     * @param array $mountOptions mount-specific options
75
+     * @param array $applicableUsers users for which to mount the storage
76
+     * @param array $applicableGroups groups for which to mount the storage
77
+     * @param int $priority priority
78
+     *
79
+     * @return DataResponse
80
+     */
81
+    public function create(
82
+        $mountPoint,
83
+        $backend,
84
+        $authMechanism,
85
+        $backendOptions,
86
+        $mountOptions,
87
+        $applicableUsers,
88
+        $applicableGroups,
89
+        $priority
90
+    ) {
91
+        $newStorage = $this->createStorage(
92
+            $mountPoint,
93
+            $backend,
94
+            $authMechanism,
95
+            $backendOptions,
96
+            $mountOptions,
97
+            $applicableUsers,
98
+            $applicableGroups,
99
+            $priority
100
+        );
101
+        if ($newStorage instanceof DataResponse) {
102
+            return $newStorage;
103
+        }
104
+
105
+        $response = $this->validate($newStorage);
106
+        if (!empty($response)) {
107
+            return $response;
108
+        }
109
+
110
+        $newStorage = $this->service->addStorage($newStorage);
111
+
112
+        $this->updateStorageStatus($newStorage);
113
+
114
+        return new DataResponse(
115
+            $newStorage,
116
+            Http::STATUS_CREATED
117
+        );
118
+    }
119
+
120
+    /**
121
+     * Update an external storage entry.
122
+     *
123
+     * @param int $id storage id
124
+     * @param string $mountPoint storage mount point
125
+     * @param string $backend backend identifier
126
+     * @param string $authMechanism authentication mechansim identifier
127
+     * @param array $backendOptions backend-specific options
128
+     * @param array $mountOptions mount-specific options
129
+     * @param array $applicableUsers users for which to mount the storage
130
+     * @param array $applicableGroups groups for which to mount the storage
131
+     * @param int $priority priority
132
+     * @param bool $testOnly whether to storage should only test the connection or do more things
133
+     *
134
+     * @return DataResponse
135
+     */
136
+    public function update(
137
+        $id,
138
+        $mountPoint,
139
+        $backend,
140
+        $authMechanism,
141
+        $backendOptions,
142
+        $mountOptions,
143
+        $applicableUsers,
144
+        $applicableGroups,
145
+        $priority,
146
+        $testOnly = true
147
+    ) {
148
+        $storage = $this->createStorage(
149
+            $mountPoint,
150
+            $backend,
151
+            $authMechanism,
152
+            $backendOptions,
153
+            $mountOptions,
154
+            $applicableUsers,
155
+            $applicableGroups,
156
+            $priority
157
+        );
158
+        if ($storage instanceof DataResponse) {
159
+            return $storage;
160
+        }
161
+        $storage->setId($id);
162
+
163
+        $response = $this->validate($storage);
164
+        if (!empty($response)) {
165
+            return $response;
166
+        }
167
+
168
+        try {
169
+            $storage = $this->service->updateStorage($storage);
170
+        } catch (NotFoundException $e) {
171
+            return new DataResponse(
172
+                [
173
+                    'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
174
+                ],
175
+                Http::STATUS_NOT_FOUND
176
+            );
177
+        }
178
+
179
+        $this->updateStorageStatus($storage, $testOnly);
180
+
181
+        return new DataResponse(
182
+            $storage,
183
+            Http::STATUS_OK
184
+        );
185
+
186
+    }
187 187
 
188 188
 
189 189
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/StoragesController.php 1 patch
Indentation   +272 added lines, -272 removed lines patch added patch discarded remove patch
@@ -47,298 +47,298 @@
 block discarded – undo
47 47
  */
48 48
 abstract class StoragesController extends Controller {
49 49
 
50
-	/**
51
-	 * L10N service
52
-	 *
53
-	 * @var IL10N
54
-	 */
55
-	protected $l10n;
50
+    /**
51
+     * L10N service
52
+     *
53
+     * @var IL10N
54
+     */
55
+    protected $l10n;
56 56
 
57
-	/**
58
-	 * Storages service
59
-	 *
60
-	 * @var StoragesService
61
-	 */
62
-	protected $service;
57
+    /**
58
+     * Storages service
59
+     *
60
+     * @var StoragesService
61
+     */
62
+    protected $service;
63 63
 
64
-	/**
65
-	 * @var ILogger
66
-	 */
67
-	protected $logger;
64
+    /**
65
+     * @var ILogger
66
+     */
67
+    protected $logger;
68 68
 
69
-	/**
70
-	 * Creates a new storages controller.
71
-	 *
72
-	 * @param string $AppName application name
73
-	 * @param IRequest $request request object
74
-	 * @param IL10N $l10n l10n service
75
-	 * @param StoragesService $storagesService storage service
76
-	 * @param ILogger $logger
77
-	 */
78
-	public function __construct(
79
-		$AppName,
80
-		IRequest $request,
81
-		IL10N $l10n,
82
-		StoragesService $storagesService,
83
-		ILogger $logger
84
-	) {
85
-		parent::__construct($AppName, $request);
86
-		$this->l10n = $l10n;
87
-		$this->service = $storagesService;
88
-		$this->logger = $logger;
89
-	}
69
+    /**
70
+     * Creates a new storages controller.
71
+     *
72
+     * @param string $AppName application name
73
+     * @param IRequest $request request object
74
+     * @param IL10N $l10n l10n service
75
+     * @param StoragesService $storagesService storage service
76
+     * @param ILogger $logger
77
+     */
78
+    public function __construct(
79
+        $AppName,
80
+        IRequest $request,
81
+        IL10N $l10n,
82
+        StoragesService $storagesService,
83
+        ILogger $logger
84
+    ) {
85
+        parent::__construct($AppName, $request);
86
+        $this->l10n = $l10n;
87
+        $this->service = $storagesService;
88
+        $this->logger = $logger;
89
+    }
90 90
 
91
-	/**
92
-	 * Create a storage from its parameters
93
-	 *
94
-	 * @param string $mountPoint storage mount point
95
-	 * @param string $backend backend identifier
96
-	 * @param string $authMechanism authentication mechanism identifier
97
-	 * @param array $backendOptions backend-specific options
98
-	 * @param array|null $mountOptions mount-specific options
99
-	 * @param array|null $applicableUsers users for which to mount the storage
100
-	 * @param array|null $applicableGroups groups for which to mount the storage
101
-	 * @param int|null $priority priority
102
-	 *
103
-	 * @return StorageConfig|DataResponse
104
-	 */
105
-	protected function createStorage(
106
-		$mountPoint,
107
-		$backend,
108
-		$authMechanism,
109
-		$backendOptions,
110
-		$mountOptions = null,
111
-		$applicableUsers = null,
112
-		$applicableGroups = null,
113
-		$priority = null
114
-	) {
115
-		try {
116
-			return $this->service->createStorage(
117
-				$mountPoint,
118
-				$backend,
119
-				$authMechanism,
120
-				$backendOptions,
121
-				$mountOptions,
122
-				$applicableUsers,
123
-				$applicableGroups,
124
-				$priority
125
-			);
126
-		} catch (\InvalidArgumentException $e) {
127
-			$this->logger->logException($e);
128
-			return new DataResponse(
129
-				[
130
-					'message' => (string)$this->l10n->t('Invalid backend or authentication mechanism class')
131
-				],
132
-				Http::STATUS_UNPROCESSABLE_ENTITY
133
-			);
134
-		}
135
-	}
91
+    /**
92
+     * Create a storage from its parameters
93
+     *
94
+     * @param string $mountPoint storage mount point
95
+     * @param string $backend backend identifier
96
+     * @param string $authMechanism authentication mechanism identifier
97
+     * @param array $backendOptions backend-specific options
98
+     * @param array|null $mountOptions mount-specific options
99
+     * @param array|null $applicableUsers users for which to mount the storage
100
+     * @param array|null $applicableGroups groups for which to mount the storage
101
+     * @param int|null $priority priority
102
+     *
103
+     * @return StorageConfig|DataResponse
104
+     */
105
+    protected function createStorage(
106
+        $mountPoint,
107
+        $backend,
108
+        $authMechanism,
109
+        $backendOptions,
110
+        $mountOptions = null,
111
+        $applicableUsers = null,
112
+        $applicableGroups = null,
113
+        $priority = null
114
+    ) {
115
+        try {
116
+            return $this->service->createStorage(
117
+                $mountPoint,
118
+                $backend,
119
+                $authMechanism,
120
+                $backendOptions,
121
+                $mountOptions,
122
+                $applicableUsers,
123
+                $applicableGroups,
124
+                $priority
125
+            );
126
+        } catch (\InvalidArgumentException $e) {
127
+            $this->logger->logException($e);
128
+            return new DataResponse(
129
+                [
130
+                    'message' => (string)$this->l10n->t('Invalid backend or authentication mechanism class')
131
+                ],
132
+                Http::STATUS_UNPROCESSABLE_ENTITY
133
+            );
134
+        }
135
+    }
136 136
 
137
-	/**
138
-	 * Validate storage config
139
-	 *
140
-	 * @param StorageConfig $storage storage config
141
-	 *1
142
-	 * @return DataResponse|null returns response in case of validation error
143
-	 */
144
-	protected function validate(StorageConfig $storage) {
145
-		$mountPoint = $storage->getMountPoint();
146
-		if ($mountPoint === '' || $mountPoint === '/') {
147
-			return new DataResponse(
148
-				array(
149
-					'message' => (string)$this->l10n->t('Invalid mount point')
150
-				),
151
-				Http::STATUS_UNPROCESSABLE_ENTITY
152
-			);
153
-		}
137
+    /**
138
+     * Validate storage config
139
+     *
140
+     * @param StorageConfig $storage storage config
141
+     *1
142
+     * @return DataResponse|null returns response in case of validation error
143
+     */
144
+    protected function validate(StorageConfig $storage) {
145
+        $mountPoint = $storage->getMountPoint();
146
+        if ($mountPoint === '' || $mountPoint === '/') {
147
+            return new DataResponse(
148
+                array(
149
+                    'message' => (string)$this->l10n->t('Invalid mount point')
150
+                ),
151
+                Http::STATUS_UNPROCESSABLE_ENTITY
152
+            );
153
+        }
154 154
 
155
-		if ($storage->getBackendOption('objectstore')) {
156
-			// objectstore must not be sent from client side
157
-			return new DataResponse(
158
-				array(
159
-					'message' => (string)$this->l10n->t('Objectstore forbidden')
160
-				),
161
-				Http::STATUS_UNPROCESSABLE_ENTITY
162
-			);
163
-		}
155
+        if ($storage->getBackendOption('objectstore')) {
156
+            // objectstore must not be sent from client side
157
+            return new DataResponse(
158
+                array(
159
+                    'message' => (string)$this->l10n->t('Objectstore forbidden')
160
+                ),
161
+                Http::STATUS_UNPROCESSABLE_ENTITY
162
+            );
163
+        }
164 164
 
165
-		/** @var Backend */
166
-		$backend = $storage->getBackend();
167
-		/** @var AuthMechanism */
168
-		$authMechanism = $storage->getAuthMechanism();
169
-		if ($backend->checkDependencies()) {
170
-			// invalid backend
171
-			return new DataResponse(
172
-				array(
173
-					'message' => (string)$this->l10n->t('Invalid storage backend "%s"', [
174
-						$backend->getIdentifier()
175
-					])
176
-				),
177
-				Http::STATUS_UNPROCESSABLE_ENTITY
178
-			);
179
-		}
165
+        /** @var Backend */
166
+        $backend = $storage->getBackend();
167
+        /** @var AuthMechanism */
168
+        $authMechanism = $storage->getAuthMechanism();
169
+        if ($backend->checkDependencies()) {
170
+            // invalid backend
171
+            return new DataResponse(
172
+                array(
173
+                    'message' => (string)$this->l10n->t('Invalid storage backend "%s"', [
174
+                        $backend->getIdentifier()
175
+                    ])
176
+                ),
177
+                Http::STATUS_UNPROCESSABLE_ENTITY
178
+            );
179
+        }
180 180
 
181
-		if (!$backend->isVisibleFor($this->service->getVisibilityType())) {
182
-			// not permitted to use backend
183
-			return new DataResponse(
184
-				array(
185
-					'message' => (string)$this->l10n->t('Not permitted to use backend "%s"', [
186
-						$backend->getIdentifier()
187
-					])
188
-				),
189
-				Http::STATUS_UNPROCESSABLE_ENTITY
190
-			);
191
-		}
192
-		if (!$authMechanism->isVisibleFor($this->service->getVisibilityType())) {
193
-			// not permitted to use auth mechanism
194
-			return new DataResponse(
195
-				array(
196
-					'message' => (string)$this->l10n->t('Not permitted to use authentication mechanism "%s"', [
197
-						$authMechanism->getIdentifier()
198
-					])
199
-				),
200
-				Http::STATUS_UNPROCESSABLE_ENTITY
201
-			);
202
-		}
181
+        if (!$backend->isVisibleFor($this->service->getVisibilityType())) {
182
+            // not permitted to use backend
183
+            return new DataResponse(
184
+                array(
185
+                    'message' => (string)$this->l10n->t('Not permitted to use backend "%s"', [
186
+                        $backend->getIdentifier()
187
+                    ])
188
+                ),
189
+                Http::STATUS_UNPROCESSABLE_ENTITY
190
+            );
191
+        }
192
+        if (!$authMechanism->isVisibleFor($this->service->getVisibilityType())) {
193
+            // not permitted to use auth mechanism
194
+            return new DataResponse(
195
+                array(
196
+                    'message' => (string)$this->l10n->t('Not permitted to use authentication mechanism "%s"', [
197
+                        $authMechanism->getIdentifier()
198
+                    ])
199
+                ),
200
+                Http::STATUS_UNPROCESSABLE_ENTITY
201
+            );
202
+        }
203 203
 
204
-		if (!$backend->validateStorage($storage)) {
205
-			// unsatisfied parameters
206
-			return new DataResponse(
207
-				array(
208
-					'message' => (string)$this->l10n->t('Unsatisfied backend parameters')
209
-				),
210
-				Http::STATUS_UNPROCESSABLE_ENTITY
211
-			);
212
-		}
213
-		if (!$authMechanism->validateStorage($storage)) {
214
-			// unsatisfied parameters
215
-			return new DataResponse(
216
-				[
217
-					'message' => (string)$this->l10n->t('Unsatisfied authentication mechanism parameters')
218
-				],
219
-				Http::STATUS_UNPROCESSABLE_ENTITY
220
-			);
221
-		}
204
+        if (!$backend->validateStorage($storage)) {
205
+            // unsatisfied parameters
206
+            return new DataResponse(
207
+                array(
208
+                    'message' => (string)$this->l10n->t('Unsatisfied backend parameters')
209
+                ),
210
+                Http::STATUS_UNPROCESSABLE_ENTITY
211
+            );
212
+        }
213
+        if (!$authMechanism->validateStorage($storage)) {
214
+            // unsatisfied parameters
215
+            return new DataResponse(
216
+                [
217
+                    'message' => (string)$this->l10n->t('Unsatisfied authentication mechanism parameters')
218
+                ],
219
+                Http::STATUS_UNPROCESSABLE_ENTITY
220
+            );
221
+        }
222 222
 
223
-		return null;
224
-	}
223
+        return null;
224
+    }
225 225
 
226
-	protected function manipulateStorageConfig(StorageConfig $storage) {
227
-		/** @var AuthMechanism */
228
-		$authMechanism = $storage->getAuthMechanism();
229
-		$authMechanism->manipulateStorageConfig($storage);
230
-		/** @var Backend */
231
-		$backend = $storage->getBackend();
232
-		$backend->manipulateStorageConfig($storage);
233
-	}
226
+    protected function manipulateStorageConfig(StorageConfig $storage) {
227
+        /** @var AuthMechanism */
228
+        $authMechanism = $storage->getAuthMechanism();
229
+        $authMechanism->manipulateStorageConfig($storage);
230
+        /** @var Backend */
231
+        $backend = $storage->getBackend();
232
+        $backend->manipulateStorageConfig($storage);
233
+    }
234 234
 
235
-	/**
236
-	 * Check whether the given storage is available / valid.
237
-	 *
238
-	 * Note that this operation can be time consuming depending
239
-	 * on whether the remote storage is available or not.
240
-	 *
241
-	 * @param StorageConfig $storage storage configuration
242
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
243
-	 */
244
-	protected function updateStorageStatus(StorageConfig &$storage, $testOnly = true) {
245
-		try {
246
-			$this->manipulateStorageConfig($storage);
235
+    /**
236
+     * Check whether the given storage is available / valid.
237
+     *
238
+     * Note that this operation can be time consuming depending
239
+     * on whether the remote storage is available or not.
240
+     *
241
+     * @param StorageConfig $storage storage configuration
242
+     * @param bool $testOnly whether to storage should only test the connection or do more things
243
+     */
244
+    protected function updateStorageStatus(StorageConfig &$storage, $testOnly = true) {
245
+        try {
246
+            $this->manipulateStorageConfig($storage);
247 247
 
248
-			/** @var Backend */
249
-			$backend = $storage->getBackend();
250
-			// update status (can be time-consuming)
251
-			$storage->setStatus(
252
-				\OC_Mount_Config::getBackendStatus(
253
-					$backend->getStorageClass(),
254
-					$storage->getBackendOptions(),
255
-					false,
256
-					$testOnly
257
-				)
258
-			);
259
-		} catch (InsufficientDataForMeaningfulAnswerException $e) {
260
-			$status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE;
261
-			$storage->setStatus(
262
-				$status,
263
-				$this->l10n->t('Insufficient data: %s', [$e->getMessage()])
264
-			);
265
-		} catch (StorageNotAvailableException $e) {
266
-			$storage->setStatus(
267
-				$e->getCode(),
268
-				$this->l10n->t('%s', [$e->getMessage()])
269
-			);
270
-		} catch (\Exception $e) {
271
-			// FIXME: convert storage exceptions to StorageNotAvailableException
272
-			$storage->setStatus(
273
-				StorageNotAvailableException::STATUS_ERROR,
274
-				get_class($e).': '.$e->getMessage()
275
-			);
276
-		}
277
-	}
248
+            /** @var Backend */
249
+            $backend = $storage->getBackend();
250
+            // update status (can be time-consuming)
251
+            $storage->setStatus(
252
+                \OC_Mount_Config::getBackendStatus(
253
+                    $backend->getStorageClass(),
254
+                    $storage->getBackendOptions(),
255
+                    false,
256
+                    $testOnly
257
+                )
258
+            );
259
+        } catch (InsufficientDataForMeaningfulAnswerException $e) {
260
+            $status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE;
261
+            $storage->setStatus(
262
+                $status,
263
+                $this->l10n->t('Insufficient data: %s', [$e->getMessage()])
264
+            );
265
+        } catch (StorageNotAvailableException $e) {
266
+            $storage->setStatus(
267
+                $e->getCode(),
268
+                $this->l10n->t('%s', [$e->getMessage()])
269
+            );
270
+        } catch (\Exception $e) {
271
+            // FIXME: convert storage exceptions to StorageNotAvailableException
272
+            $storage->setStatus(
273
+                StorageNotAvailableException::STATUS_ERROR,
274
+                get_class($e).': '.$e->getMessage()
275
+            );
276
+        }
277
+    }
278 278
 
279
-	/**
280
-	 * Get all storage entries
281
-	 *
282
-	 * @return DataResponse
283
-	 */
284
-	public function index() {
285
-		$storages = $this->service->getStorages();
279
+    /**
280
+     * Get all storage entries
281
+     *
282
+     * @return DataResponse
283
+     */
284
+    public function index() {
285
+        $storages = $this->service->getStorages();
286 286
 
287
-		return new DataResponse(
288
-			$storages,
289
-			Http::STATUS_OK
290
-		);
291
-	}
287
+        return new DataResponse(
288
+            $storages,
289
+            Http::STATUS_OK
290
+        );
291
+    }
292 292
 
293
-	/**
294
-	 * Get an external storage entry.
295
-	 *
296
-	 * @param int $id storage id
297
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
298
-	 *
299
-	 * @return DataResponse
300
-	 */
301
-	public function show($id, $testOnly = true) {
302
-		try {
303
-			$storage = $this->service->getStorage($id);
293
+    /**
294
+     * Get an external storage entry.
295
+     *
296
+     * @param int $id storage id
297
+     * @param bool $testOnly whether to storage should only test the connection or do more things
298
+     *
299
+     * @return DataResponse
300
+     */
301
+    public function show($id, $testOnly = true) {
302
+        try {
303
+            $storage = $this->service->getStorage($id);
304 304
 
305
-			$this->updateStorageStatus($storage, $testOnly);
306
-		} catch (NotFoundException $e) {
307
-			return new DataResponse(
308
-				[
309
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
310
-				],
311
-				Http::STATUS_NOT_FOUND
312
-			);
313
-		}
305
+            $this->updateStorageStatus($storage, $testOnly);
306
+        } catch (NotFoundException $e) {
307
+            return new DataResponse(
308
+                [
309
+                    'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
310
+                ],
311
+                Http::STATUS_NOT_FOUND
312
+            );
313
+        }
314 314
 
315
-		return new DataResponse(
316
-			$storage,
317
-			Http::STATUS_OK
318
-		);
319
-	}
315
+        return new DataResponse(
316
+            $storage,
317
+            Http::STATUS_OK
318
+        );
319
+    }
320 320
 
321
-	/**
322
-	 * Deletes the storage with the given id.
323
-	 *
324
-	 * @param int $id storage id
325
-	 *
326
-	 * @return DataResponse
327
-	 */
328
-	public function destroy($id) {
329
-		try {
330
-			$this->service->removeStorage($id);
331
-		} catch (NotFoundException $e) {
332
-			return new DataResponse(
333
-				[
334
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
335
-				],
336
-				Http::STATUS_NOT_FOUND
337
-			);
338
-		}
321
+    /**
322
+     * Deletes the storage with the given id.
323
+     *
324
+     * @param int $id storage id
325
+     *
326
+     * @return DataResponse
327
+     */
328
+    public function destroy($id) {
329
+        try {
330
+            $this->service->removeStorage($id);
331
+        } catch (NotFoundException $e) {
332
+            return new DataResponse(
333
+                [
334
+                    'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
335
+                ],
336
+                Http::STATUS_NOT_FOUND
337
+            );
338
+        }
339 339
 
340
-		return new DataResponse([], Http::STATUS_NO_CONTENT);
341
-	}
340
+        return new DataResponse([], Http::STATUS_NO_CONTENT);
341
+    }
342 342
 
343 343
 }
344 344
 
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/UserGlobalStoragesController.php 1 patch
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -43,165 +43,165 @@
 block discarded – undo
43 43
  * User global storages controller
44 44
  */
45 45
 class UserGlobalStoragesController extends StoragesController {
46
-	/**
47
-	 * @var IUserSession
48
-	 */
49
-	private $userSession;
50
-
51
-	/**
52
-	 * Creates a new user global storages controller.
53
-	 *
54
-	 * @param string $AppName application name
55
-	 * @param IRequest $request request object
56
-	 * @param IL10N $l10n l10n service
57
-	 * @param UserGlobalStoragesService $userGlobalStoragesService storage service
58
-	 * @param IUserSession $userSession
59
-	 */
60
-	public function __construct(
61
-		$AppName,
62
-		IRequest $request,
63
-		IL10N $l10n,
64
-		UserGlobalStoragesService $userGlobalStoragesService,
65
-		IUserSession $userSession,
66
-		ILogger $logger
67
-	) {
68
-		parent::__construct(
69
-			$AppName,
70
-			$request,
71
-			$l10n,
72
-			$userGlobalStoragesService,
73
-			$logger
74
-		);
75
-		$this->userSession = $userSession;
76
-	}
77
-
78
-	/**
79
-	 * Get all storage entries
80
-	 *
81
-	 * @return DataResponse
82
-	 *
83
-	 * @NoAdminRequired
84
-	 */
85
-	public function index() {
86
-		$storages = $this->service->getUniqueStorages();
87
-
88
-		// remove configuration data, this must be kept private
89
-		foreach ($storages as $storage) {
90
-			$this->sanitizeStorage($storage);
91
-		}
92
-
93
-		return new DataResponse(
94
-			$storages,
95
-			Http::STATUS_OK
96
-		);
97
-	}
98
-
99
-	protected function manipulateStorageConfig(StorageConfig $storage) {
100
-		/** @var AuthMechanism */
101
-		$authMechanism = $storage->getAuthMechanism();
102
-		$authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
103
-		/** @var Backend */
104
-		$backend = $storage->getBackend();
105
-		$backend->manipulateStorageConfig($storage, $this->userSession->getUser());
106
-	}
107
-
108
-	/**
109
-	 * Get an external storage entry.
110
-	 *
111
-	 * @param int $id storage id
112
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
113
-	 * @return DataResponse
114
-	 *
115
-	 * @NoAdminRequired
116
-	 */
117
-	public function show($id, $testOnly = true) {
118
-		try {
119
-			$storage = $this->service->getStorage($id);
120
-
121
-			$this->updateStorageStatus($storage, $testOnly);
122
-		} catch (NotFoundException $e) {
123
-			return new DataResponse(
124
-				[
125
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
126
-				],
127
-				Http::STATUS_NOT_FOUND
128
-			);
129
-		}
130
-
131
-		$this->sanitizeStorage($storage);
132
-
133
-		return new DataResponse(
134
-			$storage,
135
-			Http::STATUS_OK
136
-		);
137
-	}
138
-
139
-	/**
140
-	 * Update an external storage entry.
141
-	 * Only allows setting user provided backend fields
142
-	 *
143
-	 * @param int $id storage id
144
-	 * @param array $backendOptions backend-specific options
145
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
146
-	 *
147
-	 * @return DataResponse
148
-	 *
149
-	 * @NoAdminRequired
150
-	 */
151
-	public function update(
152
-		$id,
153
-		$backendOptions,
154
-		$testOnly = true
155
-	) {
156
-		try {
157
-			$storage = $this->service->getStorage($id);
158
-			$authMechanism = $storage->getAuthMechanism();
159
-			if ($authMechanism instanceof IUserProvided) {
160
-				$authMechanism->saveBackendOptions($this->userSession->getUser(), $id, $backendOptions);
161
-				$authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
162
-			} else {
163
-				return new DataResponse(
164
-					[
165
-						'message' => (string)$this->l10n->t('Storage with id "%i" is not user editable', array($id))
166
-					],
167
-					Http::STATUS_FORBIDDEN
168
-				);
169
-			}
170
-		} catch (NotFoundException $e) {
171
-			return new DataResponse(
172
-				[
173
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
174
-				],
175
-				Http::STATUS_NOT_FOUND
176
-			);
177
-		}
178
-
179
-		$this->updateStorageStatus($storage, $testOnly);
180
-		$this->sanitizeStorage($storage);
181
-
182
-		return new DataResponse(
183
-			$storage,
184
-			Http::STATUS_OK
185
-		);
186
-
187
-	}
188
-
189
-	/**
190
-	 * Remove sensitive data from a StorageConfig before returning it to the user
191
-	 *
192
-	 * @param StorageConfig $storage
193
-	 */
194
-	protected function sanitizeStorage(StorageConfig $storage) {
195
-		$storage->setBackendOptions([]);
196
-		$storage->setMountOptions([]);
197
-
198
-		if ($storage->getAuthMechanism() instanceof IUserProvided) {
199
-			try {
200
-				$storage->getAuthMechanism()->manipulateStorageConfig($storage, $this->userSession->getUser());
201
-			} catch (InsufficientDataForMeaningfulAnswerException $e) {
202
-				// not configured yet
203
-			}
204
-		}
205
-	}
46
+    /**
47
+     * @var IUserSession
48
+     */
49
+    private $userSession;
50
+
51
+    /**
52
+     * Creates a new user global storages controller.
53
+     *
54
+     * @param string $AppName application name
55
+     * @param IRequest $request request object
56
+     * @param IL10N $l10n l10n service
57
+     * @param UserGlobalStoragesService $userGlobalStoragesService storage service
58
+     * @param IUserSession $userSession
59
+     */
60
+    public function __construct(
61
+        $AppName,
62
+        IRequest $request,
63
+        IL10N $l10n,
64
+        UserGlobalStoragesService $userGlobalStoragesService,
65
+        IUserSession $userSession,
66
+        ILogger $logger
67
+    ) {
68
+        parent::__construct(
69
+            $AppName,
70
+            $request,
71
+            $l10n,
72
+            $userGlobalStoragesService,
73
+            $logger
74
+        );
75
+        $this->userSession = $userSession;
76
+    }
77
+
78
+    /**
79
+     * Get all storage entries
80
+     *
81
+     * @return DataResponse
82
+     *
83
+     * @NoAdminRequired
84
+     */
85
+    public function index() {
86
+        $storages = $this->service->getUniqueStorages();
87
+
88
+        // remove configuration data, this must be kept private
89
+        foreach ($storages as $storage) {
90
+            $this->sanitizeStorage($storage);
91
+        }
92
+
93
+        return new DataResponse(
94
+            $storages,
95
+            Http::STATUS_OK
96
+        );
97
+    }
98
+
99
+    protected function manipulateStorageConfig(StorageConfig $storage) {
100
+        /** @var AuthMechanism */
101
+        $authMechanism = $storage->getAuthMechanism();
102
+        $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
103
+        /** @var Backend */
104
+        $backend = $storage->getBackend();
105
+        $backend->manipulateStorageConfig($storage, $this->userSession->getUser());
106
+    }
107
+
108
+    /**
109
+     * Get an external storage entry.
110
+     *
111
+     * @param int $id storage id
112
+     * @param bool $testOnly whether to storage should only test the connection or do more things
113
+     * @return DataResponse
114
+     *
115
+     * @NoAdminRequired
116
+     */
117
+    public function show($id, $testOnly = true) {
118
+        try {
119
+            $storage = $this->service->getStorage($id);
120
+
121
+            $this->updateStorageStatus($storage, $testOnly);
122
+        } catch (NotFoundException $e) {
123
+            return new DataResponse(
124
+                [
125
+                    'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
126
+                ],
127
+                Http::STATUS_NOT_FOUND
128
+            );
129
+        }
130
+
131
+        $this->sanitizeStorage($storage);
132
+
133
+        return new DataResponse(
134
+            $storage,
135
+            Http::STATUS_OK
136
+        );
137
+    }
138
+
139
+    /**
140
+     * Update an external storage entry.
141
+     * Only allows setting user provided backend fields
142
+     *
143
+     * @param int $id storage id
144
+     * @param array $backendOptions backend-specific options
145
+     * @param bool $testOnly whether to storage should only test the connection or do more things
146
+     *
147
+     * @return DataResponse
148
+     *
149
+     * @NoAdminRequired
150
+     */
151
+    public function update(
152
+        $id,
153
+        $backendOptions,
154
+        $testOnly = true
155
+    ) {
156
+        try {
157
+            $storage = $this->service->getStorage($id);
158
+            $authMechanism = $storage->getAuthMechanism();
159
+            if ($authMechanism instanceof IUserProvided) {
160
+                $authMechanism->saveBackendOptions($this->userSession->getUser(), $id, $backendOptions);
161
+                $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
162
+            } else {
163
+                return new DataResponse(
164
+                    [
165
+                        'message' => (string)$this->l10n->t('Storage with id "%i" is not user editable', array($id))
166
+                    ],
167
+                    Http::STATUS_FORBIDDEN
168
+                );
169
+            }
170
+        } catch (NotFoundException $e) {
171
+            return new DataResponse(
172
+                [
173
+                    'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
174
+                ],
175
+                Http::STATUS_NOT_FOUND
176
+            );
177
+        }
178
+
179
+        $this->updateStorageStatus($storage, $testOnly);
180
+        $this->sanitizeStorage($storage);
181
+
182
+        return new DataResponse(
183
+            $storage,
184
+            Http::STATUS_OK
185
+        );
186
+
187
+    }
188
+
189
+    /**
190
+     * Remove sensitive data from a StorageConfig before returning it to the user
191
+     *
192
+     * @param StorageConfig $storage
193
+     */
194
+    protected function sanitizeStorage(StorageConfig $storage) {
195
+        $storage->setBackendOptions([]);
196
+        $storage->setMountOptions([]);
197
+
198
+        if ($storage->getAuthMechanism() instanceof IUserProvided) {
199
+            try {
200
+                $storage->getAuthMechanism()->manipulateStorageConfig($storage, $this->userSession->getUser());
201
+            } catch (InsufficientDataForMeaningfulAnswerException $e) {
202
+                // not configured yet
203
+            }
204
+        }
205
+    }
206 206
 
207 207
 }
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
-	 * @return array
72
-	 */
73
-	private function generateSshKeys() {
74
-		$key = $this->rsaMechanism->createKey();
75
-		// Replace the placeholder label with a more meaningful one
76
-		$key['publicKey'] = str_replace('phpseclib-generated-key', gethostname(), $key['publickey']);
70
+    /**
71
+     * @return array
72
+     */
73
+    private function generateSshKeys() {
74
+        $key = $this->rsaMechanism->createKey();
75
+        // Replace the placeholder label with a more meaningful one
76
+        $key['publicKey'] = str_replace('phpseclib-generated-key', gethostname(), $key['publickey']);
77 77
 
78
-		return $key;
79
-	}
78
+        return $key;
79
+    }
80 80
 
81
-	/**
82
-	 * Generates an SSH public/private key pair.
83
-	 *
84
-	 * @NoAdminRequired
85
-	 */
86
-	public function getSshKeys() {
87
-		$key = $this->generateSshKeys();
88
-		return new JSONResponse(
89
-			array('data' => array(
90
-				'private_key' => $key['privatekey'],
91
-				'public_key' => $key['publickey']
92
-			),
93
-			'status' => 'success'
94
-		));
95
-	}
81
+    /**
82
+     * Generates an SSH public/private key pair.
83
+     *
84
+     * @NoAdminRequired
85
+     */
86
+    public function getSshKeys() {
87
+        $key = $this->generateSshKeys();
88
+        return new JSONResponse(
89
+            array('data' => array(
90
+                'private_key' => $key['privatekey'],
91
+                'public_key' => $key['publickey']
92
+            ),
93
+            'status' => 'success'
94
+        ));
95
+    }
96 96
 
97
-	/**
98
-	 * @NoAdminRequired
99
-	 *
100
-	 * @param string $uid
101
-	 * @param string $user
102
-	 * @param string $password
103
-	 * @return bool
104
-	 */
105
-	public function saveGlobalCredentials($uid, $user, $password) {
106
-		$currentUser = $this->userSession->getUser();
97
+    /**
98
+     * @NoAdminRequired
99
+     *
100
+     * @param string $uid
101
+     * @param string $user
102
+     * @param string $password
103
+     * @return bool
104
+     */
105
+    public function saveGlobalCredentials($uid, $user, $password) {
106
+        $currentUser = $this->userSession->getUser();
107 107
 
108
-		// Non-admins can only edit their own credentials
109
-		$allowedToEdit = (
110
-			$this->groupManager->isAdmin($currentUser->getUID()) || $currentUser->getUID() === $uid
111
-		) ? true : false;
108
+        // Non-admins can only edit their own credentials
109
+        $allowedToEdit = (
110
+            $this->groupManager->isAdmin($currentUser->getUID()) || $currentUser->getUID() === $uid
111
+        ) ? true : false;
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/AppInfo/Application.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -41,107 +41,107 @@
 block discarded – undo
41 41
  */
42 42
 class Application extends App implements IBackendProvider, IAuthMechanismProvider {
43 43
 
44
-	public function __construct(array $urlParams = array()) {
45
-		parent::__construct('files_external', $urlParams);
46
-
47
-		$container = $this->getContainer();
48
-
49
-		$container->registerService('OCP\Files\Config\IUserMountCache', function (IAppContainer $c) {
50
-			return $c->getServer()->query('UserMountCache');
51
-		});
52
-
53
-		$backendService = $container->query('OCA\\Files_External\\Service\\BackendService');
54
-		$backendService->registerBackendProvider($this);
55
-		$backendService->registerAuthMechanismProvider($this);
56
-
57
-		// force-load auth mechanisms since some will register hooks
58
-		// TODO: obsolete these and use the TokenProvider to get the user's password from the session
59
-		$this->getAuthMechanisms();
60
-
61
-		// app developers: do NOT depend on this! it will disappear with oC 9.0!
62
-		\OC::$server->getEventDispatcher()->dispatch(
63
-			'OCA\\Files_External::loadAdditionalBackends'
64
-		);
65
-	}
66
-
67
-	/**
68
-	 * Register settings templates
69
-	 */
70
-	public function registerSettings() {
71
-		$container = $this->getContainer();
72
-		$userSession = $container->getServer()->getUserSession();
73
-		if (!$userSession->isLoggedIn()) {
74
-			return;
75
-		}
76
-		$backendService = $container->query('OCA\\Files_External\\Service\\BackendService');
77
-
78
-		/** @var \OCA\Files_External\Service\UserGlobalStoragesService $userGlobalStoragesService */
79
-		$userGlobalStoragesService = $container->query('OCA\Files_External\Service\UserGlobalStoragesService');
80
-		if (count($userGlobalStoragesService->getStorages()) > 0 || $backendService->isUserMountingAllowed()) {
81
-			\OCP\App::registerPersonal('files_external', 'personal');
82
-		}
83
-	}
84
-
85
-	/**
86
-	 * @{inheritdoc}
87
-	 */
88
-	public function getBackends() {
89
-		$container = $this->getContainer();
90
-
91
-		$backends = [
92
-			$container->query('OCA\Files_External\Lib\Backend\Local'),
93
-			$container->query('OCA\Files_External\Lib\Backend\FTP'),
94
-			$container->query('OCA\Files_External\Lib\Backend\DAV'),
95
-			$container->query('OCA\Files_External\Lib\Backend\OwnCloud'),
96
-			$container->query('OCA\Files_External\Lib\Backend\SFTP'),
97
-			$container->query('OCA\Files_External\Lib\Backend\AmazonS3'),
98
-			$container->query('OCA\Files_External\Lib\Backend\Dropbox'),
99
-			$container->query('OCA\Files_External\Lib\Backend\Google'),
100
-			$container->query('OCA\Files_External\Lib\Backend\Swift'),
101
-			$container->query('OCA\Files_External\Lib\Backend\SFTP_Key'),
102
-			$container->query('OCA\Files_External\Lib\Backend\SMB'),
103
-			$container->query('OCA\Files_External\Lib\Backend\SMB_OC'),
104
-		];
105
-
106
-		return $backends;
107
-	}
108
-
109
-	/**
110
-	 * @{inheritdoc}
111
-	 */
112
-	public function getAuthMechanisms() {
113
-		$container = $this->getContainer();
114
-
115
-		return [
116
-			// AuthMechanism::SCHEME_NULL mechanism
117
-			$container->query('OCA\Files_External\Lib\Auth\NullMechanism'),
118
-
119
-			// AuthMechanism::SCHEME_BUILTIN mechanism
120
-			$container->query('OCA\Files_External\Lib\Auth\Builtin'),
121
-
122
-			// AuthMechanism::SCHEME_PASSWORD mechanisms
123
-			$container->query('OCA\Files_External\Lib\Auth\Password\Password'),
124
-			$container->query('OCA\Files_External\Lib\Auth\Password\SessionCredentials'),
125
-			$container->query('OCA\Files_External\Lib\Auth\Password\LoginCredentials'),
126
-			$container->query('OCA\Files_External\Lib\Auth\Password\UserProvided'),
127
-			$container->query('OCA\Files_External\Lib\Auth\Password\GlobalAuth'),
128
-
129
-			// AuthMechanism::SCHEME_OAUTH1 mechanisms
130
-			$container->query('OCA\Files_External\Lib\Auth\OAuth1\OAuth1'),
131
-
132
-			// AuthMechanism::SCHEME_OAUTH2 mechanisms
133
-			$container->query('OCA\Files_External\Lib\Auth\OAuth2\OAuth2'),
134
-
135
-			// AuthMechanism::SCHEME_PUBLICKEY mechanisms
136
-			$container->query('OCA\Files_External\Lib\Auth\PublicKey\RSA'),
137
-
138
-			// AuthMechanism::SCHEME_OPENSTACK mechanisms
139
-			$container->query('OCA\Files_External\Lib\Auth\OpenStack\OpenStack'),
140
-			$container->query('OCA\Files_External\Lib\Auth\OpenStack\Rackspace'),
141
-
142
-			// Specialized mechanisms
143
-			$container->query('OCA\Files_External\Lib\Auth\AmazonS3\AccessKey'),
144
-		];
145
-	}
44
+    public function __construct(array $urlParams = array()) {
45
+        parent::__construct('files_external', $urlParams);
46
+
47
+        $container = $this->getContainer();
48
+
49
+        $container->registerService('OCP\Files\Config\IUserMountCache', function (IAppContainer $c) {
50
+            return $c->getServer()->query('UserMountCache');
51
+        });
52
+
53
+        $backendService = $container->query('OCA\\Files_External\\Service\\BackendService');
54
+        $backendService->registerBackendProvider($this);
55
+        $backendService->registerAuthMechanismProvider($this);
56
+
57
+        // force-load auth mechanisms since some will register hooks
58
+        // TODO: obsolete these and use the TokenProvider to get the user's password from the session
59
+        $this->getAuthMechanisms();
60
+
61
+        // app developers: do NOT depend on this! it will disappear with oC 9.0!
62
+        \OC::$server->getEventDispatcher()->dispatch(
63
+            'OCA\\Files_External::loadAdditionalBackends'
64
+        );
65
+    }
66
+
67
+    /**
68
+     * Register settings templates
69
+     */
70
+    public function registerSettings() {
71
+        $container = $this->getContainer();
72
+        $userSession = $container->getServer()->getUserSession();
73
+        if (!$userSession->isLoggedIn()) {
74
+            return;
75
+        }
76
+        $backendService = $container->query('OCA\\Files_External\\Service\\BackendService');
77
+
78
+        /** @var \OCA\Files_External\Service\UserGlobalStoragesService $userGlobalStoragesService */
79
+        $userGlobalStoragesService = $container->query('OCA\Files_External\Service\UserGlobalStoragesService');
80
+        if (count($userGlobalStoragesService->getStorages()) > 0 || $backendService->isUserMountingAllowed()) {
81
+            \OCP\App::registerPersonal('files_external', 'personal');
82
+        }
83
+    }
84
+
85
+    /**
86
+     * @{inheritdoc}
87
+     */
88
+    public function getBackends() {
89
+        $container = $this->getContainer();
90
+
91
+        $backends = [
92
+            $container->query('OCA\Files_External\Lib\Backend\Local'),
93
+            $container->query('OCA\Files_External\Lib\Backend\FTP'),
94
+            $container->query('OCA\Files_External\Lib\Backend\DAV'),
95
+            $container->query('OCA\Files_External\Lib\Backend\OwnCloud'),
96
+            $container->query('OCA\Files_External\Lib\Backend\SFTP'),
97
+            $container->query('OCA\Files_External\Lib\Backend\AmazonS3'),
98
+            $container->query('OCA\Files_External\Lib\Backend\Dropbox'),
99
+            $container->query('OCA\Files_External\Lib\Backend\Google'),
100
+            $container->query('OCA\Files_External\Lib\Backend\Swift'),
101
+            $container->query('OCA\Files_External\Lib\Backend\SFTP_Key'),
102
+            $container->query('OCA\Files_External\Lib\Backend\SMB'),
103
+            $container->query('OCA\Files_External\Lib\Backend\SMB_OC'),
104
+        ];
105
+
106
+        return $backends;
107
+    }
108
+
109
+    /**
110
+     * @{inheritdoc}
111
+     */
112
+    public function getAuthMechanisms() {
113
+        $container = $this->getContainer();
114
+
115
+        return [
116
+            // AuthMechanism::SCHEME_NULL mechanism
117
+            $container->query('OCA\Files_External\Lib\Auth\NullMechanism'),
118
+
119
+            // AuthMechanism::SCHEME_BUILTIN mechanism
120
+            $container->query('OCA\Files_External\Lib\Auth\Builtin'),
121
+
122
+            // AuthMechanism::SCHEME_PASSWORD mechanisms
123
+            $container->query('OCA\Files_External\Lib\Auth\Password\Password'),
124
+            $container->query('OCA\Files_External\Lib\Auth\Password\SessionCredentials'),
125
+            $container->query('OCA\Files_External\Lib\Auth\Password\LoginCredentials'),
126
+            $container->query('OCA\Files_External\Lib\Auth\Password\UserProvided'),
127
+            $container->query('OCA\Files_External\Lib\Auth\Password\GlobalAuth'),
128
+
129
+            // AuthMechanism::SCHEME_OAUTH1 mechanisms
130
+            $container->query('OCA\Files_External\Lib\Auth\OAuth1\OAuth1'),
131
+
132
+            // AuthMechanism::SCHEME_OAUTH2 mechanisms
133
+            $container->query('OCA\Files_External\Lib\Auth\OAuth2\OAuth2'),
134
+
135
+            // AuthMechanism::SCHEME_PUBLICKEY mechanisms
136
+            $container->query('OCA\Files_External\Lib\Auth\PublicKey\RSA'),
137
+
138
+            // AuthMechanism::SCHEME_OPENSTACK mechanisms
139
+            $container->query('OCA\Files_External\Lib\Auth\OpenStack\OpenStack'),
140
+            $container->query('OCA\Files_External\Lib\Auth\OpenStack\Rackspace'),
141
+
142
+            // Specialized mechanisms
143
+            $container->query('OCA\Files_External\Lib\Auth\AmazonS3\AccessKey'),
144
+        ];
145
+    }
146 146
 
147 147
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Config/ConfigAdapter.php 1 patch
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -45,143 +45,143 @@
 block discarded – undo
45 45
  */
46 46
 class ConfigAdapter implements IMountProvider {
47 47
 
48
-	/** @var UserStoragesService */
49
-	private $userStoragesService;
50
-
51
-	/** @var UserGlobalStoragesService */
52
-	private $userGlobalStoragesService;
53
-	/** @var StorageMigrator  */
54
-	private $migrator;
55
-
56
-	/**
57
-	 * @param UserStoragesService $userStoragesService
58
-	 * @param UserGlobalStoragesService $userGlobalStoragesService
59
-	 * @param StorageMigrator $migrator
60
-	 */
61
-	public function __construct(
62
-		UserStoragesService $userStoragesService,
63
-		UserGlobalStoragesService $userGlobalStoragesService,
64
-		StorageMigrator $migrator
65
-	) {
66
-		$this->userStoragesService = $userStoragesService;
67
-		$this->userGlobalStoragesService = $userGlobalStoragesService;
68
-		$this->migrator = $migrator;
69
-	}
70
-
71
-	/**
72
-	 * Process storage ready for mounting
73
-	 *
74
-	 * @param StorageConfig $storage
75
-	 * @param IUser $user
76
-	 */
77
-	private function prepareStorageConfig(StorageConfig &$storage, IUser $user) {
78
-		foreach ($storage->getBackendOptions() as $option => $value) {
79
-			$storage->setBackendOption($option, \OC_Mount_Config::setUserVars(
80
-				$user->getUID(), $value
81
-			));
82
-		}
83
-
84
-		$objectStore = $storage->getBackendOption('objectstore');
85
-		if ($objectStore) {
86
-			$objectClass = $objectStore['class'];
87
-			if (!is_subclass_of($objectClass, '\OCP\Files\ObjectStore\IObjectStore')) {
88
-				throw new \InvalidArgumentException('Invalid object store');
89
-			}
90
-			$storage->setBackendOption('objectstore', new $objectClass($objectStore));
91
-		}
92
-
93
-		$storage->getAuthMechanism()->manipulateStorageConfig($storage, $user);
94
-		$storage->getBackend()->manipulateStorageConfig($storage, $user);
95
-	}
96
-
97
-	/**
98
-	 * Construct the storage implementation
99
-	 *
100
-	 * @param StorageConfig $storageConfig
101
-	 * @return Storage
102
-	 */
103
-	private function constructStorage(StorageConfig $storageConfig) {
104
-		$class = $storageConfig->getBackend()->getStorageClass();
105
-		$storage = new $class($storageConfig->getBackendOptions());
106
-
107
-		// auth mechanism should fire first
108
-		$storage = $storageConfig->getBackend()->wrapStorage($storage);
109
-		$storage = $storageConfig->getAuthMechanism()->wrapStorage($storage);
110
-
111
-		return $storage;
112
-	}
113
-
114
-	/**
115
-	 * Get all mountpoints applicable for the user
116
-	 *
117
-	 * @param \OCP\IUser $user
118
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
119
-	 * @return \OCP\Files\Mount\IMountPoint[]
120
-	 */
121
-	public function getMountsForUser(IUser $user, IStorageFactory $loader) {
122
-		$this->migrator->migrateUser($user);
123
-
124
-		$this->userStoragesService->setUser($user);
125
-		$this->userGlobalStoragesService->setUser($user);
126
-
127
-		$storageConfigs = $this->userGlobalStoragesService->getAllStoragesForUser();
128
-
129
-		$storages = array_map(function(StorageConfig $storageConfig) use ($user) {
130
-			try {
131
-				$this->prepareStorageConfig($storageConfig, $user);
132
-				return $this->constructStorage($storageConfig);
133
-			} catch (\Exception $e) {
134
-				// propagate exception into filesystem
135
-				return new FailedStorage(['exception' => $e]);
136
-			}
137
-		}, $storageConfigs);
138
-
139
-
140
-		\OC\Files\Cache\Storage::getGlobalCache()->loadForStorageIds(array_map(function(Storage\IStorage $storage) {
141
-			return $storage->getId();
142
-		}, $storages));
143
-
144
-		$availableStorages = array_map(function (Storage\IStorage $storage, StorageConfig $storageConfig) {
145
-			try {
146
-				$availability = $storage->getAvailability();
147
-				if (!$availability['available'] && !Availability::shouldRecheck($availability)) {
148
-					$storage = new FailedStorage([
149
-						'exception' => new StorageNotAvailableException('Storage with mount id ' . $storageConfig->getId() . ' is not available')
150
-					]);
151
-				}
152
-			} catch (\Exception $e) {
153
-				// propagate exception into filesystem
154
-				$storage = new FailedStorage(['exception' => $e]);
155
-			}
156
-			return $storage;
157
-		}, $storages, $storageConfigs);
158
-
159
-		$mounts = array_map(function(StorageConfig $storageConfig, Storage\IStorage $storage) use ($user, $loader) {
160
-			if ($storageConfig->getType() === StorageConfig::MOUNT_TYPE_PERSONAl) {
161
-				return new PersonalMount(
162
-					$this->userStoragesService,
163
-					$storageConfig->getId(),
164
-					$storage,
165
-					'/' . $user->getUID() . '/files' . $storageConfig->getMountPoint(),
166
-					null,
167
-					$loader,
168
-					$storageConfig->getMountOptions()
169
-				);
170
-			} else {
171
-				return new MountPoint(
172
-					$storage,
173
-					'/' . $user->getUID() . '/files' . $storageConfig->getMountPoint(),
174
-					null,
175
-					$loader,
176
-					$storageConfig->getMountOptions(),
177
-					$storageConfig->getId()
178
-				);
179
-			}
180
-		}, $storageConfigs, $availableStorages);
181
-
182
-		$this->userStoragesService->resetUser();
183
-		$this->userGlobalStoragesService->resetUser();
184
-
185
-		return $mounts;
186
-	}
48
+    /** @var UserStoragesService */
49
+    private $userStoragesService;
50
+
51
+    /** @var UserGlobalStoragesService */
52
+    private $userGlobalStoragesService;
53
+    /** @var StorageMigrator  */
54
+    private $migrator;
55
+
56
+    /**
57
+     * @param UserStoragesService $userStoragesService
58
+     * @param UserGlobalStoragesService $userGlobalStoragesService
59
+     * @param StorageMigrator $migrator
60
+     */
61
+    public function __construct(
62
+        UserStoragesService $userStoragesService,
63
+        UserGlobalStoragesService $userGlobalStoragesService,
64
+        StorageMigrator $migrator
65
+    ) {
66
+        $this->userStoragesService = $userStoragesService;
67
+        $this->userGlobalStoragesService = $userGlobalStoragesService;
68
+        $this->migrator = $migrator;
69
+    }
70
+
71
+    /**
72
+     * Process storage ready for mounting
73
+     *
74
+     * @param StorageConfig $storage
75
+     * @param IUser $user
76
+     */
77
+    private function prepareStorageConfig(StorageConfig &$storage, IUser $user) {
78
+        foreach ($storage->getBackendOptions() as $option => $value) {
79
+            $storage->setBackendOption($option, \OC_Mount_Config::setUserVars(
80
+                $user->getUID(), $value
81
+            ));
82
+        }
83
+
84
+        $objectStore = $storage->getBackendOption('objectstore');
85
+        if ($objectStore) {
86
+            $objectClass = $objectStore['class'];
87
+            if (!is_subclass_of($objectClass, '\OCP\Files\ObjectStore\IObjectStore')) {
88
+                throw new \InvalidArgumentException('Invalid object store');
89
+            }
90
+            $storage->setBackendOption('objectstore', new $objectClass($objectStore));
91
+        }
92
+
93
+        $storage->getAuthMechanism()->manipulateStorageConfig($storage, $user);
94
+        $storage->getBackend()->manipulateStorageConfig($storage, $user);
95
+    }
96
+
97
+    /**
98
+     * Construct the storage implementation
99
+     *
100
+     * @param StorageConfig $storageConfig
101
+     * @return Storage
102
+     */
103
+    private function constructStorage(StorageConfig $storageConfig) {
104
+        $class = $storageConfig->getBackend()->getStorageClass();
105
+        $storage = new $class($storageConfig->getBackendOptions());
106
+
107
+        // auth mechanism should fire first
108
+        $storage = $storageConfig->getBackend()->wrapStorage($storage);
109
+        $storage = $storageConfig->getAuthMechanism()->wrapStorage($storage);
110
+
111
+        return $storage;
112
+    }
113
+
114
+    /**
115
+     * Get all mountpoints applicable for the user
116
+     *
117
+     * @param \OCP\IUser $user
118
+     * @param \OCP\Files\Storage\IStorageFactory $loader
119
+     * @return \OCP\Files\Mount\IMountPoint[]
120
+     */
121
+    public function getMountsForUser(IUser $user, IStorageFactory $loader) {
122
+        $this->migrator->migrateUser($user);
123
+
124
+        $this->userStoragesService->setUser($user);
125
+        $this->userGlobalStoragesService->setUser($user);
126
+
127
+        $storageConfigs = $this->userGlobalStoragesService->getAllStoragesForUser();
128
+
129
+        $storages = array_map(function(StorageConfig $storageConfig) use ($user) {
130
+            try {
131
+                $this->prepareStorageConfig($storageConfig, $user);
132
+                return $this->constructStorage($storageConfig);
133
+            } catch (\Exception $e) {
134
+                // propagate exception into filesystem
135
+                return new FailedStorage(['exception' => $e]);
136
+            }
137
+        }, $storageConfigs);
138
+
139
+
140
+        \OC\Files\Cache\Storage::getGlobalCache()->loadForStorageIds(array_map(function(Storage\IStorage $storage) {
141
+            return $storage->getId();
142
+        }, $storages));
143
+
144
+        $availableStorages = array_map(function (Storage\IStorage $storage, StorageConfig $storageConfig) {
145
+            try {
146
+                $availability = $storage->getAvailability();
147
+                if (!$availability['available'] && !Availability::shouldRecheck($availability)) {
148
+                    $storage = new FailedStorage([
149
+                        'exception' => new StorageNotAvailableException('Storage with mount id ' . $storageConfig->getId() . ' is not available')
150
+                    ]);
151
+                }
152
+            } catch (\Exception $e) {
153
+                // propagate exception into filesystem
154
+                $storage = new FailedStorage(['exception' => $e]);
155
+            }
156
+            return $storage;
157
+        }, $storages, $storageConfigs);
158
+
159
+        $mounts = array_map(function(StorageConfig $storageConfig, Storage\IStorage $storage) use ($user, $loader) {
160
+            if ($storageConfig->getType() === StorageConfig::MOUNT_TYPE_PERSONAl) {
161
+                return new PersonalMount(
162
+                    $this->userStoragesService,
163
+                    $storageConfig->getId(),
164
+                    $storage,
165
+                    '/' . $user->getUID() . '/files' . $storageConfig->getMountPoint(),
166
+                    null,
167
+                    $loader,
168
+                    $storageConfig->getMountOptions()
169
+                );
170
+            } else {
171
+                return new MountPoint(
172
+                    $storage,
173
+                    '/' . $user->getUID() . '/files' . $storageConfig->getMountPoint(),
174
+                    null,
175
+                    $loader,
176
+                    $storageConfig->getMountOptions(),
177
+                    $storageConfig->getId()
178
+                );
179
+            }
180
+        }, $storageConfigs, $availableStorages);
181
+
182
+        $this->userStoragesService->resetUser();
183
+        $this->userGlobalStoragesService->resetUser();
184
+
185
+        return $mounts;
186
+    }
187 187
 }
Please login to merge, or discard this patch.
apps/files_external/lib/config.php 1 patch
Indentation   +367 added lines, -367 removed lines patch added patch discarded remove patch
@@ -45,371 +45,371 @@
 block discarded – undo
45 45
  * Class to configure mount.json globally and for users
46 46
  */
47 47
 class OC_Mount_Config {
48
-	// TODO: make this class non-static and give it a proper namespace
49
-
50
-	const MOUNT_TYPE_GLOBAL = 'global';
51
-	const MOUNT_TYPE_GROUP = 'group';
52
-	const MOUNT_TYPE_USER = 'user';
53
-	const MOUNT_TYPE_PERSONAL = 'personal';
54
-
55
-	// whether to skip backend test (for unit tests, as this static class is not mockable)
56
-	public static $skipTest = false;
57
-
58
-	/** @var Application */
59
-	public static $app;
60
-
61
-	/**
62
-	 * @param string $class
63
-	 * @param array $definition
64
-	 * @return bool
65
-	 * @deprecated 8.2.0 use \OCA\Files_External\Service\BackendService::registerBackend()
66
-	 */
67
-	public static function registerBackend($class, $definition) {
68
-		$backendService = self::$app->getContainer()->query('OCA\Files_External\Service\BackendService');
69
-		$auth = self::$app->getContainer()->query('OCA\Files_External\Lib\Auth\Builtin');
70
-
71
-		$backendService->registerBackend(new LegacyBackend($class, $definition, $auth));
72
-
73
-		return true;
74
-	}
75
-
76
-	/**
77
-	 * Returns the mount points for the given user.
78
-	 * The mount point is relative to the data directory.
79
-	 *
80
-	 * @param string $uid user
81
-	 * @return array of mount point string as key, mountpoint config as value
82
-	 *
83
-	 * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
84
-	 */
85
-	public static function getAbsoluteMountPoints($uid) {
86
-		$mountPoints = array();
87
-
88
-		$userGlobalStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserGlobalStoragesService');
89
-		$userStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
90
-		$user = self::$app->getContainer()->query('OCP\IUserManager')->get($uid);
91
-
92
-		$userGlobalStoragesService->setUser($user);
93
-		$userStoragesService->setUser($user);
94
-
95
-		foreach ($userGlobalStoragesService->getStorages() as $storage) {
96
-			/** @var \OCA\Files_External\Lib\StorageConfig $storage */
97
-			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
98
-			$mountEntry = self::prepareMountPointEntry($storage, false);
99
-			foreach ($mountEntry['options'] as &$option) {
100
-				$option = self::setUserVars($uid, $option);
101
-			}
102
-			$mountPoints[$mountPoint] = $mountEntry;
103
-		}
104
-
105
-		foreach ($userStoragesService->getStorages() as $storage) {
106
-			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
107
-			$mountEntry = self::prepareMountPointEntry($storage, true);
108
-			foreach ($mountEntry['options'] as &$option) {
109
-				$option = self::setUserVars($uid, $option);
110
-			}
111
-			$mountPoints[$mountPoint] = $mountEntry;
112
-		}
113
-
114
-		$userGlobalStoragesService->resetUser();
115
-		$userStoragesService->resetUser();
116
-
117
-		return $mountPoints;
118
-	}
119
-
120
-	/**
121
-	 * Get the system mount points
122
-	 *
123
-	 * @return array
124
-	 *
125
-	 * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
126
-	 */
127
-	public static function getSystemMountPoints() {
128
-		$mountPoints = [];
129
-		$service = self::$app->getContainer()->query('OCA\Files_External\Service\GlobalStoragesService');
130
-
131
-		foreach ($service->getStorages() as $storage) {
132
-			$mountPoints[] = self::prepareMountPointEntry($storage, false);
133
-		}
134
-
135
-		return $mountPoints;
136
-	}
137
-
138
-	/**
139
-	 * Get the personal mount points of the current user
140
-	 *
141
-	 * @return array
142
-	 *
143
-	 * @deprecated 8.2.0 use UserStoragesService::getStorages()
144
-	 */
145
-	public static function getPersonalMountPoints() {
146
-		$mountPoints = [];
147
-		$service = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
148
-
149
-		foreach ($service->getStorages() as $storage) {
150
-			$mountPoints[] = self::prepareMountPointEntry($storage, true);
151
-		}
152
-
153
-		return $mountPoints;
154
-	}
155
-
156
-	/**
157
-	 * Convert a StorageConfig to the legacy mountPoints array format
158
-	 * There's a lot of extra information in here, to satisfy all of the legacy functions
159
-	 *
160
-	 * @param StorageConfig $storage
161
-	 * @param bool $isPersonal
162
-	 * @return array
163
-	 */
164
-	private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
165
-		$mountEntry = [];
166
-
167
-		$mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
168
-		$mountEntry['class'] = $storage->getBackend()->getIdentifier();
169
-		$mountEntry['backend'] = $storage->getBackend()->getText();
170
-		$mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
171
-		$mountEntry['personal'] = $isPersonal;
172
-		$mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
173
-		$mountEntry['mountOptions'] = $storage->getMountOptions();
174
-		$mountEntry['priority'] = $storage->getPriority();
175
-		$mountEntry['applicable'] = [
176
-			'groups' => $storage->getApplicableGroups(),
177
-			'users' => $storage->getApplicableUsers(),
178
-		];
179
-		// if mountpoint is applicable to all users the old API expects ['all']
180
-		if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
181
-			$mountEntry['applicable']['users'] = ['all'];
182
-		}
183
-
184
-		$mountEntry['id'] = $storage->getId();
185
-
186
-		return $mountEntry;
187
-	}
188
-
189
-	/**
190
-	 * fill in the correct values for $user
191
-	 *
192
-	 * @param string $user user value
193
-	 * @param string|array $input
194
-	 * @return string
195
-	 */
196
-	public static function setUserVars($user, $input) {
197
-		if (is_array($input)) {
198
-			foreach ($input as &$value) {
199
-				if (is_string($value)) {
200
-					$value = str_replace('$user', $user, $value);
201
-				}
202
-			}
203
-		} else {
204
-			if (is_string($input)) {
205
-				$input = str_replace('$user', $user, $input);
206
-			}
207
-		}
208
-		return $input;
209
-	}
210
-
211
-	/**
212
-	 * Test connecting using the given backend configuration
213
-	 *
214
-	 * @param string $class backend class name
215
-	 * @param array $options backend configuration options
216
-	 * @param boolean $isPersonal
217
-	 * @return int see self::STATUS_*
218
-	 * @throws Exception
219
-	 */
220
-	public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
221
-		if (self::$skipTest) {
222
-			return StorageNotAvailableException::STATUS_SUCCESS;
223
-		}
224
-		foreach ($options as &$option) {
225
-			$option = self::setUserVars(OCP\User::getUser(), $option);
226
-		}
227
-		if (class_exists($class)) {
228
-			try {
229
-				/** @var \OC\Files\Storage\Common $storage */
230
-				$storage = new $class($options);
231
-
232
-				try {
233
-					$result = $storage->test($isPersonal, $testOnly);
234
-					$storage->setAvailability($result);
235
-					if ($result) {
236
-						return StorageNotAvailableException::STATUS_SUCCESS;
237
-					}
238
-				} catch (\Exception $e) {
239
-					$storage->setAvailability(false);
240
-					throw $e;
241
-				}
242
-			} catch (Exception $exception) {
243
-				\OCP\Util::logException('files_external', $exception);
244
-				throw $exception;
245
-			}
246
-		}
247
-		return StorageNotAvailableException::STATUS_ERROR;
248
-	}
249
-
250
-	/**
251
-	 * Read the mount points in the config file into an array
252
-	 *
253
-	 * @param string|null $user If not null, personal for $user, otherwise system
254
-	 * @return array
255
-	 */
256
-	public static function readData($user = null) {
257
-		if (isset($user)) {
258
-			$jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
259
-		} else {
260
-			$config = \OC::$server->getConfig();
261
-			$datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
262
-			$jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
263
-		}
264
-		if (is_file($jsonFile)) {
265
-			$mountPoints = json_decode(file_get_contents($jsonFile), true);
266
-			if (is_array($mountPoints)) {
267
-				return $mountPoints;
268
-			}
269
-		}
270
-		return array();
271
-	}
272
-
273
-	/**
274
-	 * Get backend dependency message
275
-	 * TODO: move into AppFramework along with templates
276
-	 *
277
-	 * @param Backend[] $backends
278
-	 * @return string
279
-	 */
280
-	public static function dependencyMessage($backends) {
281
-		$l = \OC::$server->getL10N('files_external');
282
-		$message = '';
283
-		$dependencyGroups = [];
284
-
285
-		foreach ($backends as $backend) {
286
-			foreach ($backend->checkDependencies() as $dependency) {
287
-				if ($message = $dependency->getMessage()) {
288
-					$message .= '<p>' . $message . '</p>';
289
-				} else {
290
-					$dependencyGroups[$dependency->getDependency()][] = $backend;
291
-				}
292
-			}
293
-		}
294
-
295
-		foreach ($dependencyGroups as $module => $dependants) {
296
-			$backends = implode(', ', array_map(function($backend) {
297
-				return '"' . $backend->getText() . '"';
298
-			}, $dependants));
299
-			$message .= '<p>' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends) . '</p>';
300
-		}
301
-
302
-		return $message;
303
-	}
304
-
305
-	/**
306
-	 * Returns a dependency missing message
307
-	 *
308
-	 * @param \OCP\IL10N $l
309
-	 * @param string $module
310
-	 * @param string $backend
311
-	 * @return string
312
-	 */
313
-	private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
314
-		switch (strtolower($module)) {
315
-			case 'curl':
316
-				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);
317
-			case 'ftp':
318
-				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);
319
-			default:
320
-				return (string)$l->t('"%s" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it.', array($module, $backend));
321
-		}
322
-	}
323
-
324
-	/**
325
-	 * Encrypt passwords in the given config options
326
-	 *
327
-	 * @param array $options mount options
328
-	 * @return array updated options
329
-	 */
330
-	public static function encryptPasswords($options) {
331
-		if (isset($options['password'])) {
332
-			$options['password_encrypted'] = self::encryptPassword($options['password']);
333
-			// do not unset the password, we want to keep the keys order
334
-			// on load... because that's how the UI currently works
335
-			$options['password'] = '';
336
-		}
337
-		return $options;
338
-	}
339
-
340
-	/**
341
-	 * Decrypt passwords in the given config options
342
-	 *
343
-	 * @param array $options mount options
344
-	 * @return array updated options
345
-	 */
346
-	public static function decryptPasswords($options) {
347
-		// note: legacy options might still have the unencrypted password in the "password" field
348
-		if (isset($options['password_encrypted'])) {
349
-			$options['password'] = self::decryptPassword($options['password_encrypted']);
350
-			unset($options['password_encrypted']);
351
-		}
352
-		return $options;
353
-	}
354
-
355
-	/**
356
-	 * Encrypt a single password
357
-	 *
358
-	 * @param string $password plain text password
359
-	 * @return string encrypted password
360
-	 */
361
-	private static function encryptPassword($password) {
362
-		$cipher = self::getCipher();
363
-		$iv = \OCP\Util::generateRandomBytes(16);
364
-		$cipher->setIV($iv);
365
-		return base64_encode($iv . $cipher->encrypt($password));
366
-	}
367
-
368
-	/**
369
-	 * Decrypts a single password
370
-	 *
371
-	 * @param string $encryptedPassword encrypted password
372
-	 * @return string plain text password
373
-	 */
374
-	private static function decryptPassword($encryptedPassword) {
375
-		$cipher = self::getCipher();
376
-		$binaryPassword = base64_decode($encryptedPassword);
377
-		$iv = substr($binaryPassword, 0, 16);
378
-		$cipher->setIV($iv);
379
-		$binaryPassword = substr($binaryPassword, 16);
380
-		return $cipher->decrypt($binaryPassword);
381
-	}
382
-
383
-	/**
384
-	 * Returns the encryption cipher
385
-	 *
386
-	 * @return AES
387
-	 */
388
-	private static function getCipher() {
389
-		$cipher = new AES(AES::MODE_CBC);
390
-		$cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
391
-		return $cipher;
392
-	}
393
-
394
-	/**
395
-	 * Computes a hash based on the given configuration.
396
-	 * This is mostly used to find out whether configurations
397
-	 * are the same.
398
-	 *
399
-	 * @param array $config
400
-	 * @return string
401
-	 */
402
-	public static function makeConfigHash($config) {
403
-		$data = json_encode(
404
-			array(
405
-				'c' => $config['backend'],
406
-				'a' => $config['authMechanism'],
407
-				'm' => $config['mountpoint'],
408
-				'o' => $config['options'],
409
-				'p' => isset($config['priority']) ? $config['priority'] : -1,
410
-				'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
411
-			)
412
-		);
413
-		return hash('md5', $data);
414
-	}
48
+    // TODO: make this class non-static and give it a proper namespace
49
+
50
+    const MOUNT_TYPE_GLOBAL = 'global';
51
+    const MOUNT_TYPE_GROUP = 'group';
52
+    const MOUNT_TYPE_USER = 'user';
53
+    const MOUNT_TYPE_PERSONAL = 'personal';
54
+
55
+    // whether to skip backend test (for unit tests, as this static class is not mockable)
56
+    public static $skipTest = false;
57
+
58
+    /** @var Application */
59
+    public static $app;
60
+
61
+    /**
62
+     * @param string $class
63
+     * @param array $definition
64
+     * @return bool
65
+     * @deprecated 8.2.0 use \OCA\Files_External\Service\BackendService::registerBackend()
66
+     */
67
+    public static function registerBackend($class, $definition) {
68
+        $backendService = self::$app->getContainer()->query('OCA\Files_External\Service\BackendService');
69
+        $auth = self::$app->getContainer()->query('OCA\Files_External\Lib\Auth\Builtin');
70
+
71
+        $backendService->registerBackend(new LegacyBackend($class, $definition, $auth));
72
+
73
+        return true;
74
+    }
75
+
76
+    /**
77
+     * Returns the mount points for the given user.
78
+     * The mount point is relative to the data directory.
79
+     *
80
+     * @param string $uid user
81
+     * @return array of mount point string as key, mountpoint config as value
82
+     *
83
+     * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
84
+     */
85
+    public static function getAbsoluteMountPoints($uid) {
86
+        $mountPoints = array();
87
+
88
+        $userGlobalStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserGlobalStoragesService');
89
+        $userStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
90
+        $user = self::$app->getContainer()->query('OCP\IUserManager')->get($uid);
91
+
92
+        $userGlobalStoragesService->setUser($user);
93
+        $userStoragesService->setUser($user);
94
+
95
+        foreach ($userGlobalStoragesService->getStorages() as $storage) {
96
+            /** @var \OCA\Files_External\Lib\StorageConfig $storage */
97
+            $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
98
+            $mountEntry = self::prepareMountPointEntry($storage, false);
99
+            foreach ($mountEntry['options'] as &$option) {
100
+                $option = self::setUserVars($uid, $option);
101
+            }
102
+            $mountPoints[$mountPoint] = $mountEntry;
103
+        }
104
+
105
+        foreach ($userStoragesService->getStorages() as $storage) {
106
+            $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
107
+            $mountEntry = self::prepareMountPointEntry($storage, true);
108
+            foreach ($mountEntry['options'] as &$option) {
109
+                $option = self::setUserVars($uid, $option);
110
+            }
111
+            $mountPoints[$mountPoint] = $mountEntry;
112
+        }
113
+
114
+        $userGlobalStoragesService->resetUser();
115
+        $userStoragesService->resetUser();
116
+
117
+        return $mountPoints;
118
+    }
119
+
120
+    /**
121
+     * Get the system mount points
122
+     *
123
+     * @return array
124
+     *
125
+     * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
126
+     */
127
+    public static function getSystemMountPoints() {
128
+        $mountPoints = [];
129
+        $service = self::$app->getContainer()->query('OCA\Files_External\Service\GlobalStoragesService');
130
+
131
+        foreach ($service->getStorages() as $storage) {
132
+            $mountPoints[] = self::prepareMountPointEntry($storage, false);
133
+        }
134
+
135
+        return $mountPoints;
136
+    }
137
+
138
+    /**
139
+     * Get the personal mount points of the current user
140
+     *
141
+     * @return array
142
+     *
143
+     * @deprecated 8.2.0 use UserStoragesService::getStorages()
144
+     */
145
+    public static function getPersonalMountPoints() {
146
+        $mountPoints = [];
147
+        $service = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
148
+
149
+        foreach ($service->getStorages() as $storage) {
150
+            $mountPoints[] = self::prepareMountPointEntry($storage, true);
151
+        }
152
+
153
+        return $mountPoints;
154
+    }
155
+
156
+    /**
157
+     * Convert a StorageConfig to the legacy mountPoints array format
158
+     * There's a lot of extra information in here, to satisfy all of the legacy functions
159
+     *
160
+     * @param StorageConfig $storage
161
+     * @param bool $isPersonal
162
+     * @return array
163
+     */
164
+    private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
165
+        $mountEntry = [];
166
+
167
+        $mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
168
+        $mountEntry['class'] = $storage->getBackend()->getIdentifier();
169
+        $mountEntry['backend'] = $storage->getBackend()->getText();
170
+        $mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
171
+        $mountEntry['personal'] = $isPersonal;
172
+        $mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
173
+        $mountEntry['mountOptions'] = $storage->getMountOptions();
174
+        $mountEntry['priority'] = $storage->getPriority();
175
+        $mountEntry['applicable'] = [
176
+            'groups' => $storage->getApplicableGroups(),
177
+            'users' => $storage->getApplicableUsers(),
178
+        ];
179
+        // if mountpoint is applicable to all users the old API expects ['all']
180
+        if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
181
+            $mountEntry['applicable']['users'] = ['all'];
182
+        }
183
+
184
+        $mountEntry['id'] = $storage->getId();
185
+
186
+        return $mountEntry;
187
+    }
188
+
189
+    /**
190
+     * fill in the correct values for $user
191
+     *
192
+     * @param string $user user value
193
+     * @param string|array $input
194
+     * @return string
195
+     */
196
+    public static function setUserVars($user, $input) {
197
+        if (is_array($input)) {
198
+            foreach ($input as &$value) {
199
+                if (is_string($value)) {
200
+                    $value = str_replace('$user', $user, $value);
201
+                }
202
+            }
203
+        } else {
204
+            if (is_string($input)) {
205
+                $input = str_replace('$user', $user, $input);
206
+            }
207
+        }
208
+        return $input;
209
+    }
210
+
211
+    /**
212
+     * Test connecting using the given backend configuration
213
+     *
214
+     * @param string $class backend class name
215
+     * @param array $options backend configuration options
216
+     * @param boolean $isPersonal
217
+     * @return int see self::STATUS_*
218
+     * @throws Exception
219
+     */
220
+    public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
221
+        if (self::$skipTest) {
222
+            return StorageNotAvailableException::STATUS_SUCCESS;
223
+        }
224
+        foreach ($options as &$option) {
225
+            $option = self::setUserVars(OCP\User::getUser(), $option);
226
+        }
227
+        if (class_exists($class)) {
228
+            try {
229
+                /** @var \OC\Files\Storage\Common $storage */
230
+                $storage = new $class($options);
231
+
232
+                try {
233
+                    $result = $storage->test($isPersonal, $testOnly);
234
+                    $storage->setAvailability($result);
235
+                    if ($result) {
236
+                        return StorageNotAvailableException::STATUS_SUCCESS;
237
+                    }
238
+                } catch (\Exception $e) {
239
+                    $storage->setAvailability(false);
240
+                    throw $e;
241
+                }
242
+            } catch (Exception $exception) {
243
+                \OCP\Util::logException('files_external', $exception);
244
+                throw $exception;
245
+            }
246
+        }
247
+        return StorageNotAvailableException::STATUS_ERROR;
248
+    }
249
+
250
+    /**
251
+     * Read the mount points in the config file into an array
252
+     *
253
+     * @param string|null $user If not null, personal for $user, otherwise system
254
+     * @return array
255
+     */
256
+    public static function readData($user = null) {
257
+        if (isset($user)) {
258
+            $jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
259
+        } else {
260
+            $config = \OC::$server->getConfig();
261
+            $datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
262
+            $jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
263
+        }
264
+        if (is_file($jsonFile)) {
265
+            $mountPoints = json_decode(file_get_contents($jsonFile), true);
266
+            if (is_array($mountPoints)) {
267
+                return $mountPoints;
268
+            }
269
+        }
270
+        return array();
271
+    }
272
+
273
+    /**
274
+     * Get backend dependency message
275
+     * TODO: move into AppFramework along with templates
276
+     *
277
+     * @param Backend[] $backends
278
+     * @return string
279
+     */
280
+    public static function dependencyMessage($backends) {
281
+        $l = \OC::$server->getL10N('files_external');
282
+        $message = '';
283
+        $dependencyGroups = [];
284
+
285
+        foreach ($backends as $backend) {
286
+            foreach ($backend->checkDependencies() as $dependency) {
287
+                if ($message = $dependency->getMessage()) {
288
+                    $message .= '<p>' . $message . '</p>';
289
+                } else {
290
+                    $dependencyGroups[$dependency->getDependency()][] = $backend;
291
+                }
292
+            }
293
+        }
294
+
295
+        foreach ($dependencyGroups as $module => $dependants) {
296
+            $backends = implode(', ', array_map(function($backend) {
297
+                return '"' . $backend->getText() . '"';
298
+            }, $dependants));
299
+            $message .= '<p>' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends) . '</p>';
300
+        }
301
+
302
+        return $message;
303
+    }
304
+
305
+    /**
306
+     * Returns a dependency missing message
307
+     *
308
+     * @param \OCP\IL10N $l
309
+     * @param string $module
310
+     * @param string $backend
311
+     * @return string
312
+     */
313
+    private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
314
+        switch (strtolower($module)) {
315
+            case 'curl':
316
+                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);
317
+            case 'ftp':
318
+                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);
319
+            default:
320
+                return (string)$l->t('"%s" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it.', array($module, $backend));
321
+        }
322
+    }
323
+
324
+    /**
325
+     * Encrypt passwords in the given config options
326
+     *
327
+     * @param array $options mount options
328
+     * @return array updated options
329
+     */
330
+    public static function encryptPasswords($options) {
331
+        if (isset($options['password'])) {
332
+            $options['password_encrypted'] = self::encryptPassword($options['password']);
333
+            // do not unset the password, we want to keep the keys order
334
+            // on load... because that's how the UI currently works
335
+            $options['password'] = '';
336
+        }
337
+        return $options;
338
+    }
339
+
340
+    /**
341
+     * Decrypt passwords in the given config options
342
+     *
343
+     * @param array $options mount options
344
+     * @return array updated options
345
+     */
346
+    public static function decryptPasswords($options) {
347
+        // note: legacy options might still have the unencrypted password in the "password" field
348
+        if (isset($options['password_encrypted'])) {
349
+            $options['password'] = self::decryptPassword($options['password_encrypted']);
350
+            unset($options['password_encrypted']);
351
+        }
352
+        return $options;
353
+    }
354
+
355
+    /**
356
+     * Encrypt a single password
357
+     *
358
+     * @param string $password plain text password
359
+     * @return string encrypted password
360
+     */
361
+    private static function encryptPassword($password) {
362
+        $cipher = self::getCipher();
363
+        $iv = \OCP\Util::generateRandomBytes(16);
364
+        $cipher->setIV($iv);
365
+        return base64_encode($iv . $cipher->encrypt($password));
366
+    }
367
+
368
+    /**
369
+     * Decrypts a single password
370
+     *
371
+     * @param string $encryptedPassword encrypted password
372
+     * @return string plain text password
373
+     */
374
+    private static function decryptPassword($encryptedPassword) {
375
+        $cipher = self::getCipher();
376
+        $binaryPassword = base64_decode($encryptedPassword);
377
+        $iv = substr($binaryPassword, 0, 16);
378
+        $cipher->setIV($iv);
379
+        $binaryPassword = substr($binaryPassword, 16);
380
+        return $cipher->decrypt($binaryPassword);
381
+    }
382
+
383
+    /**
384
+     * Returns the encryption cipher
385
+     *
386
+     * @return AES
387
+     */
388
+    private static function getCipher() {
389
+        $cipher = new AES(AES::MODE_CBC);
390
+        $cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
391
+        return $cipher;
392
+    }
393
+
394
+    /**
395
+     * Computes a hash based on the given configuration.
396
+     * This is mostly used to find out whether configurations
397
+     * are the same.
398
+     *
399
+     * @param array $config
400
+     * @return string
401
+     */
402
+    public static function makeConfigHash($config) {
403
+        $data = json_encode(
404
+            array(
405
+                'c' => $config['backend'],
406
+                'a' => $config['authMechanism'],
407
+                'm' => $config['mountpoint'],
408
+                'o' => $config['options'],
409
+                'p' => isset($config['priority']) ? $config['priority'] : -1,
410
+                'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
411
+            )
412
+        );
413
+        return hash('md5', $data);
414
+    }
415 415
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Migration/StorageMigrator.php 1 patch
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -42,107 +42,107 @@
 block discarded – undo
42 42
  * Migrate mount config from mount.json to the database
43 43
  */
44 44
 class StorageMigrator {
45
-	/**
46
-	 * @var BackendService
47
-	 */
48
-	private $backendService;
45
+    /**
46
+     * @var BackendService
47
+     */
48
+    private $backendService;
49 49
 
50
-	/**
51
-	 * @var DBConfigService
52
-	 */
53
-	private $dbConfig;
50
+    /**
51
+     * @var DBConfigService
52
+     */
53
+    private $dbConfig;
54 54
 
55
-	/**
56
-	 * @var IConfig
57
-	 */
58
-	private $config;
55
+    /**
56
+     * @var IConfig
57
+     */
58
+    private $config;
59 59
 
60
-	/**
61
-	 * @var IDBConnection
62
-	 */
63
-	private $connection;
60
+    /**
61
+     * @var IDBConnection
62
+     */
63
+    private $connection;
64 64
 
65
-	/**
66
-	 * @var ILogger
67
-	 */
68
-	private $logger;
65
+    /**
66
+     * @var ILogger
67
+     */
68
+    private $logger;
69 69
 
70
-	/** @var IUserMountCache  */
71
-	private $userMountCache;
70
+    /** @var IUserMountCache  */
71
+    private $userMountCache;
72 72
 
73
-	/**
74
-	 * StorageMigrator constructor.
75
-	 *
76
-	 * @param BackendService $backendService
77
-	 * @param DBConfigService $dbConfig
78
-	 * @param IConfig $config
79
-	 * @param IDBConnection $connection
80
-	 * @param ILogger $logger
81
-	 * @param IUserMountCache $userMountCache
82
-	 */
83
-	public function __construct(
84
-		BackendService $backendService,
85
-		DBConfigService $dbConfig,
86
-		IConfig $config,
87
-		IDBConnection $connection,
88
-		ILogger $logger,
89
-		IUserMountCache $userMountCache
90
-	) {
91
-		$this->backendService = $backendService;
92
-		$this->dbConfig = $dbConfig;
93
-		$this->config = $config;
94
-		$this->connection = $connection;
95
-		$this->logger = $logger;
96
-		$this->userMountCache = $userMountCache;
97
-	}
73
+    /**
74
+     * StorageMigrator constructor.
75
+     *
76
+     * @param BackendService $backendService
77
+     * @param DBConfigService $dbConfig
78
+     * @param IConfig $config
79
+     * @param IDBConnection $connection
80
+     * @param ILogger $logger
81
+     * @param IUserMountCache $userMountCache
82
+     */
83
+    public function __construct(
84
+        BackendService $backendService,
85
+        DBConfigService $dbConfig,
86
+        IConfig $config,
87
+        IDBConnection $connection,
88
+        ILogger $logger,
89
+        IUserMountCache $userMountCache
90
+    ) {
91
+        $this->backendService = $backendService;
92
+        $this->dbConfig = $dbConfig;
93
+        $this->config = $config;
94
+        $this->connection = $connection;
95
+        $this->logger = $logger;
96
+        $this->userMountCache = $userMountCache;
97
+    }
98 98
 
99
-	private function migrate(LegacyStoragesService $legacyService, StoragesService $storageService) {
100
-		$existingStorage = $legacyService->getAllStorages();
99
+    private function migrate(LegacyStoragesService $legacyService, StoragesService $storageService) {
100
+        $existingStorage = $legacyService->getAllStorages();
101 101
 
102
-		$this->connection->beginTransaction();
103
-		try {
104
-			foreach ($existingStorage as $storage) {
105
-				$mountOptions = $storage->getMountOptions();
106
-				if (!empty($mountOptions) && !isset($mountOptions['enable_sharing'])) {
107
-					// existing mounts must have sharing enabled by default to avoid surprises
108
-					$mountOptions['enable_sharing'] = true;
109
-					$storage->setMountOptions($mountOptions);
110
-				}
111
-				$storageService->addStorage($storage);
112
-			}
113
-			$this->connection->commit();
114
-		} catch (\Exception $e) {
115
-			$this->logger->logException($e);
116
-			$this->connection->rollBack();
117
-		}
118
-	}
102
+        $this->connection->beginTransaction();
103
+        try {
104
+            foreach ($existingStorage as $storage) {
105
+                $mountOptions = $storage->getMountOptions();
106
+                if (!empty($mountOptions) && !isset($mountOptions['enable_sharing'])) {
107
+                    // existing mounts must have sharing enabled by default to avoid surprises
108
+                    $mountOptions['enable_sharing'] = true;
109
+                    $storage->setMountOptions($mountOptions);
110
+                }
111
+                $storageService->addStorage($storage);
112
+            }
113
+            $this->connection->commit();
114
+        } catch (\Exception $e) {
115
+            $this->logger->logException($e);
116
+            $this->connection->rollBack();
117
+        }
118
+    }
119 119
 
120
-	/**
121
-	 * Migrate admin configured storages
122
-	 */
123
-	public function migrateGlobal() {
124
-		$legacyService = new GlobalLegacyStoragesService($this->backendService);
125
-		$storageService = new GlobalStoragesService($this->backendService, $this->dbConfig, $this->userMountCache);
120
+    /**
121
+     * Migrate admin configured storages
122
+     */
123
+    public function migrateGlobal() {
124
+        $legacyService = new GlobalLegacyStoragesService($this->backendService);
125
+        $storageService = new GlobalStoragesService($this->backendService, $this->dbConfig, $this->userMountCache);
126 126
 
127
-		$this->migrate($legacyService, $storageService);
128
-	}
127
+        $this->migrate($legacyService, $storageService);
128
+    }
129 129
 
130
-	/**
131
-	 * Migrate personal storages configured by the current user
132
-	 *
133
-	 * @param IUser $user
134
-	 */
135
-	public function migrateUser(IUser $user) {
136
-		$dummySession = new DummyUserSession();
137
-		$dummySession->setUser($user);
138
-		$userId = $user->getUID();
139
-		$userVersion = $this->config->getUserValue($userId, 'files_external', 'config_version', '0.0.0');
140
-		if (version_compare($userVersion, '0.5.0', '<')) {
141
-			$this->config->setUserValue($userId, 'files_external', 'config_version', '0.5.0');
142
-			$legacyService = new UserLegacyStoragesService($this->backendService, $dummySession);
143
-			$storageService = new UserStoragesService($this->backendService, $this->dbConfig, $dummySession, $this->userMountCache);
130
+    /**
131
+     * Migrate personal storages configured by the current user
132
+     *
133
+     * @param IUser $user
134
+     */
135
+    public function migrateUser(IUser $user) {
136
+        $dummySession = new DummyUserSession();
137
+        $dummySession->setUser($user);
138
+        $userId = $user->getUID();
139
+        $userVersion = $this->config->getUserValue($userId, 'files_external', 'config_version', '0.0.0');
140
+        if (version_compare($userVersion, '0.5.0', '<')) {
141
+            $this->config->setUserValue($userId, 'files_external', 'config_version', '0.5.0');
142
+            $legacyService = new UserLegacyStoragesService($this->backendService, $dummySession);
143
+            $storageService = new UserStoragesService($this->backendService, $this->dbConfig, $dummySession, $this->userMountCache);
144 144
 
145
-			$this->migrate($legacyService, $storageService);
146
-		}
147
-	}
145
+            $this->migrate($legacyService, $storageService);
146
+        }
147
+    }
148 148
 }
Please login to merge, or discard this patch.