Passed
Push — master ( 683685...5ed673 )
by Morris
13:18 queued 11s
created
apps/files_external/lib/Controller/UserStoragesController.php 1 patch
Indentation   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -45,181 +45,181 @@
 block discarded – undo
45 45
  * User storages controller
46 46
  */
47 47
 class UserStoragesController extends StoragesController {
48
-	/**
49
-	 * Creates a new user storages controller.
50
-	 *
51
-	 * @param string $AppName application name
52
-	 * @param IRequest $request request object
53
-	 * @param IL10N $l10n l10n service
54
-	 * @param UserStoragesService $userStoragesService storage service
55
-	 * @param ILogger $logger
56
-	 * @param IUserSession $userSession
57
-	 * @param IGroupManager $groupManager
58
-	 */
59
-	public function __construct(
60
-		$AppName,
61
-		IRequest $request,
62
-		IL10N $l10n,
63
-		UserStoragesService $userStoragesService,
64
-		ILogger $logger,
65
-		IUserSession $userSession,
66
-		IGroupManager $groupManager
67
-	) {
68
-		parent::__construct(
69
-			$AppName,
70
-			$request,
71
-			$l10n,
72
-			$userStoragesService,
73
-			$logger,
74
-			$userSession,
75
-			$groupManager
76
-		);
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
-			$this->formatStorageForUI($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' => $this->l10n->t('Storage with ID "%d" not found', [$id])
202
-				],
203
-				Http::STATUS_NOT_FOUND
204
-			);
205
-		}
206
-
207
-		$this->updateStorageStatus($storage, $testOnly);
208
-
209
-		return new DataResponse(
210
-			$this->formatStorageForUI($storage),
211
-			Http::STATUS_OK
212
-		);
213
-	}
214
-
215
-	/**
216
-	 * Delete storage
217
-	 *
218
-	 * @NoAdminRequired
219
-	 *
220
-	 * {@inheritdoc}
221
-	 */
222
-	public function destroy($id) {
223
-		return parent::destroy($id);
224
-	}
48
+    /**
49
+     * Creates a new user storages controller.
50
+     *
51
+     * @param string $AppName application name
52
+     * @param IRequest $request request object
53
+     * @param IL10N $l10n l10n service
54
+     * @param UserStoragesService $userStoragesService storage service
55
+     * @param ILogger $logger
56
+     * @param IUserSession $userSession
57
+     * @param IGroupManager $groupManager
58
+     */
59
+    public function __construct(
60
+        $AppName,
61
+        IRequest $request,
62
+        IL10N $l10n,
63
+        UserStoragesService $userStoragesService,
64
+        ILogger $logger,
65
+        IUserSession $userSession,
66
+        IGroupManager $groupManager
67
+    ) {
68
+        parent::__construct(
69
+            $AppName,
70
+            $request,
71
+            $l10n,
72
+            $userStoragesService,
73
+            $logger,
74
+            $userSession,
75
+            $groupManager
76
+        );
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
+            $this->formatStorageForUI($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' => $this->l10n->t('Storage with ID "%d" not found', [$id])
202
+                ],
203
+                Http::STATUS_NOT_FOUND
204
+            );
205
+        }
206
+
207
+        $this->updateStorageStatus($storage, $testOnly);
208
+
209
+        return new DataResponse(
210
+            $this->formatStorageForUI($storage),
211
+            Http::STATUS_OK
212
+        );
213
+    }
214
+
215
+    /**
216
+     * Delete storage
217
+     *
218
+     * @NoAdminRequired
219
+     *
220
+     * {@inheritdoc}
221
+     */
222
+    public function destroy($id) {
223
+        return parent::destroy($id);
224
+    }
225 225
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/UserGlobalStoragesController.php 1 patch
Indentation   +162 added lines, -162 removed lines patch added patch discarded remove patch
@@ -47,166 +47,166 @@
 block discarded – undo
47 47
  * User global storages controller
48 48
  */
49 49
 class UserGlobalStoragesController extends StoragesController {
50
-	/**
51
-	 * Creates a new user global storages controller.
52
-	 *
53
-	 * @param string $AppName application name
54
-	 * @param IRequest $request request object
55
-	 * @param IL10N $l10n l10n service
56
-	 * @param UserGlobalStoragesService $userGlobalStoragesService storage service
57
-	 * @param ILogger $logger
58
-	 * @param IUserSession $userSession
59
-	 * @param IGroupManager $groupManager
60
-	 */
61
-	public function __construct(
62
-		$AppName,
63
-		IRequest $request,
64
-		IL10N $l10n,
65
-		UserGlobalStoragesService $userGlobalStoragesService,
66
-		ILogger $logger,
67
-		IUserSession $userSession,
68
-		IGroupManager $groupManager
69
-	) {
70
-		parent::__construct(
71
-			$AppName,
72
-			$request,
73
-			$l10n,
74
-			$userGlobalStoragesService,
75
-			$logger,
76
-			$userSession,
77
-			$groupManager
78
-		);
79
-	}
80
-
81
-	/**
82
-	 * Get all storage entries
83
-	 *
84
-	 * @return DataResponse
85
-	 *
86
-	 * @NoAdminRequired
87
-	 */
88
-	public function index() {
89
-		$storages = $this->formatStoragesForUI($this->service->getUniqueStorages());
90
-
91
-		// remove configuration data, this must be kept private
92
-		foreach ($storages as $storage) {
93
-			$this->sanitizeStorage($storage);
94
-		}
95
-
96
-		return new DataResponse(
97
-			$storages,
98
-			Http::STATUS_OK
99
-		);
100
-	}
101
-
102
-	protected function manipulateStorageConfig(StorageConfig $storage) {
103
-		/** @var AuthMechanism */
104
-		$authMechanism = $storage->getAuthMechanism();
105
-		$authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
106
-		/** @var Backend */
107
-		$backend = $storage->getBackend();
108
-		$backend->manipulateStorageConfig($storage, $this->userSession->getUser());
109
-	}
110
-
111
-	/**
112
-	 * Get an external storage entry.
113
-	 *
114
-	 * @param int $id storage id
115
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
116
-	 * @return DataResponse
117
-	 *
118
-	 * @NoAdminRequired
119
-	 */
120
-	public function show($id, $testOnly = true) {
121
-		try {
122
-			$storage = $this->service->getStorage($id);
123
-
124
-			$this->updateStorageStatus($storage, $testOnly);
125
-		} catch (NotFoundException $e) {
126
-			return new DataResponse(
127
-				[
128
-					'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
129
-				],
130
-				Http::STATUS_NOT_FOUND
131
-			);
132
-		}
133
-
134
-		$this->sanitizeStorage($storage);
135
-
136
-		$data = $this->formatStorageForUI($storage)->jsonSerialize();
137
-		$isAdmin = $this->groupManager->isAdmin($this->userSession->getUser()->getUID());
138
-		$data['can_edit'] = $storage->getType() === StorageConfig::MOUNT_TYPE_PERSONAl || $isAdmin;
139
-
140
-		return new DataResponse(
141
-			$data,
142
-			Http::STATUS_OK
143
-		);
144
-	}
145
-
146
-	/**
147
-	 * Update an external storage entry.
148
-	 * Only allows setting user provided backend fields
149
-	 *
150
-	 * @param int $id storage id
151
-	 * @param array $backendOptions backend-specific options
152
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
153
-	 *
154
-	 * @return DataResponse
155
-	 *
156
-	 * @NoAdminRequired
157
-	 */
158
-	public function update(
159
-		$id,
160
-		$backendOptions,
161
-		$testOnly = true
162
-	) {
163
-		try {
164
-			$storage = $this->service->getStorage($id);
165
-			$authMechanism = $storage->getAuthMechanism();
166
-			if ($authMechanism instanceof IUserProvided || $authMechanism instanceof  UserGlobalAuth) {
167
-				$authMechanism->saveBackendOptions($this->userSession->getUser(), $id, $backendOptions);
168
-				$authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
169
-			} else {
170
-				return new DataResponse(
171
-					[
172
-						'message' => $this->l10n->t('Storage with ID "%d" is not user editable', [$id])
173
-					],
174
-					Http::STATUS_FORBIDDEN
175
-				);
176
-			}
177
-		} catch (NotFoundException $e) {
178
-			return new DataResponse(
179
-				[
180
-					'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
181
-				],
182
-				Http::STATUS_NOT_FOUND
183
-			);
184
-		}
185
-
186
-		$this->updateStorageStatus($storage, $testOnly);
187
-		$this->sanitizeStorage($storage);
188
-
189
-		return new DataResponse(
190
-			$this->formatStorageForUI($storage),
191
-			Http::STATUS_OK
192
-		);
193
-	}
194
-
195
-	/**
196
-	 * Remove sensitive data from a StorageConfig before returning it to the user
197
-	 *
198
-	 * @param StorageConfig $storage
199
-	 */
200
-	protected function sanitizeStorage(StorageConfig $storage) {
201
-		$storage->setBackendOptions([]);
202
-		$storage->setMountOptions([]);
203
-
204
-		if ($storage->getAuthMechanism() instanceof IUserProvided) {
205
-			try {
206
-				$storage->getAuthMechanism()->manipulateStorageConfig($storage, $this->userSession->getUser());
207
-			} catch (InsufficientDataForMeaningfulAnswerException $e) {
208
-				// not configured yet
209
-			}
210
-		}
211
-	}
50
+    /**
51
+     * Creates a new user global storages controller.
52
+     *
53
+     * @param string $AppName application name
54
+     * @param IRequest $request request object
55
+     * @param IL10N $l10n l10n service
56
+     * @param UserGlobalStoragesService $userGlobalStoragesService storage service
57
+     * @param ILogger $logger
58
+     * @param IUserSession $userSession
59
+     * @param IGroupManager $groupManager
60
+     */
61
+    public function __construct(
62
+        $AppName,
63
+        IRequest $request,
64
+        IL10N $l10n,
65
+        UserGlobalStoragesService $userGlobalStoragesService,
66
+        ILogger $logger,
67
+        IUserSession $userSession,
68
+        IGroupManager $groupManager
69
+    ) {
70
+        parent::__construct(
71
+            $AppName,
72
+            $request,
73
+            $l10n,
74
+            $userGlobalStoragesService,
75
+            $logger,
76
+            $userSession,
77
+            $groupManager
78
+        );
79
+    }
80
+
81
+    /**
82
+     * Get all storage entries
83
+     *
84
+     * @return DataResponse
85
+     *
86
+     * @NoAdminRequired
87
+     */
88
+    public function index() {
89
+        $storages = $this->formatStoragesForUI($this->service->getUniqueStorages());
90
+
91
+        // remove configuration data, this must be kept private
92
+        foreach ($storages as $storage) {
93
+            $this->sanitizeStorage($storage);
94
+        }
95
+
96
+        return new DataResponse(
97
+            $storages,
98
+            Http::STATUS_OK
99
+        );
100
+    }
101
+
102
+    protected function manipulateStorageConfig(StorageConfig $storage) {
103
+        /** @var AuthMechanism */
104
+        $authMechanism = $storage->getAuthMechanism();
105
+        $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
106
+        /** @var Backend */
107
+        $backend = $storage->getBackend();
108
+        $backend->manipulateStorageConfig($storage, $this->userSession->getUser());
109
+    }
110
+
111
+    /**
112
+     * Get an external storage entry.
113
+     *
114
+     * @param int $id storage id
115
+     * @param bool $testOnly whether to storage should only test the connection or do more things
116
+     * @return DataResponse
117
+     *
118
+     * @NoAdminRequired
119
+     */
120
+    public function show($id, $testOnly = true) {
121
+        try {
122
+            $storage = $this->service->getStorage($id);
123
+
124
+            $this->updateStorageStatus($storage, $testOnly);
125
+        } catch (NotFoundException $e) {
126
+            return new DataResponse(
127
+                [
128
+                    'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
129
+                ],
130
+                Http::STATUS_NOT_FOUND
131
+            );
132
+        }
133
+
134
+        $this->sanitizeStorage($storage);
135
+
136
+        $data = $this->formatStorageForUI($storage)->jsonSerialize();
137
+        $isAdmin = $this->groupManager->isAdmin($this->userSession->getUser()->getUID());
138
+        $data['can_edit'] = $storage->getType() === StorageConfig::MOUNT_TYPE_PERSONAl || $isAdmin;
139
+
140
+        return new DataResponse(
141
+            $data,
142
+            Http::STATUS_OK
143
+        );
144
+    }
145
+
146
+    /**
147
+     * Update an external storage entry.
148
+     * Only allows setting user provided backend fields
149
+     *
150
+     * @param int $id storage id
151
+     * @param array $backendOptions backend-specific options
152
+     * @param bool $testOnly whether to storage should only test the connection or do more things
153
+     *
154
+     * @return DataResponse
155
+     *
156
+     * @NoAdminRequired
157
+     */
158
+    public function update(
159
+        $id,
160
+        $backendOptions,
161
+        $testOnly = true
162
+    ) {
163
+        try {
164
+            $storage = $this->service->getStorage($id);
165
+            $authMechanism = $storage->getAuthMechanism();
166
+            if ($authMechanism instanceof IUserProvided || $authMechanism instanceof  UserGlobalAuth) {
167
+                $authMechanism->saveBackendOptions($this->userSession->getUser(), $id, $backendOptions);
168
+                $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
169
+            } else {
170
+                return new DataResponse(
171
+                    [
172
+                        'message' => $this->l10n->t('Storage with ID "%d" is not user editable', [$id])
173
+                    ],
174
+                    Http::STATUS_FORBIDDEN
175
+                );
176
+            }
177
+        } catch (NotFoundException $e) {
178
+            return new DataResponse(
179
+                [
180
+                    'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
181
+                ],
182
+                Http::STATUS_NOT_FOUND
183
+            );
184
+        }
185
+
186
+        $this->updateStorageStatus($storage, $testOnly);
187
+        $this->sanitizeStorage($storage);
188
+
189
+        return new DataResponse(
190
+            $this->formatStorageForUI($storage),
191
+            Http::STATUS_OK
192
+        );
193
+    }
194
+
195
+    /**
196
+     * Remove sensitive data from a StorageConfig before returning it to the user
197
+     *
198
+     * @param StorageConfig $storage
199
+     */
200
+    protected function sanitizeStorage(StorageConfig $storage) {
201
+        $storage->setBackendOptions([]);
202
+        $storage->setMountOptions([]);
203
+
204
+        if ($storage->getAuthMechanism() instanceof IUserProvided) {
205
+            try {
206
+                $storage->getAuthMechanism()->manipulateStorageConfig($storage, $this->userSession->getUser());
207
+            } catch (InsufficientDataForMeaningfulAnswerException $e) {
208
+                // not configured yet
209
+            }
210
+        }
211
+    }
212 212
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Controller/GlobalStoragesController.php 1 patch
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -42,154 +42,154 @@
 block discarded – undo
42 42
  * Global storages controller
43 43
  */
44 44
 class GlobalStoragesController extends StoragesController {
45
-	/**
46
-	 * Creates a new global storages controller.
47
-	 *
48
-	 * @param string $AppName application name
49
-	 * @param IRequest $request request object
50
-	 * @param IL10N $l10n l10n service
51
-	 * @param GlobalStoragesService $globalStoragesService storage service
52
-	 * @param ILogger $logger
53
-	 * @param IUserSession $userSession
54
-	 * @param IGroupManager $groupManager
55
-	 */
56
-	public function __construct(
57
-		$AppName,
58
-		IRequest $request,
59
-		IL10N $l10n,
60
-		GlobalStoragesService $globalStoragesService,
61
-		ILogger $logger,
62
-		IUserSession $userSession,
63
-		IGroupManager $groupManager
64
-	) {
65
-		parent::__construct(
66
-			$AppName,
67
-			$request,
68
-			$l10n,
69
-			$globalStoragesService,
70
-			$logger,
71
-			$userSession,
72
-			$groupManager
73
-		);
74
-	}
45
+    /**
46
+     * Creates a new global storages controller.
47
+     *
48
+     * @param string $AppName application name
49
+     * @param IRequest $request request object
50
+     * @param IL10N $l10n l10n service
51
+     * @param GlobalStoragesService $globalStoragesService storage service
52
+     * @param ILogger $logger
53
+     * @param IUserSession $userSession
54
+     * @param IGroupManager $groupManager
55
+     */
56
+    public function __construct(
57
+        $AppName,
58
+        IRequest $request,
59
+        IL10N $l10n,
60
+        GlobalStoragesService $globalStoragesService,
61
+        ILogger $logger,
62
+        IUserSession $userSession,
63
+        IGroupManager $groupManager
64
+    ) {
65
+        parent::__construct(
66
+            $AppName,
67
+            $request,
68
+            $l10n,
69
+            $globalStoragesService,
70
+            $logger,
71
+            $userSession,
72
+            $groupManager
73
+        );
74
+    }
75 75
 
76
-	/**
77
-	 * Create an external storage entry.
78
-	 *
79
-	 * @param string $mountPoint storage mount point
80
-	 * @param string $backend backend identifier
81
-	 * @param string $authMechanism authentication mechanism identifier
82
-	 * @param array $backendOptions backend-specific options
83
-	 * @param array $mountOptions mount-specific options
84
-	 * @param array $applicableUsers users for which to mount the storage
85
-	 * @param array $applicableGroups groups for which to mount the storage
86
-	 * @param int $priority priority
87
-	 *
88
-	 * @return DataResponse
89
-	 */
90
-	public function create(
91
-		$mountPoint,
92
-		$backend,
93
-		$authMechanism,
94
-		$backendOptions,
95
-		$mountOptions,
96
-		$applicableUsers,
97
-		$applicableGroups,
98
-		$priority
99
-	) {
100
-		$newStorage = $this->createStorage(
101
-			$mountPoint,
102
-			$backend,
103
-			$authMechanism,
104
-			$backendOptions,
105
-			$mountOptions,
106
-			$applicableUsers,
107
-			$applicableGroups,
108
-			$priority
109
-		);
110
-		if ($newStorage instanceof DataResponse) {
111
-			return $newStorage;
112
-		}
76
+    /**
77
+     * Create an external storage entry.
78
+     *
79
+     * @param string $mountPoint storage mount point
80
+     * @param string $backend backend identifier
81
+     * @param string $authMechanism authentication mechanism identifier
82
+     * @param array $backendOptions backend-specific options
83
+     * @param array $mountOptions mount-specific options
84
+     * @param array $applicableUsers users for which to mount the storage
85
+     * @param array $applicableGroups groups for which to mount the storage
86
+     * @param int $priority priority
87
+     *
88
+     * @return DataResponse
89
+     */
90
+    public function create(
91
+        $mountPoint,
92
+        $backend,
93
+        $authMechanism,
94
+        $backendOptions,
95
+        $mountOptions,
96
+        $applicableUsers,
97
+        $applicableGroups,
98
+        $priority
99
+    ) {
100
+        $newStorage = $this->createStorage(
101
+            $mountPoint,
102
+            $backend,
103
+            $authMechanism,
104
+            $backendOptions,
105
+            $mountOptions,
106
+            $applicableUsers,
107
+            $applicableGroups,
108
+            $priority
109
+        );
110
+        if ($newStorage instanceof DataResponse) {
111
+            return $newStorage;
112
+        }
113 113
 
114
-		$response = $this->validate($newStorage);
115
-		if (!empty($response)) {
116
-			return $response;
117
-		}
114
+        $response = $this->validate($newStorage);
115
+        if (!empty($response)) {
116
+            return $response;
117
+        }
118 118
 
119
-		$newStorage = $this->service->addStorage($newStorage);
119
+        $newStorage = $this->service->addStorage($newStorage);
120 120
 
121
-		$this->updateStorageStatus($newStorage);
121
+        $this->updateStorageStatus($newStorage);
122 122
 
123
-		return new DataResponse(
124
-			$this->formatStorageForUI($newStorage),
125
-			Http::STATUS_CREATED
126
-		);
127
-	}
123
+        return new DataResponse(
124
+            $this->formatStorageForUI($newStorage),
125
+            Http::STATUS_CREATED
126
+        );
127
+    }
128 128
 
129
-	/**
130
-	 * Update an external storage entry.
131
-	 *
132
-	 * @param int $id storage id
133
-	 * @param string $mountPoint storage mount point
134
-	 * @param string $backend backend identifier
135
-	 * @param string $authMechanism authentication mechansim identifier
136
-	 * @param array $backendOptions backend-specific options
137
-	 * @param array $mountOptions mount-specific options
138
-	 * @param array $applicableUsers users for which to mount the storage
139
-	 * @param array $applicableGroups groups for which to mount the storage
140
-	 * @param int $priority priority
141
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
142
-	 *
143
-	 * @return DataResponse
144
-	 */
145
-	public function update(
146
-		$id,
147
-		$mountPoint,
148
-		$backend,
149
-		$authMechanism,
150
-		$backendOptions,
151
-		$mountOptions,
152
-		$applicableUsers,
153
-		$applicableGroups,
154
-		$priority,
155
-		$testOnly = true
156
-	) {
157
-		$storage = $this->createStorage(
158
-			$mountPoint,
159
-			$backend,
160
-			$authMechanism,
161
-			$backendOptions,
162
-			$mountOptions,
163
-			$applicableUsers,
164
-			$applicableGroups,
165
-			$priority
166
-		);
167
-		if ($storage instanceof DataResponse) {
168
-			return $storage;
169
-		}
170
-		$storage->setId($id);
129
+    /**
130
+     * Update an external storage entry.
131
+     *
132
+     * @param int $id storage id
133
+     * @param string $mountPoint storage mount point
134
+     * @param string $backend backend identifier
135
+     * @param string $authMechanism authentication mechansim identifier
136
+     * @param array $backendOptions backend-specific options
137
+     * @param array $mountOptions mount-specific options
138
+     * @param array $applicableUsers users for which to mount the storage
139
+     * @param array $applicableGroups groups for which to mount the storage
140
+     * @param int $priority priority
141
+     * @param bool $testOnly whether to storage should only test the connection or do more things
142
+     *
143
+     * @return DataResponse
144
+     */
145
+    public function update(
146
+        $id,
147
+        $mountPoint,
148
+        $backend,
149
+        $authMechanism,
150
+        $backendOptions,
151
+        $mountOptions,
152
+        $applicableUsers,
153
+        $applicableGroups,
154
+        $priority,
155
+        $testOnly = true
156
+    ) {
157
+        $storage = $this->createStorage(
158
+            $mountPoint,
159
+            $backend,
160
+            $authMechanism,
161
+            $backendOptions,
162
+            $mountOptions,
163
+            $applicableUsers,
164
+            $applicableGroups,
165
+            $priority
166
+        );
167
+        if ($storage instanceof DataResponse) {
168
+            return $storage;
169
+        }
170
+        $storage->setId($id);
171 171
 
172
-		$response = $this->validate($storage);
173
-		if (!empty($response)) {
174
-			return $response;
175
-		}
172
+        $response = $this->validate($storage);
173
+        if (!empty($response)) {
174
+            return $response;
175
+        }
176 176
 
177
-		try {
178
-			$storage = $this->service->updateStorage($storage);
179
-		} catch (NotFoundException $e) {
180
-			return new DataResponse(
181
-				[
182
-					'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
183
-				],
184
-				Http::STATUS_NOT_FOUND
185
-			);
186
-		}
177
+        try {
178
+            $storage = $this->service->updateStorage($storage);
179
+        } catch (NotFoundException $e) {
180
+            return new DataResponse(
181
+                [
182
+                    'message' => $this->l10n->t('Storage with ID "%d" not found', [$id])
183
+                ],
184
+                Http::STATUS_NOT_FOUND
185
+            );
186
+        }
187 187
 
188
-		$this->updateStorageStatus($storage, $testOnly);
188
+        $this->updateStorageStatus($storage, $testOnly);
189 189
 
190
-		return new DataResponse(
191
-			$this->formatStorageForUI($storage),
192
-			Http::STATUS_OK
193
-		);
194
-	}
190
+        return new DataResponse(
191
+            $this->formatStorageForUI($storage),
192
+            Http::STATUS_OK
193
+        );
194
+    }
195 195
 }
Please login to merge, or discard this patch.
apps/files_external/lib/MountConfig.php 2 patches
Indentation   +337 added lines, -337 removed lines patch added patch discarded remove patch
@@ -57,341 +57,341 @@
 block discarded – undo
57 57
  * Class to configure mount.json globally and for users
58 58
  */
59 59
 class MountConfig {
60
-	// TODO: make this class non-static and give it a proper namespace
61
-
62
-	public const MOUNT_TYPE_GLOBAL = 'global';
63
-	public const MOUNT_TYPE_GROUP = 'group';
64
-	public const MOUNT_TYPE_USER = 'user';
65
-	public const MOUNT_TYPE_PERSONAL = 'personal';
66
-
67
-	// whether to skip backend test (for unit tests, as this static class is not mockable)
68
-	public static $skipTest = false;
69
-
70
-	/** @var Application */
71
-	public static $app;
72
-
73
-	/**
74
-	 * Returns the mount points for the given user.
75
-	 * The mount point is relative to the data directory.
76
-	 *
77
-	 * @param string $uid user
78
-	 * @return array of mount point string as key, mountpoint config as value
79
-	 *
80
-	 * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
81
-	 */
82
-	public static function getAbsoluteMountPoints($uid) {
83
-		$mountPoints = [];
84
-
85
-		$userGlobalStoragesService = self::$app->getContainer()->query(UserGlobalStoragesService::class);
86
-		$userStoragesService = self::$app->getContainer()->query(UserStoragesService::class);
87
-		$user = self::$app->getContainer()->query(IUserManager::class)->get($uid);
88
-
89
-		$userGlobalStoragesService->setUser($user);
90
-		$userStoragesService->setUser($user);
91
-
92
-		foreach ($userGlobalStoragesService->getStorages() as $storage) {
93
-			/** @var \OCA\Files_External\Lib\StorageConfig $storage */
94
-			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
95
-			$mountEntry = self::prepareMountPointEntry($storage, false);
96
-			foreach ($mountEntry['options'] as &$option) {
97
-				$option = self::substitutePlaceholdersInConfig($option, $uid);
98
-			}
99
-			$mountPoints[$mountPoint] = $mountEntry;
100
-		}
101
-
102
-		foreach ($userStoragesService->getStorages() as $storage) {
103
-			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
104
-			$mountEntry = self::prepareMountPointEntry($storage, true);
105
-			foreach ($mountEntry['options'] as &$option) {
106
-				$option = self::substitutePlaceholdersInConfig($option, $uid);
107
-			}
108
-			$mountPoints[$mountPoint] = $mountEntry;
109
-		}
110
-
111
-		$userGlobalStoragesService->resetUser();
112
-		$userStoragesService->resetUser();
113
-
114
-		return $mountPoints;
115
-	}
116
-
117
-	/**
118
-	 * Get the system mount points
119
-	 *
120
-	 * @return array
121
-	 *
122
-	 * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
123
-	 */
124
-	public static function getSystemMountPoints() {
125
-		$mountPoints = [];
126
-		$service = self::$app->getContainer()->query(GlobalStoragesService::class);
127
-
128
-		foreach ($service->getStorages() as $storage) {
129
-			$mountPoints[] = self::prepareMountPointEntry($storage, false);
130
-		}
131
-
132
-		return $mountPoints;
133
-	}
134
-
135
-	/**
136
-	 * Convert a StorageConfig to the legacy mountPoints array format
137
-	 * There's a lot of extra information in here, to satisfy all of the legacy functions
138
-	 *
139
-	 * @param StorageConfig $storage
140
-	 * @param bool $isPersonal
141
-	 * @return array
142
-	 */
143
-	private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
144
-		$mountEntry = [];
145
-
146
-		$mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
147
-		$mountEntry['class'] = $storage->getBackend()->getIdentifier();
148
-		$mountEntry['backend'] = $storage->getBackend()->getText();
149
-		$mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
150
-		$mountEntry['personal'] = $isPersonal;
151
-		$mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
152
-		$mountEntry['mountOptions'] = $storage->getMountOptions();
153
-		$mountEntry['priority'] = $storage->getPriority();
154
-		$mountEntry['applicable'] = [
155
-			'groups' => $storage->getApplicableGroups(),
156
-			'users' => $storage->getApplicableUsers(),
157
-		];
158
-		// if mountpoint is applicable to all users the old API expects ['all']
159
-		if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
160
-			$mountEntry['applicable']['users'] = ['all'];
161
-		}
162
-
163
-		$mountEntry['id'] = $storage->getId();
164
-
165
-		return $mountEntry;
166
-	}
167
-
168
-	/**
169
-	 * @param mixed $input
170
-	 * @param string|null $userId
171
-	 * @return mixed
172
-	 * @throws \OCP\AppFramework\QueryException
173
-	 * @since 16.0.0
174
-	 */
175
-	public static function substitutePlaceholdersInConfig($input, string $userId = null) {
176
-		/** @var BackendService $backendService */
177
-		$backendService = self::$app->getContainer()->query(BackendService::class);
178
-		/** @var IConfigHandler[] $handlers */
179
-		$handlers = $backendService->getConfigHandlers();
180
-		foreach ($handlers as $handler) {
181
-			if ($handler instanceof UserContext && $userId !== null) {
182
-				$handler->setUserId($userId);
183
-			}
184
-			$input = $handler->handle($input);
185
-		}
186
-		return $input;
187
-	}
188
-
189
-	/**
190
-	 * Test connecting using the given backend configuration
191
-	 *
192
-	 * @param string $class backend class name
193
-	 * @param array $options backend configuration options
194
-	 * @param boolean $isPersonal
195
-	 * @return int see self::STATUS_*
196
-	 * @throws Exception
197
-	 */
198
-	public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
199
-		if (self::$skipTest) {
200
-			return StorageNotAvailableException::STATUS_SUCCESS;
201
-		}
202
-		foreach ($options as $key => &$option) {
203
-			if ($key === 'password') {
204
-				// no replacements in passwords
205
-				continue;
206
-			}
207
-			$option = self::substitutePlaceholdersInConfig($option);
208
-		}
209
-		if (class_exists($class)) {
210
-			try {
211
-				/** @var \OC\Files\Storage\Common $storage */
212
-				$storage = new $class($options);
213
-
214
-				try {
215
-					$result = $storage->test($isPersonal, $testOnly);
216
-					$storage->setAvailability($result);
217
-					if ($result) {
218
-						return StorageNotAvailableException::STATUS_SUCCESS;
219
-					}
220
-				} catch (\Exception $e) {
221
-					$storage->setAvailability(false);
222
-					throw $e;
223
-				}
224
-			} catch (Exception $exception) {
225
-				\OC::$server->getLogger()->logException($exception, ['app' => 'files_external']);
226
-				throw $exception;
227
-			}
228
-		}
229
-		return StorageNotAvailableException::STATUS_ERROR;
230
-	}
231
-
232
-	/**
233
-	 * Read the mount points in the config file into an array
234
-	 *
235
-	 * @param string|null $user If not null, personal for $user, otherwise system
236
-	 * @return array
237
-	 */
238
-	public static function readData($user = null) {
239
-		if (isset($user)) {
240
-			$jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
241
-		} else {
242
-			$config = \OC::$server->getConfig();
243
-			$datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
244
-			$jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
245
-		}
246
-		if (is_file($jsonFile)) {
247
-			$mountPoints = json_decode(file_get_contents($jsonFile), true);
248
-			if (is_array($mountPoints)) {
249
-				return $mountPoints;
250
-			}
251
-		}
252
-		return [];
253
-	}
254
-
255
-	/**
256
-	 * Get backend dependency message
257
-	 * TODO: move into AppFramework along with templates
258
-	 *
259
-	 * @param Backend[] $backends
260
-	 * @return string
261
-	 */
262
-	public static function dependencyMessage($backends) {
263
-		$l = \OC::$server->getL10N('files_external');
264
-		$message = '';
265
-		$dependencyGroups = [];
266
-
267
-		foreach ($backends as $backend) {
268
-			foreach ($backend->checkDependencies() as $dependency) {
269
-				if ($message = $dependency->getMessage()) {
270
-					$message .= '<p>' . $message . '</p>';
271
-				} else {
272
-					$dependencyGroups[$dependency->getDependency()][] = $backend;
273
-				}
274
-			}
275
-		}
276
-
277
-		foreach ($dependencyGroups as $module => $dependants) {
278
-			$backends = implode(', ', array_map(function ($backend) {
279
-				return '"' . $backend->getText() . '"';
280
-			}, $dependants));
281
-			$message .= '<p>' . MountConfig::getSingleDependencyMessage($l, $module, $backends) . '</p>';
282
-		}
283
-
284
-		return $message;
285
-	}
286
-
287
-	/**
288
-	 * Returns a dependency missing message
289
-	 *
290
-	 * @param \OCP\IL10N $l
291
-	 * @param string $module
292
-	 * @param string $backend
293
-	 * @return string
294
-	 */
295
-	private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
296
-		switch (strtolower($module)) {
297
-			case 'curl':
298
-				return $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]);
299
-			case 'ftp':
300
-				return $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]);
301
-			default:
302
-				return $l->t('"%1$s" is not installed. Mounting of %2$s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
303
-		}
304
-	}
305
-
306
-	/**
307
-	 * Encrypt passwords in the given config options
308
-	 *
309
-	 * @param array $options mount options
310
-	 * @return array updated options
311
-	 */
312
-	public static function encryptPasswords($options) {
313
-		if (isset($options['password'])) {
314
-			$options['password_encrypted'] = self::encryptPassword($options['password']);
315
-			// do not unset the password, we want to keep the keys order
316
-			// on load... because that's how the UI currently works
317
-			$options['password'] = '';
318
-		}
319
-		return $options;
320
-	}
321
-
322
-	/**
323
-	 * Decrypt passwords in the given config options
324
-	 *
325
-	 * @param array $options mount options
326
-	 * @return array updated options
327
-	 */
328
-	public static function decryptPasswords($options) {
329
-		// note: legacy options might still have the unencrypted password in the "password" field
330
-		if (isset($options['password_encrypted'])) {
331
-			$options['password'] = self::decryptPassword($options['password_encrypted']);
332
-			unset($options['password_encrypted']);
333
-		}
334
-		return $options;
335
-	}
336
-
337
-	/**
338
-	 * Encrypt a single password
339
-	 *
340
-	 * @param string $password plain text password
341
-	 * @return string encrypted password
342
-	 */
343
-	private static function encryptPassword($password) {
344
-		$cipher = self::getCipher();
345
-		$iv = \OC::$server->getSecureRandom()->generate(16);
346
-		$cipher->setIV($iv);
347
-		return base64_encode($iv . $cipher->encrypt($password));
348
-	}
349
-
350
-	/**
351
-	 * Decrypts a single password
352
-	 *
353
-	 * @param string $encryptedPassword encrypted password
354
-	 * @return string plain text password
355
-	 */
356
-	private static function decryptPassword($encryptedPassword) {
357
-		$cipher = self::getCipher();
358
-		$binaryPassword = base64_decode($encryptedPassword);
359
-		$iv = substr($binaryPassword, 0, 16);
360
-		$cipher->setIV($iv);
361
-		$binaryPassword = substr($binaryPassword, 16);
362
-		return $cipher->decrypt($binaryPassword);
363
-	}
364
-
365
-	/**
366
-	 * Returns the encryption cipher
367
-	 *
368
-	 * @return AES
369
-	 */
370
-	private static function getCipher() {
371
-		$cipher = new AES(AES::MODE_CBC);
372
-		$cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
373
-		return $cipher;
374
-	}
375
-
376
-	/**
377
-	 * Computes a hash based on the given configuration.
378
-	 * This is mostly used to find out whether configurations
379
-	 * are the same.
380
-	 *
381
-	 * @param array $config
382
-	 * @return string
383
-	 */
384
-	public static function makeConfigHash($config) {
385
-		$data = json_encode(
386
-			[
387
-				'c' => $config['backend'],
388
-				'a' => $config['authMechanism'],
389
-				'm' => $config['mountpoint'],
390
-				'o' => $config['options'],
391
-				'p' => isset($config['priority']) ? $config['priority'] : -1,
392
-				'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
393
-			]
394
-		);
395
-		return hash('md5', $data);
396
-	}
60
+    // TODO: make this class non-static and give it a proper namespace
61
+
62
+    public const MOUNT_TYPE_GLOBAL = 'global';
63
+    public const MOUNT_TYPE_GROUP = 'group';
64
+    public const MOUNT_TYPE_USER = 'user';
65
+    public const MOUNT_TYPE_PERSONAL = 'personal';
66
+
67
+    // whether to skip backend test (for unit tests, as this static class is not mockable)
68
+    public static $skipTest = false;
69
+
70
+    /** @var Application */
71
+    public static $app;
72
+
73
+    /**
74
+     * Returns the mount points for the given user.
75
+     * The mount point is relative to the data directory.
76
+     *
77
+     * @param string $uid user
78
+     * @return array of mount point string as key, mountpoint config as value
79
+     *
80
+     * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
81
+     */
82
+    public static function getAbsoluteMountPoints($uid) {
83
+        $mountPoints = [];
84
+
85
+        $userGlobalStoragesService = self::$app->getContainer()->query(UserGlobalStoragesService::class);
86
+        $userStoragesService = self::$app->getContainer()->query(UserStoragesService::class);
87
+        $user = self::$app->getContainer()->query(IUserManager::class)->get($uid);
88
+
89
+        $userGlobalStoragesService->setUser($user);
90
+        $userStoragesService->setUser($user);
91
+
92
+        foreach ($userGlobalStoragesService->getStorages() as $storage) {
93
+            /** @var \OCA\Files_External\Lib\StorageConfig $storage */
94
+            $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
95
+            $mountEntry = self::prepareMountPointEntry($storage, false);
96
+            foreach ($mountEntry['options'] as &$option) {
97
+                $option = self::substitutePlaceholdersInConfig($option, $uid);
98
+            }
99
+            $mountPoints[$mountPoint] = $mountEntry;
100
+        }
101
+
102
+        foreach ($userStoragesService->getStorages() as $storage) {
103
+            $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
104
+            $mountEntry = self::prepareMountPointEntry($storage, true);
105
+            foreach ($mountEntry['options'] as &$option) {
106
+                $option = self::substitutePlaceholdersInConfig($option, $uid);
107
+            }
108
+            $mountPoints[$mountPoint] = $mountEntry;
109
+        }
110
+
111
+        $userGlobalStoragesService->resetUser();
112
+        $userStoragesService->resetUser();
113
+
114
+        return $mountPoints;
115
+    }
116
+
117
+    /**
118
+     * Get the system mount points
119
+     *
120
+     * @return array
121
+     *
122
+     * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
123
+     */
124
+    public static function getSystemMountPoints() {
125
+        $mountPoints = [];
126
+        $service = self::$app->getContainer()->query(GlobalStoragesService::class);
127
+
128
+        foreach ($service->getStorages() as $storage) {
129
+            $mountPoints[] = self::prepareMountPointEntry($storage, false);
130
+        }
131
+
132
+        return $mountPoints;
133
+    }
134
+
135
+    /**
136
+     * Convert a StorageConfig to the legacy mountPoints array format
137
+     * There's a lot of extra information in here, to satisfy all of the legacy functions
138
+     *
139
+     * @param StorageConfig $storage
140
+     * @param bool $isPersonal
141
+     * @return array
142
+     */
143
+    private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
144
+        $mountEntry = [];
145
+
146
+        $mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
147
+        $mountEntry['class'] = $storage->getBackend()->getIdentifier();
148
+        $mountEntry['backend'] = $storage->getBackend()->getText();
149
+        $mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
150
+        $mountEntry['personal'] = $isPersonal;
151
+        $mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
152
+        $mountEntry['mountOptions'] = $storage->getMountOptions();
153
+        $mountEntry['priority'] = $storage->getPriority();
154
+        $mountEntry['applicable'] = [
155
+            'groups' => $storage->getApplicableGroups(),
156
+            'users' => $storage->getApplicableUsers(),
157
+        ];
158
+        // if mountpoint is applicable to all users the old API expects ['all']
159
+        if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
160
+            $mountEntry['applicable']['users'] = ['all'];
161
+        }
162
+
163
+        $mountEntry['id'] = $storage->getId();
164
+
165
+        return $mountEntry;
166
+    }
167
+
168
+    /**
169
+     * @param mixed $input
170
+     * @param string|null $userId
171
+     * @return mixed
172
+     * @throws \OCP\AppFramework\QueryException
173
+     * @since 16.0.0
174
+     */
175
+    public static function substitutePlaceholdersInConfig($input, string $userId = null) {
176
+        /** @var BackendService $backendService */
177
+        $backendService = self::$app->getContainer()->query(BackendService::class);
178
+        /** @var IConfigHandler[] $handlers */
179
+        $handlers = $backendService->getConfigHandlers();
180
+        foreach ($handlers as $handler) {
181
+            if ($handler instanceof UserContext && $userId !== null) {
182
+                $handler->setUserId($userId);
183
+            }
184
+            $input = $handler->handle($input);
185
+        }
186
+        return $input;
187
+    }
188
+
189
+    /**
190
+     * Test connecting using the given backend configuration
191
+     *
192
+     * @param string $class backend class name
193
+     * @param array $options backend configuration options
194
+     * @param boolean $isPersonal
195
+     * @return int see self::STATUS_*
196
+     * @throws Exception
197
+     */
198
+    public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
199
+        if (self::$skipTest) {
200
+            return StorageNotAvailableException::STATUS_SUCCESS;
201
+        }
202
+        foreach ($options as $key => &$option) {
203
+            if ($key === 'password') {
204
+                // no replacements in passwords
205
+                continue;
206
+            }
207
+            $option = self::substitutePlaceholdersInConfig($option);
208
+        }
209
+        if (class_exists($class)) {
210
+            try {
211
+                /** @var \OC\Files\Storage\Common $storage */
212
+                $storage = new $class($options);
213
+
214
+                try {
215
+                    $result = $storage->test($isPersonal, $testOnly);
216
+                    $storage->setAvailability($result);
217
+                    if ($result) {
218
+                        return StorageNotAvailableException::STATUS_SUCCESS;
219
+                    }
220
+                } catch (\Exception $e) {
221
+                    $storage->setAvailability(false);
222
+                    throw $e;
223
+                }
224
+            } catch (Exception $exception) {
225
+                \OC::$server->getLogger()->logException($exception, ['app' => 'files_external']);
226
+                throw $exception;
227
+            }
228
+        }
229
+        return StorageNotAvailableException::STATUS_ERROR;
230
+    }
231
+
232
+    /**
233
+     * Read the mount points in the config file into an array
234
+     *
235
+     * @param string|null $user If not null, personal for $user, otherwise system
236
+     * @return array
237
+     */
238
+    public static function readData($user = null) {
239
+        if (isset($user)) {
240
+            $jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
241
+        } else {
242
+            $config = \OC::$server->getConfig();
243
+            $datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
244
+            $jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
245
+        }
246
+        if (is_file($jsonFile)) {
247
+            $mountPoints = json_decode(file_get_contents($jsonFile), true);
248
+            if (is_array($mountPoints)) {
249
+                return $mountPoints;
250
+            }
251
+        }
252
+        return [];
253
+    }
254
+
255
+    /**
256
+     * Get backend dependency message
257
+     * TODO: move into AppFramework along with templates
258
+     *
259
+     * @param Backend[] $backends
260
+     * @return string
261
+     */
262
+    public static function dependencyMessage($backends) {
263
+        $l = \OC::$server->getL10N('files_external');
264
+        $message = '';
265
+        $dependencyGroups = [];
266
+
267
+        foreach ($backends as $backend) {
268
+            foreach ($backend->checkDependencies() as $dependency) {
269
+                if ($message = $dependency->getMessage()) {
270
+                    $message .= '<p>' . $message . '</p>';
271
+                } else {
272
+                    $dependencyGroups[$dependency->getDependency()][] = $backend;
273
+                }
274
+            }
275
+        }
276
+
277
+        foreach ($dependencyGroups as $module => $dependants) {
278
+            $backends = implode(', ', array_map(function ($backend) {
279
+                return '"' . $backend->getText() . '"';
280
+            }, $dependants));
281
+            $message .= '<p>' . MountConfig::getSingleDependencyMessage($l, $module, $backends) . '</p>';
282
+        }
283
+
284
+        return $message;
285
+    }
286
+
287
+    /**
288
+     * Returns a dependency missing message
289
+     *
290
+     * @param \OCP\IL10N $l
291
+     * @param string $module
292
+     * @param string $backend
293
+     * @return string
294
+     */
295
+    private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
296
+        switch (strtolower($module)) {
297
+            case 'curl':
298
+                return $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]);
299
+            case 'ftp':
300
+                return $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]);
301
+            default:
302
+                return $l->t('"%1$s" is not installed. Mounting of %2$s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
303
+        }
304
+    }
305
+
306
+    /**
307
+     * Encrypt passwords in the given config options
308
+     *
309
+     * @param array $options mount options
310
+     * @return array updated options
311
+     */
312
+    public static function encryptPasswords($options) {
313
+        if (isset($options['password'])) {
314
+            $options['password_encrypted'] = self::encryptPassword($options['password']);
315
+            // do not unset the password, we want to keep the keys order
316
+            // on load... because that's how the UI currently works
317
+            $options['password'] = '';
318
+        }
319
+        return $options;
320
+    }
321
+
322
+    /**
323
+     * Decrypt passwords in the given config options
324
+     *
325
+     * @param array $options mount options
326
+     * @return array updated options
327
+     */
328
+    public static function decryptPasswords($options) {
329
+        // note: legacy options might still have the unencrypted password in the "password" field
330
+        if (isset($options['password_encrypted'])) {
331
+            $options['password'] = self::decryptPassword($options['password_encrypted']);
332
+            unset($options['password_encrypted']);
333
+        }
334
+        return $options;
335
+    }
336
+
337
+    /**
338
+     * Encrypt a single password
339
+     *
340
+     * @param string $password plain text password
341
+     * @return string encrypted password
342
+     */
343
+    private static function encryptPassword($password) {
344
+        $cipher = self::getCipher();
345
+        $iv = \OC::$server->getSecureRandom()->generate(16);
346
+        $cipher->setIV($iv);
347
+        return base64_encode($iv . $cipher->encrypt($password));
348
+    }
349
+
350
+    /**
351
+     * Decrypts a single password
352
+     *
353
+     * @param string $encryptedPassword encrypted password
354
+     * @return string plain text password
355
+     */
356
+    private static function decryptPassword($encryptedPassword) {
357
+        $cipher = self::getCipher();
358
+        $binaryPassword = base64_decode($encryptedPassword);
359
+        $iv = substr($binaryPassword, 0, 16);
360
+        $cipher->setIV($iv);
361
+        $binaryPassword = substr($binaryPassword, 16);
362
+        return $cipher->decrypt($binaryPassword);
363
+    }
364
+
365
+    /**
366
+     * Returns the encryption cipher
367
+     *
368
+     * @return AES
369
+     */
370
+    private static function getCipher() {
371
+        $cipher = new AES(AES::MODE_CBC);
372
+        $cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
373
+        return $cipher;
374
+    }
375
+
376
+    /**
377
+     * Computes a hash based on the given configuration.
378
+     * This is mostly used to find out whether configurations
379
+     * are the same.
380
+     *
381
+     * @param array $config
382
+     * @return string
383
+     */
384
+    public static function makeConfigHash($config) {
385
+        $data = json_encode(
386
+            [
387
+                'c' => $config['backend'],
388
+                'a' => $config['authMechanism'],
389
+                'm' => $config['mountpoint'],
390
+                'o' => $config['options'],
391
+                'p' => isset($config['priority']) ? $config['priority'] : -1,
392
+                'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
393
+            ]
394
+        );
395
+        return hash('md5', $data);
396
+    }
397 397
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -237,11 +237,11 @@  discard block
 block discarded – undo
237 237
 	 */
238 238
 	public static function readData($user = null) {
239 239
 		if (isset($user)) {
240
-			$jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
240
+			$jsonFile = \OC::$server->getUserManager()->get($user)->getHome().'/mount.json';
241 241
 		} else {
242 242
 			$config = \OC::$server->getConfig();
243
-			$datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
244
-			$jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
243
+			$datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data/');
244
+			$jsonFile = $config->getSystemValue('mount_file', $datadir.'/mount.json');
245 245
 		}
246 246
 		if (is_file($jsonFile)) {
247 247
 			$mountPoints = json_decode(file_get_contents($jsonFile), true);
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 		foreach ($backends as $backend) {
268 268
 			foreach ($backend->checkDependencies() as $dependency) {
269 269
 				if ($message = $dependency->getMessage()) {
270
-					$message .= '<p>' . $message . '</p>';
270
+					$message .= '<p>'.$message.'</p>';
271 271
 				} else {
272 272
 					$dependencyGroups[$dependency->getDependency()][] = $backend;
273 273
 				}
@@ -275,10 +275,10 @@  discard block
 block discarded – undo
275 275
 		}
276 276
 
277 277
 		foreach ($dependencyGroups as $module => $dependants) {
278
-			$backends = implode(', ', array_map(function ($backend) {
279
-				return '"' . $backend->getText() . '"';
278
+			$backends = implode(', ', array_map(function($backend) {
279
+				return '"'.$backend->getText().'"';
280 280
 			}, $dependants));
281
-			$message .= '<p>' . MountConfig::getSingleDependencyMessage($l, $module, $backends) . '</p>';
281
+			$message .= '<p>'.MountConfig::getSingleDependencyMessage($l, $module, $backends).'</p>';
282 282
 		}
283 283
 
284 284
 		return $message;
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 		$cipher = self::getCipher();
345 345
 		$iv = \OC::$server->getSecureRandom()->generate(16);
346 346
 		$cipher->setIV($iv);
347
-		return base64_encode($iv . $cipher->encrypt($password));
347
+		return base64_encode($iv.$cipher->encrypt($password));
348 348
 	}
349 349
 
350 350
 	/**
Please login to merge, or discard this patch.
apps/theming/lib/IconBuilder.php 2 patches
Indentation   +206 added lines, -206 removed lines patch added patch discarded remove patch
@@ -32,210 +32,210 @@
 block discarded – undo
32 32
 use OCP\Files\SimpleFS\ISimpleFile;
33 33
 
34 34
 class IconBuilder {
35
-	/** @var ThemingDefaults */
36
-	private $themingDefaults;
37
-	/** @var Util */
38
-	private $util;
39
-	/** @var ImageManager */
40
-	private $imageManager;
41
-
42
-	/**
43
-	 * IconBuilder constructor.
44
-	 *
45
-	 * @param ThemingDefaults $themingDefaults
46
-	 * @param Util $util
47
-	 * @param ImageManager $imageManager
48
-	 */
49
-	public function __construct(
50
-		ThemingDefaults $themingDefaults,
51
-		Util $util,
52
-		ImageManager $imageManager
53
-	) {
54
-		$this->themingDefaults = $themingDefaults;
55
-		$this->util = $util;
56
-		$this->imageManager = $imageManager;
57
-	}
58
-
59
-	/**
60
-	 * @param $app string app name
61
-	 * @return string|false image blob
62
-	 */
63
-	public function getFavicon($app) {
64
-		if (!$this->imageManager->shouldReplaceIcons()) {
65
-			return false;
66
-		}
67
-		try {
68
-			$favicon = new Imagick();
69
-			$favicon->setFormat("ico");
70
-			$icon = $this->renderAppIcon($app, 128);
71
-			if ($icon === false) {
72
-				return false;
73
-			}
74
-			$icon->setImageFormat("png32");
75
-
76
-			$clone = clone $icon;
77
-			$clone->scaleImage(16,0);
78
-			$favicon->addImage($clone);
79
-
80
-			$clone = clone $icon;
81
-			$clone->scaleImage(32,0);
82
-			$favicon->addImage($clone);
83
-
84
-			$clone = clone $icon;
85
-			$clone->scaleImage(64,0);
86
-			$favicon->addImage($clone);
87
-
88
-			$clone = clone $icon;
89
-			$clone->scaleImage(128,0);
90
-			$favicon->addImage($clone);
91
-
92
-			$data = $favicon->getImagesBlob();
93
-			$favicon->destroy();
94
-			$icon->destroy();
95
-			$clone->destroy();
96
-			return $data;
97
-		} catch (\ImagickException $e) {
98
-			return false;
99
-		}
100
-	}
101
-
102
-	/**
103
-	 * @param $app string app name
104
-	 * @return string|false image blob
105
-	 */
106
-	public function getTouchIcon($app) {
107
-		try {
108
-			$icon = $this->renderAppIcon($app, 512);
109
-			if ($icon === false) {
110
-				return false;
111
-			}
112
-			$icon->setImageFormat("png32");
113
-			$data = $icon->getImageBlob();
114
-			$icon->destroy();
115
-			return $data;
116
-		} catch (\ImagickException $e) {
117
-			return false;
118
-		}
119
-	}
120
-
121
-	/**
122
-	 * Render app icon on themed background color
123
-	 * fallback to logo
124
-	 *
125
-	 * @param $app string app name
126
-	 * @param $size int size of the icon in px
127
-	 * @return Imagick|false
128
-	 */
129
-	public function renderAppIcon($app, $size) {
130
-		$appIcon = $this->util->getAppIcon($app);
131
-		if ($appIcon === false) {
132
-			return false;
133
-		}
134
-		if ($appIcon instanceof ISimpleFile) {
135
-			$appIconContent = $appIcon->getContent();
136
-			$mime = $appIcon->getMimeType();
137
-		} else {
138
-			$appIconContent = file_get_contents($appIcon);
139
-			$mime = mime_content_type($appIcon);
140
-		}
141
-
142
-		if ($appIconContent === false || $appIconContent === "") {
143
-			return false;
144
-		}
145
-
146
-		$color = $this->themingDefaults->getColorPrimary();
147
-
148
-		// generate background image with rounded corners
149
-		$background = '<?xml version="1.0" encoding="UTF-8"?>' .
150
-			'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:cc="http://creativecommons.org/ns#" width="512" height="512" xmlns:xlink="http://www.w3.org/1999/xlink">' .
151
-			'<rect x="0" y="0" rx="100" ry="100" width="512" height="512" style="fill:' . $color . ';" />' .
152
-			'</svg>';
153
-		// resize svg magic as this seems broken in Imagemagick
154
-		if ($mime === "image/svg+xml" || substr($appIconContent, 0, 4) === "<svg") {
155
-			if (substr($appIconContent, 0, 5) !== "<?xml") {
156
-				$svg = "<?xml version=\"1.0\"?>".$appIconContent;
157
-			} else {
158
-				$svg = $appIconContent;
159
-			}
160
-			$tmp = new Imagick();
161
-			$tmp->readImageBlob($svg);
162
-			$x = $tmp->getImageWidth();
163
-			$y = $tmp->getImageHeight();
164
-			$res = $tmp->getImageResolution();
165
-			$tmp->destroy();
166
-
167
-			if ($x > $y) {
168
-				$max = $x;
169
-			} else {
170
-				$max = $y;
171
-			}
172
-
173
-			// convert svg to resized image
174
-			$appIconFile = new Imagick();
175
-			$resX = (int)(512 * $res['x'] / $max * 2.53);
176
-			$resY = (int)(512 * $res['y'] / $max * 2.53);
177
-			$appIconFile->setResolution($resX, $resY);
178
-			$appIconFile->setBackgroundColor(new ImagickPixel('transparent'));
179
-			$appIconFile->readImageBlob($svg);
180
-
181
-			/**
182
-			 * invert app icons for bright primary colors
183
-			 * the default nextcloud logo will not be inverted to black
184
-			 */
185
-			if ($this->util->invertTextColor($color)
186
-				&& !$appIcon instanceof ISimpleFile
187
-				&& $app !== "core"
188
-			) {
189
-				$appIconFile->negateImage(false);
190
-			}
191
-			$appIconFile->scaleImage(512, 512, true);
192
-		} else {
193
-			$appIconFile = new Imagick();
194
-			$appIconFile->setBackgroundColor(new ImagickPixel('transparent'));
195
-			$appIconFile->readImageBlob($appIconContent);
196
-			$appIconFile->scaleImage(512, 512, true);
197
-		}
198
-		// offset for icon positioning
199
-		$border_w = (int)($appIconFile->getImageWidth() * 0.05);
200
-		$border_h = (int)($appIconFile->getImageHeight() * 0.05);
201
-		$innerWidth = ($appIconFile->getImageWidth() - $border_w * 2);
202
-		$innerHeight = ($appIconFile->getImageHeight() - $border_h * 2);
203
-		$appIconFile->adaptiveResizeImage($innerWidth, $innerHeight);
204
-		// center icon
205
-		$offset_w = 512 / 2 - $innerWidth / 2;
206
-		$offset_h = 512 / 2 - $innerHeight / 2;
207
-
208
-		$finalIconFile = new Imagick();
209
-		$finalIconFile->setBackgroundColor(new ImagickPixel('transparent'));
210
-		$finalIconFile->readImageBlob($background);
211
-		$finalIconFile->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
212
-		$finalIconFile->setImageArtifact('compose:args', "1,0,-0.5,0.5");
213
-		$finalIconFile->compositeImage($appIconFile, Imagick::COMPOSITE_ATOP, $offset_w, $offset_h);
214
-		$finalIconFile->setImageFormat('png24');
215
-		if (defined("Imagick::INTERPOLATE_BICUBIC") === true) {
216
-			$filter = Imagick::INTERPOLATE_BICUBIC;
217
-		} else {
218
-			$filter = Imagick::FILTER_LANCZOS;
219
-		}
220
-		$finalIconFile->resizeImage($size, $size, $filter, 1, false);
221
-
222
-		$appIconFile->destroy();
223
-		return $finalIconFile;
224
-	}
225
-
226
-	public function colorSvg($app, $image) {
227
-		try {
228
-			$imageFile = $this->util->getAppImage($app, $image);
229
-		} catch (AppPathNotFoundException $e) {
230
-			return false;
231
-		}
232
-		$svg = file_get_contents($imageFile);
233
-		if ($svg !== false && $svg !== "") {
234
-			$color = $this->util->elementColor($this->themingDefaults->getColorPrimary());
235
-			$svg = $this->util->colorizeSvg($svg, $color);
236
-			return $svg;
237
-		} else {
238
-			return false;
239
-		}
240
-	}
35
+    /** @var ThemingDefaults */
36
+    private $themingDefaults;
37
+    /** @var Util */
38
+    private $util;
39
+    /** @var ImageManager */
40
+    private $imageManager;
41
+
42
+    /**
43
+     * IconBuilder constructor.
44
+     *
45
+     * @param ThemingDefaults $themingDefaults
46
+     * @param Util $util
47
+     * @param ImageManager $imageManager
48
+     */
49
+    public function __construct(
50
+        ThemingDefaults $themingDefaults,
51
+        Util $util,
52
+        ImageManager $imageManager
53
+    ) {
54
+        $this->themingDefaults = $themingDefaults;
55
+        $this->util = $util;
56
+        $this->imageManager = $imageManager;
57
+    }
58
+
59
+    /**
60
+     * @param $app string app name
61
+     * @return string|false image blob
62
+     */
63
+    public function getFavicon($app) {
64
+        if (!$this->imageManager->shouldReplaceIcons()) {
65
+            return false;
66
+        }
67
+        try {
68
+            $favicon = new Imagick();
69
+            $favicon->setFormat("ico");
70
+            $icon = $this->renderAppIcon($app, 128);
71
+            if ($icon === false) {
72
+                return false;
73
+            }
74
+            $icon->setImageFormat("png32");
75
+
76
+            $clone = clone $icon;
77
+            $clone->scaleImage(16,0);
78
+            $favicon->addImage($clone);
79
+
80
+            $clone = clone $icon;
81
+            $clone->scaleImage(32,0);
82
+            $favicon->addImage($clone);
83
+
84
+            $clone = clone $icon;
85
+            $clone->scaleImage(64,0);
86
+            $favicon->addImage($clone);
87
+
88
+            $clone = clone $icon;
89
+            $clone->scaleImage(128,0);
90
+            $favicon->addImage($clone);
91
+
92
+            $data = $favicon->getImagesBlob();
93
+            $favicon->destroy();
94
+            $icon->destroy();
95
+            $clone->destroy();
96
+            return $data;
97
+        } catch (\ImagickException $e) {
98
+            return false;
99
+        }
100
+    }
101
+
102
+    /**
103
+     * @param $app string app name
104
+     * @return string|false image blob
105
+     */
106
+    public function getTouchIcon($app) {
107
+        try {
108
+            $icon = $this->renderAppIcon($app, 512);
109
+            if ($icon === false) {
110
+                return false;
111
+            }
112
+            $icon->setImageFormat("png32");
113
+            $data = $icon->getImageBlob();
114
+            $icon->destroy();
115
+            return $data;
116
+        } catch (\ImagickException $e) {
117
+            return false;
118
+        }
119
+    }
120
+
121
+    /**
122
+     * Render app icon on themed background color
123
+     * fallback to logo
124
+     *
125
+     * @param $app string app name
126
+     * @param $size int size of the icon in px
127
+     * @return Imagick|false
128
+     */
129
+    public function renderAppIcon($app, $size) {
130
+        $appIcon = $this->util->getAppIcon($app);
131
+        if ($appIcon === false) {
132
+            return false;
133
+        }
134
+        if ($appIcon instanceof ISimpleFile) {
135
+            $appIconContent = $appIcon->getContent();
136
+            $mime = $appIcon->getMimeType();
137
+        } else {
138
+            $appIconContent = file_get_contents($appIcon);
139
+            $mime = mime_content_type($appIcon);
140
+        }
141
+
142
+        if ($appIconContent === false || $appIconContent === "") {
143
+            return false;
144
+        }
145
+
146
+        $color = $this->themingDefaults->getColorPrimary();
147
+
148
+        // generate background image with rounded corners
149
+        $background = '<?xml version="1.0" encoding="UTF-8"?>' .
150
+            '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:cc="http://creativecommons.org/ns#" width="512" height="512" xmlns:xlink="http://www.w3.org/1999/xlink">' .
151
+            '<rect x="0" y="0" rx="100" ry="100" width="512" height="512" style="fill:' . $color . ';" />' .
152
+            '</svg>';
153
+        // resize svg magic as this seems broken in Imagemagick
154
+        if ($mime === "image/svg+xml" || substr($appIconContent, 0, 4) === "<svg") {
155
+            if (substr($appIconContent, 0, 5) !== "<?xml") {
156
+                $svg = "<?xml version=\"1.0\"?>".$appIconContent;
157
+            } else {
158
+                $svg = $appIconContent;
159
+            }
160
+            $tmp = new Imagick();
161
+            $tmp->readImageBlob($svg);
162
+            $x = $tmp->getImageWidth();
163
+            $y = $tmp->getImageHeight();
164
+            $res = $tmp->getImageResolution();
165
+            $tmp->destroy();
166
+
167
+            if ($x > $y) {
168
+                $max = $x;
169
+            } else {
170
+                $max = $y;
171
+            }
172
+
173
+            // convert svg to resized image
174
+            $appIconFile = new Imagick();
175
+            $resX = (int)(512 * $res['x'] / $max * 2.53);
176
+            $resY = (int)(512 * $res['y'] / $max * 2.53);
177
+            $appIconFile->setResolution($resX, $resY);
178
+            $appIconFile->setBackgroundColor(new ImagickPixel('transparent'));
179
+            $appIconFile->readImageBlob($svg);
180
+
181
+            /**
182
+             * invert app icons for bright primary colors
183
+             * the default nextcloud logo will not be inverted to black
184
+             */
185
+            if ($this->util->invertTextColor($color)
186
+                && !$appIcon instanceof ISimpleFile
187
+                && $app !== "core"
188
+            ) {
189
+                $appIconFile->negateImage(false);
190
+            }
191
+            $appIconFile->scaleImage(512, 512, true);
192
+        } else {
193
+            $appIconFile = new Imagick();
194
+            $appIconFile->setBackgroundColor(new ImagickPixel('transparent'));
195
+            $appIconFile->readImageBlob($appIconContent);
196
+            $appIconFile->scaleImage(512, 512, true);
197
+        }
198
+        // offset for icon positioning
199
+        $border_w = (int)($appIconFile->getImageWidth() * 0.05);
200
+        $border_h = (int)($appIconFile->getImageHeight() * 0.05);
201
+        $innerWidth = ($appIconFile->getImageWidth() - $border_w * 2);
202
+        $innerHeight = ($appIconFile->getImageHeight() - $border_h * 2);
203
+        $appIconFile->adaptiveResizeImage($innerWidth, $innerHeight);
204
+        // center icon
205
+        $offset_w = 512 / 2 - $innerWidth / 2;
206
+        $offset_h = 512 / 2 - $innerHeight / 2;
207
+
208
+        $finalIconFile = new Imagick();
209
+        $finalIconFile->setBackgroundColor(new ImagickPixel('transparent'));
210
+        $finalIconFile->readImageBlob($background);
211
+        $finalIconFile->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
212
+        $finalIconFile->setImageArtifact('compose:args', "1,0,-0.5,0.5");
213
+        $finalIconFile->compositeImage($appIconFile, Imagick::COMPOSITE_ATOP, $offset_w, $offset_h);
214
+        $finalIconFile->setImageFormat('png24');
215
+        if (defined("Imagick::INTERPOLATE_BICUBIC") === true) {
216
+            $filter = Imagick::INTERPOLATE_BICUBIC;
217
+        } else {
218
+            $filter = Imagick::FILTER_LANCZOS;
219
+        }
220
+        $finalIconFile->resizeImage($size, $size, $filter, 1, false);
221
+
222
+        $appIconFile->destroy();
223
+        return $finalIconFile;
224
+    }
225
+
226
+    public function colorSvg($app, $image) {
227
+        try {
228
+            $imageFile = $this->util->getAppImage($app, $image);
229
+        } catch (AppPathNotFoundException $e) {
230
+            return false;
231
+        }
232
+        $svg = file_get_contents($imageFile);
233
+        if ($svg !== false && $svg !== "") {
234
+            $color = $this->util->elementColor($this->themingDefaults->getColorPrimary());
235
+            $svg = $this->util->colorizeSvg($svg, $color);
236
+            return $svg;
237
+        } else {
238
+            return false;
239
+        }
240
+    }
241 241
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -74,19 +74,19 @@  discard block
 block discarded – undo
74 74
 			$icon->setImageFormat("png32");
75 75
 
76 76
 			$clone = clone $icon;
77
-			$clone->scaleImage(16,0);
77
+			$clone->scaleImage(16, 0);
78 78
 			$favicon->addImage($clone);
79 79
 
80 80
 			$clone = clone $icon;
81
-			$clone->scaleImage(32,0);
81
+			$clone->scaleImage(32, 0);
82 82
 			$favicon->addImage($clone);
83 83
 
84 84
 			$clone = clone $icon;
85
-			$clone->scaleImage(64,0);
85
+			$clone->scaleImage(64, 0);
86 86
 			$favicon->addImage($clone);
87 87
 
88 88
 			$clone = clone $icon;
89
-			$clone->scaleImage(128,0);
89
+			$clone->scaleImage(128, 0);
90 90
 			$favicon->addImage($clone);
91 91
 
92 92
 			$data = $favicon->getImagesBlob();
@@ -146,9 +146,9 @@  discard block
 block discarded – undo
146 146
 		$color = $this->themingDefaults->getColorPrimary();
147 147
 
148 148
 		// generate background image with rounded corners
149
-		$background = '<?xml version="1.0" encoding="UTF-8"?>' .
150
-			'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:cc="http://creativecommons.org/ns#" width="512" height="512" xmlns:xlink="http://www.w3.org/1999/xlink">' .
151
-			'<rect x="0" y="0" rx="100" ry="100" width="512" height="512" style="fill:' . $color . ';" />' .
149
+		$background = '<?xml version="1.0" encoding="UTF-8"?>'.
150
+			'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:cc="http://creativecommons.org/ns#" width="512" height="512" xmlns:xlink="http://www.w3.org/1999/xlink">'.
151
+			'<rect x="0" y="0" rx="100" ry="100" width="512" height="512" style="fill:'.$color.';" />'.
152 152
 			'</svg>';
153 153
 		// resize svg magic as this seems broken in Imagemagick
154 154
 		if ($mime === "image/svg+xml" || substr($appIconContent, 0, 4) === "<svg") {
@@ -172,8 +172,8 @@  discard block
 block discarded – undo
172 172
 
173 173
 			// convert svg to resized image
174 174
 			$appIconFile = new Imagick();
175
-			$resX = (int)(512 * $res['x'] / $max * 2.53);
176
-			$resY = (int)(512 * $res['y'] / $max * 2.53);
175
+			$resX = (int) (512 * $res['x'] / $max * 2.53);
176
+			$resY = (int) (512 * $res['y'] / $max * 2.53);
177 177
 			$appIconFile->setResolution($resX, $resY);
178 178
 			$appIconFile->setBackgroundColor(new ImagickPixel('transparent'));
179 179
 			$appIconFile->readImageBlob($svg);
@@ -196,8 +196,8 @@  discard block
 block discarded – undo
196 196
 			$appIconFile->scaleImage(512, 512, true);
197 197
 		}
198 198
 		// offset for icon positioning
199
-		$border_w = (int)($appIconFile->getImageWidth() * 0.05);
200
-		$border_h = (int)($appIconFile->getImageHeight() * 0.05);
199
+		$border_w = (int) ($appIconFile->getImageWidth() * 0.05);
200
+		$border_h = (int) ($appIconFile->getImageHeight() * 0.05);
201 201
 		$innerWidth = ($appIconFile->getImageWidth() - $border_w * 2);
202 202
 		$innerHeight = ($appIconFile->getImageHeight() - $border_h * 2);
203 203
 		$appIconFile->adaptiveResizeImage($innerWidth, $innerHeight);
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifier.php 2 patches
Indentation   +206 added lines, -206 removed lines patch added patch discarded remove patch
@@ -37,237 +37,237 @@
 block discarded – undo
37 37
 use OCP\Notification\INotifier;
38 38
 
39 39
 class Notifier implements INotifier {
40
-	/** @var IFactory */
41
-	protected $factory;
42
-	/** @var IManager */
43
-	protected $contactsManager;
44
-	/** @var IURLGenerator */
45
-	protected $url;
46
-	/** @var array */
47
-	protected $federatedContacts;
48
-	/** @var ICloudIdManager */
49
-	protected $cloudIdManager;
40
+    /** @var IFactory */
41
+    protected $factory;
42
+    /** @var IManager */
43
+    protected $contactsManager;
44
+    /** @var IURLGenerator */
45
+    protected $url;
46
+    /** @var array */
47
+    protected $federatedContacts;
48
+    /** @var ICloudIdManager */
49
+    protected $cloudIdManager;
50 50
 
51
-	/**
52
-	 * @param IFactory $factory
53
-	 * @param IManager $contactsManager
54
-	 * @param IURLGenerator $url
55
-	 * @param ICloudIdManager $cloudIdManager
56
-	 */
57
-	public function __construct(IFactory $factory, IManager $contactsManager, IURLGenerator $url, ICloudIdManager $cloudIdManager) {
58
-		$this->factory = $factory;
59
-		$this->contactsManager = $contactsManager;
60
-		$this->url = $url;
61
-		$this->cloudIdManager = $cloudIdManager;
62
-	}
51
+    /**
52
+     * @param IFactory $factory
53
+     * @param IManager $contactsManager
54
+     * @param IURLGenerator $url
55
+     * @param ICloudIdManager $cloudIdManager
56
+     */
57
+    public function __construct(IFactory $factory, IManager $contactsManager, IURLGenerator $url, ICloudIdManager $cloudIdManager) {
58
+        $this->factory = $factory;
59
+        $this->contactsManager = $contactsManager;
60
+        $this->url = $url;
61
+        $this->cloudIdManager = $cloudIdManager;
62
+    }
63 63
 
64
-	/**
65
-	 * Identifier of the notifier, only use [a-z0-9_]
66
-	 *
67
-	 * @return string
68
-	 * @since 17.0.0
69
-	 */
70
-	public function getID(): string {
71
-		return 'federatedfilesharing';
72
-	}
64
+    /**
65
+     * Identifier of the notifier, only use [a-z0-9_]
66
+     *
67
+     * @return string
68
+     * @since 17.0.0
69
+     */
70
+    public function getID(): string {
71
+        return 'federatedfilesharing';
72
+    }
73 73
 
74
-	/**
75
-	 * Human readable name describing the notifier
76
-	 *
77
-	 * @return string
78
-	 * @since 17.0.0
79
-	 */
80
-	public function getName(): string {
81
-		return $this->factory->get('federatedfilesharing')->t('Federated sharing');
82
-	}
74
+    /**
75
+     * Human readable name describing the notifier
76
+     *
77
+     * @return string
78
+     * @since 17.0.0
79
+     */
80
+    public function getName(): string {
81
+        return $this->factory->get('federatedfilesharing')->t('Federated sharing');
82
+    }
83 83
 
84
-	/**
85
-	 * @param INotification $notification
86
-	 * @param string $languageCode The code of the language that should be used to prepare the notification
87
-	 * @return INotification
88
-	 * @throws \InvalidArgumentException
89
-	 */
90
-	public function prepare(INotification $notification, string $languageCode): INotification {
91
-		if ($notification->getApp() !== 'files_sharing' || $notification->getObjectType() !== 'remote_share') {
92
-			// Not my app => throw
93
-			throw new \InvalidArgumentException();
94
-		}
84
+    /**
85
+     * @param INotification $notification
86
+     * @param string $languageCode The code of the language that should be used to prepare the notification
87
+     * @return INotification
88
+     * @throws \InvalidArgumentException
89
+     */
90
+    public function prepare(INotification $notification, string $languageCode): INotification {
91
+        if ($notification->getApp() !== 'files_sharing' || $notification->getObjectType() !== 'remote_share') {
92
+            // Not my app => throw
93
+            throw new \InvalidArgumentException();
94
+        }
95 95
 
96
-		// Read the language from the notification
97
-		$l = $this->factory->get('files_sharing', $languageCode);
96
+        // Read the language from the notification
97
+        $l = $this->factory->get('files_sharing', $languageCode);
98 98
 
99
-		switch ($notification->getSubject()) {
100
-			// Deal with known subjects
101
-			case 'remote_share':
102
-				$notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
99
+        switch ($notification->getSubject()) {
100
+            // Deal with known subjects
101
+            case 'remote_share':
102
+                $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
103 103
 
104
-				$params = $notification->getSubjectParameters();
105
-				if ($params[0] !== $params[1] && $params[1] !== null) {
106
-					$remoteInitiator = $this->createRemoteUser($params[0]);
107
-					$remoteOwner = $this->createRemoteUser($params[1]);
108
-					$params[3] = $remoteInitiator['name'] . '@' . $remoteInitiator['server'];
109
-					$params[4] = $remoteOwner['name'] . '@' . $remoteOwner['server'];
104
+                $params = $notification->getSubjectParameters();
105
+                if ($params[0] !== $params[1] && $params[1] !== null) {
106
+                    $remoteInitiator = $this->createRemoteUser($params[0]);
107
+                    $remoteOwner = $this->createRemoteUser($params[1]);
108
+                    $params[3] = $remoteInitiator['name'] . '@' . $remoteInitiator['server'];
109
+                    $params[4] = $remoteOwner['name'] . '@' . $remoteOwner['server'];
110 110
 
111
-					$notification->setParsedSubject(
112
-						$l->t('You received "%3$s" as a remote share from %4$s (%1$s) (on behalf of %5$s (%2$s))', $params)
113
-					);
111
+                    $notification->setParsedSubject(
112
+                        $l->t('You received "%3$s" as a remote share from %4$s (%1$s) (on behalf of %5$s (%2$s))', $params)
113
+                    );
114 114
 
115
-					$notification->setRichSubject(
116
-						$l->t('You received {share} as a remote share from {user} (on behalf of {behalf})'),
117
-						[
118
-							'share' => [
119
-								'type' => 'pending-federated-share',
120
-								'id' => $notification->getObjectId(),
121
-								'name' => $params[2],
122
-							],
123
-							'user' => $remoteInitiator,
124
-							'behalf' => $remoteOwner,
125
-						]
126
-					);
127
-				} else {
128
-					$remoteOwner = $this->createRemoteUser($params[0]);
129
-					$params[3] = $remoteOwner['name'] . '@' . $remoteOwner['server'];
115
+                    $notification->setRichSubject(
116
+                        $l->t('You received {share} as a remote share from {user} (on behalf of {behalf})'),
117
+                        [
118
+                            'share' => [
119
+                                'type' => 'pending-federated-share',
120
+                                'id' => $notification->getObjectId(),
121
+                                'name' => $params[2],
122
+                            ],
123
+                            'user' => $remoteInitiator,
124
+                            'behalf' => $remoteOwner,
125
+                        ]
126
+                    );
127
+                } else {
128
+                    $remoteOwner = $this->createRemoteUser($params[0]);
129
+                    $params[3] = $remoteOwner['name'] . '@' . $remoteOwner['server'];
130 130
 
131
-					$notification->setParsedSubject(
132
-						$l->t('You received "%3$s" as a remote share from %4$s (%1$s)', $params)
133
-					);
131
+                    $notification->setParsedSubject(
132
+                        $l->t('You received "%3$s" as a remote share from %4$s (%1$s)', $params)
133
+                    );
134 134
 
135 135
 
136
-					$notification->setRichSubject(
137
-						$l->t('You received {share} as a remote share from {user}'),
138
-						[
139
-							'share' => [
140
-								'type' => 'pending-federated-share',
141
-								'id' => $notification->getObjectId(),
142
-								'name' => $params[2],
143
-							],
144
-							'user' => $remoteOwner,
145
-						]
146
-					);
147
-				}
136
+                    $notification->setRichSubject(
137
+                        $l->t('You received {share} as a remote share from {user}'),
138
+                        [
139
+                            'share' => [
140
+                                'type' => 'pending-federated-share',
141
+                                'id' => $notification->getObjectId(),
142
+                                'name' => $params[2],
143
+                            ],
144
+                            'user' => $remoteOwner,
145
+                        ]
146
+                    );
147
+                }
148 148
 
149
-				// Deal with the actions for a known subject
150
-				foreach ($notification->getActions() as $action) {
151
-					switch ($action->getLabel()) {
152
-						case 'accept':
153
-							$action->setParsedLabel(
154
-								$l->t('Accept')
155
-							)
156
-								->setPrimary(true);
157
-							break;
149
+                // Deal with the actions for a known subject
150
+                foreach ($notification->getActions() as $action) {
151
+                    switch ($action->getLabel()) {
152
+                        case 'accept':
153
+                            $action->setParsedLabel(
154
+                                $l->t('Accept')
155
+                            )
156
+                                ->setPrimary(true);
157
+                            break;
158 158
 
159
-						case 'decline':
160
-							$action->setParsedLabel(
161
-								$l->t('Decline')
162
-							);
163
-							break;
164
-					}
159
+                        case 'decline':
160
+                            $action->setParsedLabel(
161
+                                $l->t('Decline')
162
+                            );
163
+                            break;
164
+                    }
165 165
 
166
-					$notification->addParsedAction($action);
167
-				}
168
-				return $notification;
166
+                    $notification->addParsedAction($action);
167
+                }
168
+                return $notification;
169 169
 
170
-			default:
171
-				// Unknown subject => Unknown notification => throw
172
-				throw new \InvalidArgumentException();
173
-		}
174
-	}
170
+            default:
171
+                // Unknown subject => Unknown notification => throw
172
+                throw new \InvalidArgumentException();
173
+        }
174
+    }
175 175
 
176
-	/**
177
-	 * @param string $cloudId
178
-	 * @return array
179
-	 */
180
-	protected function createRemoteUser($cloudId, $displayName = null) {
181
-		try {
182
-			$resolvedId = $this->cloudIdManager->resolveCloudId($cloudId);
183
-			if ($displayName === null) {
184
-				$displayName = $this->getDisplayName($resolvedId);
185
-			}
186
-			$user = $resolvedId->getUser();
187
-			$server = $resolvedId->getRemote();
188
-		} catch (HintException $e) {
189
-			$user = $cloudId;
190
-			$displayName = $cloudId;
191
-			$server = '';
192
-		}
176
+    /**
177
+     * @param string $cloudId
178
+     * @return array
179
+     */
180
+    protected function createRemoteUser($cloudId, $displayName = null) {
181
+        try {
182
+            $resolvedId = $this->cloudIdManager->resolveCloudId($cloudId);
183
+            if ($displayName === null) {
184
+                $displayName = $this->getDisplayName($resolvedId);
185
+            }
186
+            $user = $resolvedId->getUser();
187
+            $server = $resolvedId->getRemote();
188
+        } catch (HintException $e) {
189
+            $user = $cloudId;
190
+            $displayName = $cloudId;
191
+            $server = '';
192
+        }
193 193
 
194
-		return [
195
-			'type' => 'user',
196
-			'id' => $user,
197
-			'name' => $displayName,
198
-			'server' => $server,
199
-		];
200
-	}
194
+        return [
195
+            'type' => 'user',
196
+            'id' => $user,
197
+            'name' => $displayName,
198
+            'server' => $server,
199
+        ];
200
+    }
201 201
 
202
-	/**
203
-	 * Try to find the user in the contacts
204
-	 *
205
-	 * @param ICloudId $cloudId
206
-	 * @return string
207
-	 */
208
-	protected function getDisplayName(ICloudId $cloudId): string {
209
-		$server = $cloudId->getRemote();
210
-		$user = $cloudId->getUser();
211
-		if (strpos($server, 'http://') === 0) {
212
-			$server = substr($server, strlen('http://'));
213
-		} elseif (strpos($server, 'https://') === 0) {
214
-			$server = substr($server, strlen('https://'));
215
-		}
202
+    /**
203
+     * Try to find the user in the contacts
204
+     *
205
+     * @param ICloudId $cloudId
206
+     * @return string
207
+     */
208
+    protected function getDisplayName(ICloudId $cloudId): string {
209
+        $server = $cloudId->getRemote();
210
+        $user = $cloudId->getUser();
211
+        if (strpos($server, 'http://') === 0) {
212
+            $server = substr($server, strlen('http://'));
213
+        } elseif (strpos($server, 'https://') === 0) {
214
+            $server = substr($server, strlen('https://'));
215
+        }
216 216
 
217
-		try {
218
-			// contains protocol in the  ID
219
-			return $this->getDisplayNameFromContact($cloudId->getId());
220
-		} catch (\OutOfBoundsException $e) {
221
-		}
217
+        try {
218
+            // contains protocol in the  ID
219
+            return $this->getDisplayNameFromContact($cloudId->getId());
220
+        } catch (\OutOfBoundsException $e) {
221
+        }
222 222
 
223
-		try {
224
-			// does not include protocol, as stored in addressbooks
225
-			return $this->getDisplayNameFromContact($cloudId->getDisplayId());
226
-		} catch (\OutOfBoundsException $e) {
227
-		}
223
+        try {
224
+            // does not include protocol, as stored in addressbooks
225
+            return $this->getDisplayNameFromContact($cloudId->getDisplayId());
226
+        } catch (\OutOfBoundsException $e) {
227
+        }
228 228
 
229
-		try {
230
-			return $this->getDisplayNameFromContact($user . '@http://' . $server);
231
-		} catch (\OutOfBoundsException $e) {
232
-		}
229
+        try {
230
+            return $this->getDisplayNameFromContact($user . '@http://' . $server);
231
+        } catch (\OutOfBoundsException $e) {
232
+        }
233 233
 
234
-		try {
235
-			return $this->getDisplayNameFromContact($user . '@https://' . $server);
236
-		} catch (\OutOfBoundsException $e) {
237
-		}
234
+        try {
235
+            return $this->getDisplayNameFromContact($user . '@https://' . $server);
236
+        } catch (\OutOfBoundsException $e) {
237
+        }
238 238
 
239
-		return $cloudId->getId();
240
-	}
239
+        return $cloudId->getId();
240
+    }
241 241
 
242
-	/**
243
-	 * Try to find the user in the contacts
244
-	 *
245
-	 * @param string $federatedCloudId
246
-	 * @return string
247
-	 * @throws \OutOfBoundsException when there is no contact for the id
248
-	 */
249
-	protected function getDisplayNameFromContact($federatedCloudId) {
250
-		if (isset($this->federatedContacts[$federatedCloudId])) {
251
-			if ($this->federatedContacts[$federatedCloudId] !== '') {
252
-				return $this->federatedContacts[$federatedCloudId];
253
-			} else {
254
-				throw new \OutOfBoundsException('No contact found for federated cloud id');
255
-			}
256
-		}
242
+    /**
243
+     * Try to find the user in the contacts
244
+     *
245
+     * @param string $federatedCloudId
246
+     * @return string
247
+     * @throws \OutOfBoundsException when there is no contact for the id
248
+     */
249
+    protected function getDisplayNameFromContact($federatedCloudId) {
250
+        if (isset($this->federatedContacts[$federatedCloudId])) {
251
+            if ($this->federatedContacts[$federatedCloudId] !== '') {
252
+                return $this->federatedContacts[$federatedCloudId];
253
+            } else {
254
+                throw new \OutOfBoundsException('No contact found for federated cloud id');
255
+            }
256
+        }
257 257
 
258
-		$addressBookEntries = $this->contactsManager->search($federatedCloudId, ['CLOUD']);
259
-		foreach ($addressBookEntries as $entry) {
260
-			if (isset($entry['CLOUD'])) {
261
-				foreach ($entry['CLOUD'] as $cloudID) {
262
-					if ($cloudID === $federatedCloudId) {
263
-						$this->federatedContacts[$federatedCloudId] = $entry['FN'];
264
-						return $entry['FN'];
265
-					}
266
-				}
267
-			}
268
-		}
258
+        $addressBookEntries = $this->contactsManager->search($federatedCloudId, ['CLOUD']);
259
+        foreach ($addressBookEntries as $entry) {
260
+            if (isset($entry['CLOUD'])) {
261
+                foreach ($entry['CLOUD'] as $cloudID) {
262
+                    if ($cloudID === $federatedCloudId) {
263
+                        $this->federatedContacts[$federatedCloudId] = $entry['FN'];
264
+                        return $entry['FN'];
265
+                    }
266
+                }
267
+            }
268
+        }
269 269
 
270
-		$this->federatedContacts[$federatedCloudId] = '';
271
-		throw new \OutOfBoundsException('No contact found for federated cloud id');
272
-	}
270
+        $this->federatedContacts[$federatedCloudId] = '';
271
+        throw new \OutOfBoundsException('No contact found for federated cloud id');
272
+    }
273 273
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -105,8 +105,8 @@  discard block
 block discarded – undo
105 105
 				if ($params[0] !== $params[1] && $params[1] !== null) {
106 106
 					$remoteInitiator = $this->createRemoteUser($params[0]);
107 107
 					$remoteOwner = $this->createRemoteUser($params[1]);
108
-					$params[3] = $remoteInitiator['name'] . '@' . $remoteInitiator['server'];
109
-					$params[4] = $remoteOwner['name'] . '@' . $remoteOwner['server'];
108
+					$params[3] = $remoteInitiator['name'].'@'.$remoteInitiator['server'];
109
+					$params[4] = $remoteOwner['name'].'@'.$remoteOwner['server'];
110 110
 
111 111
 					$notification->setParsedSubject(
112 112
 						$l->t('You received "%3$s" as a remote share from %4$s (%1$s) (on behalf of %5$s (%2$s))', $params)
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 					);
127 127
 				} else {
128 128
 					$remoteOwner = $this->createRemoteUser($params[0]);
129
-					$params[3] = $remoteOwner['name'] . '@' . $remoteOwner['server'];
129
+					$params[3] = $remoteOwner['name'].'@'.$remoteOwner['server'];
130 130
 
131 131
 					$notification->setParsedSubject(
132 132
 						$l->t('You received "%3$s" as a remote share from %4$s (%1$s)', $params)
@@ -227,12 +227,12 @@  discard block
 block discarded – undo
227 227
 		}
228 228
 
229 229
 		try {
230
-			return $this->getDisplayNameFromContact($user . '@http://' . $server);
230
+			return $this->getDisplayNameFromContact($user.'@http://'.$server);
231 231
 		} catch (\OutOfBoundsException $e) {
232 232
 		}
233 233
 
234 234
 		try {
235
-			return $this->getDisplayNameFromContact($user . '@https://' . $server);
235
+			return $this->getDisplayNameFromContact($user.'@https://'.$server);
236 236
 		} catch (\OutOfBoundsException $e) {
237 237
 		}
238 238
 
Please login to merge, or discard this patch.
apps/files/lib/Controller/ApiController.php 2 patches
Indentation   +267 added lines, -267 removed lines patch added patch discarded remove patch
@@ -61,286 +61,286 @@
 block discarded – undo
61 61
  * @package OCA\Files\Controller
62 62
  */
63 63
 class ApiController extends Controller {
64
-	/** @var TagService */
65
-	private $tagService;
66
-	/** @var IManager * */
67
-	private $shareManager;
68
-	/** @var IPreview */
69
-	private $previewManager;
70
-	/** IUserSession */
71
-	private $userSession;
72
-	/** IConfig */
73
-	private $config;
74
-	/** @var Folder */
75
-	private $userFolder;
64
+    /** @var TagService */
65
+    private $tagService;
66
+    /** @var IManager * */
67
+    private $shareManager;
68
+    /** @var IPreview */
69
+    private $previewManager;
70
+    /** IUserSession */
71
+    private $userSession;
72
+    /** IConfig */
73
+    private $config;
74
+    /** @var Folder */
75
+    private $userFolder;
76 76
 
77
-	/**
78
-	 * @param string $appName
79
-	 * @param IRequest $request
80
-	 * @param IUserSession $userSession
81
-	 * @param TagService $tagService
82
-	 * @param IPreview $previewManager
83
-	 * @param IManager $shareManager
84
-	 * @param IConfig $config
85
-	 * @param Folder $userFolder
86
-	 */
87
-	public function __construct($appName,
88
-								IRequest $request,
89
-								IUserSession $userSession,
90
-								TagService $tagService,
91
-								IPreview $previewManager,
92
-								IManager $shareManager,
93
-								IConfig $config,
94
-								Folder $userFolder) {
95
-		parent::__construct($appName, $request);
96
-		$this->userSession = $userSession;
97
-		$this->tagService = $tagService;
98
-		$this->previewManager = $previewManager;
99
-		$this->shareManager = $shareManager;
100
-		$this->config = $config;
101
-		$this->userFolder = $userFolder;
102
-	}
77
+    /**
78
+     * @param string $appName
79
+     * @param IRequest $request
80
+     * @param IUserSession $userSession
81
+     * @param TagService $tagService
82
+     * @param IPreview $previewManager
83
+     * @param IManager $shareManager
84
+     * @param IConfig $config
85
+     * @param Folder $userFolder
86
+     */
87
+    public function __construct($appName,
88
+                                IRequest $request,
89
+                                IUserSession $userSession,
90
+                                TagService $tagService,
91
+                                IPreview $previewManager,
92
+                                IManager $shareManager,
93
+                                IConfig $config,
94
+                                Folder $userFolder) {
95
+        parent::__construct($appName, $request);
96
+        $this->userSession = $userSession;
97
+        $this->tagService = $tagService;
98
+        $this->previewManager = $previewManager;
99
+        $this->shareManager = $shareManager;
100
+        $this->config = $config;
101
+        $this->userFolder = $userFolder;
102
+    }
103 103
 
104
-	/**
105
-	 * Gets a thumbnail of the specified file
106
-	 *
107
-	 * @since API version 1.0
108
-	 *
109
-	 * @NoAdminRequired
110
-	 * @NoCSRFRequired
111
-	 * @StrictCookieRequired
112
-	 *
113
-	 * @param int $x
114
-	 * @param int $y
115
-	 * @param string $file URL-encoded filename
116
-	 * @return DataResponse|FileDisplayResponse
117
-	 */
118
-	public function getThumbnail($x, $y, $file) {
119
-		if ($x < 1 || $y < 1) {
120
-			return new DataResponse(['message' => 'Requested size must be numeric and a positive value.'], Http::STATUS_BAD_REQUEST);
121
-		}
104
+    /**
105
+     * Gets a thumbnail of the specified file
106
+     *
107
+     * @since API version 1.0
108
+     *
109
+     * @NoAdminRequired
110
+     * @NoCSRFRequired
111
+     * @StrictCookieRequired
112
+     *
113
+     * @param int $x
114
+     * @param int $y
115
+     * @param string $file URL-encoded filename
116
+     * @return DataResponse|FileDisplayResponse
117
+     */
118
+    public function getThumbnail($x, $y, $file) {
119
+        if ($x < 1 || $y < 1) {
120
+            return new DataResponse(['message' => 'Requested size must be numeric and a positive value.'], Http::STATUS_BAD_REQUEST);
121
+        }
122 122
 
123
-		try {
124
-			$file = $this->userFolder->get($file);
125
-			if ($file instanceof Folder) {
126
-				throw new NotFoundException();
127
-			}
123
+        try {
124
+            $file = $this->userFolder->get($file);
125
+            if ($file instanceof Folder) {
126
+                throw new NotFoundException();
127
+            }
128 128
 
129
-			/** @var File $file */
130
-			$preview = $this->previewManager->getPreview($file, $x, $y, true);
129
+            /** @var File $file */
130
+            $preview = $this->previewManager->getPreview($file, $x, $y, true);
131 131
 
132
-			return new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => $preview->getMimeType()]);
133
-		} catch (NotFoundException $e) {
134
-			return new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND);
135
-		} catch (\Exception $e) {
136
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
137
-		}
138
-	}
132
+            return new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => $preview->getMimeType()]);
133
+        } catch (NotFoundException $e) {
134
+            return new DataResponse(['message' => 'File not found.'], Http::STATUS_NOT_FOUND);
135
+        } catch (\Exception $e) {
136
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
137
+        }
138
+    }
139 139
 
140
-	/**
141
-	 * Updates the info of the specified file path
142
-	 * The passed tags are absolute, which means they will
143
-	 * replace the actual tag selection.
144
-	 *
145
-	 * @NoAdminRequired
146
-	 *
147
-	 * @param string $path path
148
-	 * @param array|string $tags array of tags
149
-	 * @return DataResponse
150
-	 */
151
-	public function updateFileTags($path, $tags = null) {
152
-		$result = [];
153
-		// if tags specified or empty array, update tags
154
-		if (!is_null($tags)) {
155
-			try {
156
-				$this->tagService->updateFileTags($path, $tags);
157
-			} catch (\OCP\Files\NotFoundException $e) {
158
-				return new DataResponse([
159
-					'message' => $e->getMessage()
160
-				], Http::STATUS_NOT_FOUND);
161
-			} catch (\OCP\Files\StorageNotAvailableException $e) {
162
-				return new DataResponse([
163
-					'message' => $e->getMessage()
164
-				], Http::STATUS_SERVICE_UNAVAILABLE);
165
-			} catch (\Exception $e) {
166
-				return new DataResponse([
167
-					'message' => $e->getMessage()
168
-				], Http::STATUS_NOT_FOUND);
169
-			}
170
-			$result['tags'] = $tags;
171
-		}
172
-		return new DataResponse($result);
173
-	}
140
+    /**
141
+     * Updates the info of the specified file path
142
+     * The passed tags are absolute, which means they will
143
+     * replace the actual tag selection.
144
+     *
145
+     * @NoAdminRequired
146
+     *
147
+     * @param string $path path
148
+     * @param array|string $tags array of tags
149
+     * @return DataResponse
150
+     */
151
+    public function updateFileTags($path, $tags = null) {
152
+        $result = [];
153
+        // if tags specified or empty array, update tags
154
+        if (!is_null($tags)) {
155
+            try {
156
+                $this->tagService->updateFileTags($path, $tags);
157
+            } catch (\OCP\Files\NotFoundException $e) {
158
+                return new DataResponse([
159
+                    'message' => $e->getMessage()
160
+                ], Http::STATUS_NOT_FOUND);
161
+            } catch (\OCP\Files\StorageNotAvailableException $e) {
162
+                return new DataResponse([
163
+                    'message' => $e->getMessage()
164
+                ], Http::STATUS_SERVICE_UNAVAILABLE);
165
+            } catch (\Exception $e) {
166
+                return new DataResponse([
167
+                    'message' => $e->getMessage()
168
+                ], Http::STATUS_NOT_FOUND);
169
+            }
170
+            $result['tags'] = $tags;
171
+        }
172
+        return new DataResponse($result);
173
+    }
174 174
 
175
-	/**
176
-	 * @param \OCP\Files\Node[] $nodes
177
-	 * @return array
178
-	 */
179
-	private function formatNodes(array $nodes) {
180
-		return array_values(array_map(function (Node $node) {
181
-			/** @var \OC\Files\Node\Node $shareTypes */
182
-			$shareTypes = $this->getShareTypes($node);
183
-			$file = \OCA\Files\Helper::formatFileInfo($node->getFileInfo());
184
-			$file['hasPreview'] = $this->previewManager->isAvailable($node);
185
-			$parts = explode('/', dirname($node->getPath()), 4);
186
-			if (isset($parts[3])) {
187
-				$file['path'] = '/' . $parts[3];
188
-			} else {
189
-				$file['path'] = '/';
190
-			}
191
-			if (!empty($shareTypes)) {
192
-				$file['shareTypes'] = $shareTypes;
193
-			}
194
-			return $file;
195
-		}, $nodes));
196
-	}
175
+    /**
176
+     * @param \OCP\Files\Node[] $nodes
177
+     * @return array
178
+     */
179
+    private function formatNodes(array $nodes) {
180
+        return array_values(array_map(function (Node $node) {
181
+            /** @var \OC\Files\Node\Node $shareTypes */
182
+            $shareTypes = $this->getShareTypes($node);
183
+            $file = \OCA\Files\Helper::formatFileInfo($node->getFileInfo());
184
+            $file['hasPreview'] = $this->previewManager->isAvailable($node);
185
+            $parts = explode('/', dirname($node->getPath()), 4);
186
+            if (isset($parts[3])) {
187
+                $file['path'] = '/' . $parts[3];
188
+            } else {
189
+                $file['path'] = '/';
190
+            }
191
+            if (!empty($shareTypes)) {
192
+                $file['shareTypes'] = $shareTypes;
193
+            }
194
+            return $file;
195
+        }, $nodes));
196
+    }
197 197
 
198
-	/**
199
-	 * Returns a list of recently modifed files.
200
-	 *
201
-	 * @NoAdminRequired
202
-	 *
203
-	 * @return DataResponse
204
-	 */
205
-	public function getRecentFiles() {
206
-		$nodes = $this->userFolder->getRecent(100);
207
-		$files = $this->formatNodes($nodes);
208
-		return new DataResponse(['files' => $files]);
209
-	}
198
+    /**
199
+     * Returns a list of recently modifed files.
200
+     *
201
+     * @NoAdminRequired
202
+     *
203
+     * @return DataResponse
204
+     */
205
+    public function getRecentFiles() {
206
+        $nodes = $this->userFolder->getRecent(100);
207
+        $files = $this->formatNodes($nodes);
208
+        return new DataResponse(['files' => $files]);
209
+    }
210 210
 
211
-	/**
212
-	 * Return a list of share types for outgoing shares
213
-	 *
214
-	 * @param Node $node file node
215
-	 *
216
-	 * @return int[] array of share types
217
-	 */
218
-	private function getShareTypes(Node $node) {
219
-		$userId = $this->userSession->getUser()->getUID();
220
-		$shareTypes = [];
221
-		$requestedShareTypes = [
222
-			IShare::TYPE_USER,
223
-			IShare::TYPE_GROUP,
224
-			IShare::TYPE_LINK,
225
-			IShare::TYPE_REMOTE,
226
-			IShare::TYPE_EMAIL,
227
-			IShare::TYPE_ROOM,
228
-			IShare::TYPE_DECK,
229
-		];
230
-		foreach ($requestedShareTypes as $requestedShareType) {
231
-			// one of each type is enough to find out about the types
232
-			$shares = $this->shareManager->getSharesBy(
233
-				$userId,
234
-				$requestedShareType,
235
-				$node,
236
-				false,
237
-				1
238
-			);
239
-			if (!empty($shares)) {
240
-				$shareTypes[] = $requestedShareType;
241
-			}
242
-		}
243
-		return $shareTypes;
244
-	}
211
+    /**
212
+     * Return a list of share types for outgoing shares
213
+     *
214
+     * @param Node $node file node
215
+     *
216
+     * @return int[] array of share types
217
+     */
218
+    private function getShareTypes(Node $node) {
219
+        $userId = $this->userSession->getUser()->getUID();
220
+        $shareTypes = [];
221
+        $requestedShareTypes = [
222
+            IShare::TYPE_USER,
223
+            IShare::TYPE_GROUP,
224
+            IShare::TYPE_LINK,
225
+            IShare::TYPE_REMOTE,
226
+            IShare::TYPE_EMAIL,
227
+            IShare::TYPE_ROOM,
228
+            IShare::TYPE_DECK,
229
+        ];
230
+        foreach ($requestedShareTypes as $requestedShareType) {
231
+            // one of each type is enough to find out about the types
232
+            $shares = $this->shareManager->getSharesBy(
233
+                $userId,
234
+                $requestedShareType,
235
+                $node,
236
+                false,
237
+                1
238
+            );
239
+            if (!empty($shares)) {
240
+                $shareTypes[] = $requestedShareType;
241
+            }
242
+        }
243
+        return $shareTypes;
244
+    }
245 245
 
246
-	/**
247
-	 * Change the default sort mode
248
-	 *
249
-	 * @NoAdminRequired
250
-	 *
251
-	 * @param string $mode
252
-	 * @param string $direction
253
-	 * @return Response
254
-	 * @throws \OCP\PreConditionNotMetException
255
-	 */
256
-	public function updateFileSorting($mode, $direction) {
257
-		$allowedMode = ['name', 'size', 'mtime'];
258
-		$allowedDirection = ['asc', 'desc'];
259
-		if (!in_array($mode, $allowedMode) || !in_array($direction, $allowedDirection)) {
260
-			$response = new Response();
261
-			$response->setStatus(Http::STATUS_UNPROCESSABLE_ENTITY);
262
-			return $response;
263
-		}
264
-		$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'file_sorting', $mode);
265
-		$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'file_sorting_direction', $direction);
266
-		return new Response();
267
-	}
246
+    /**
247
+     * Change the default sort mode
248
+     *
249
+     * @NoAdminRequired
250
+     *
251
+     * @param string $mode
252
+     * @param string $direction
253
+     * @return Response
254
+     * @throws \OCP\PreConditionNotMetException
255
+     */
256
+    public function updateFileSorting($mode, $direction) {
257
+        $allowedMode = ['name', 'size', 'mtime'];
258
+        $allowedDirection = ['asc', 'desc'];
259
+        if (!in_array($mode, $allowedMode) || !in_array($direction, $allowedDirection)) {
260
+            $response = new Response();
261
+            $response->setStatus(Http::STATUS_UNPROCESSABLE_ENTITY);
262
+            return $response;
263
+        }
264
+        $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'file_sorting', $mode);
265
+        $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'file_sorting_direction', $direction);
266
+        return new Response();
267
+    }
268 268
 
269
-	/**
270
-	 * Toggle default for showing/hiding hidden files
271
-	 *
272
-	 * @NoAdminRequired
273
-	 *
274
-	 * @param bool $show
275
-	 * @return Response
276
-	 * @throws \OCP\PreConditionNotMetException
277
-	 */
278
-	public function showHiddenFiles($show) {
279
-		$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', (int)$show);
280
-		return new Response();
281
-	}
269
+    /**
270
+     * Toggle default for showing/hiding hidden files
271
+     *
272
+     * @NoAdminRequired
273
+     *
274
+     * @param bool $show
275
+     * @return Response
276
+     * @throws \OCP\PreConditionNotMetException
277
+     */
278
+    public function showHiddenFiles($show) {
279
+        $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', (int)$show);
280
+        return new Response();
281
+    }
282 282
 
283
-	/**
284
-	 * Toggle default for files grid view
285
-	 *
286
-	 * @NoAdminRequired
287
-	 *
288
-	 * @param bool $show
289
-	 * @return Response
290
-	 * @throws \OCP\PreConditionNotMetException
291
-	 */
292
-	public function showGridView($show) {
293
-		$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', (int)$show);
294
-		return new Response();
295
-	}
283
+    /**
284
+     * Toggle default for files grid view
285
+     *
286
+     * @NoAdminRequired
287
+     *
288
+     * @param bool $show
289
+     * @return Response
290
+     * @throws \OCP\PreConditionNotMetException
291
+     */
292
+    public function showGridView($show) {
293
+        $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', (int)$show);
294
+        return new Response();
295
+    }
296 296
 
297
-	/**
298
-	 * Get default settings for the grid view
299
-	 *
300
-	 * @NoAdminRequired
301
-	 */
302
-	public function getGridView() {
303
-		$status = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', '0') === '1';
304
-		return new JSONResponse(['gridview' => $status]);
305
-	}
297
+    /**
298
+     * Get default settings for the grid view
299
+     *
300
+     * @NoAdminRequired
301
+     */
302
+    public function getGridView() {
303
+        $status = $this->config->getUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', '0') === '1';
304
+        return new JSONResponse(['gridview' => $status]);
305
+    }
306 306
 
307
-	/**
308
-	 * Toggle default for showing/hiding xxx folder
309
-	 *
310
-	 * @NoAdminRequired
311
-	 *
312
-	 * @param int $show
313
-	 * @param string $key the key of the folder
314
-	 *
315
-	 * @return Response
316
-	 * @throws \OCP\PreConditionNotMetException
317
-	 */
318
-	public function toggleShowFolder(int $show, string $key) {
319
-		// ensure the edited key exists
320
-		$navItems = \OCA\Files\App::getNavigationManager()->getAll();
321
-		foreach ($navItems as $item) {
322
-			// check if data is valid
323
-			if (($show === 0 || $show === 1) && isset($item['expandedState']) && $key === $item['expandedState']) {
324
-				$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', $key, $show);
325
-				return new Response();
326
-			}
327
-		}
328
-		$response = new Response();
329
-		$response->setStatus(Http::STATUS_FORBIDDEN);
330
-		return $response;
331
-	}
307
+    /**
308
+     * Toggle default for showing/hiding xxx folder
309
+     *
310
+     * @NoAdminRequired
311
+     *
312
+     * @param int $show
313
+     * @param string $key the key of the folder
314
+     *
315
+     * @return Response
316
+     * @throws \OCP\PreConditionNotMetException
317
+     */
318
+    public function toggleShowFolder(int $show, string $key) {
319
+        // ensure the edited key exists
320
+        $navItems = \OCA\Files\App::getNavigationManager()->getAll();
321
+        foreach ($navItems as $item) {
322
+            // check if data is valid
323
+            if (($show === 0 || $show === 1) && isset($item['expandedState']) && $key === $item['expandedState']) {
324
+                $this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', $key, $show);
325
+                return new Response();
326
+            }
327
+        }
328
+        $response = new Response();
329
+        $response->setStatus(Http::STATUS_FORBIDDEN);
330
+        return $response;
331
+    }
332 332
 
333
-	/**
334
-	 * Get sorting-order for custom sorting
335
-	 *
336
-	 * @NoAdminRequired
337
-	 *
338
-	 * @param string $folderpath
339
-	 * @return string
340
-	 * @throws \OCP\Files\NotFoundException
341
-	 */
342
-	public function getNodeType($folderpath) {
343
-		$node = $this->userFolder->get($folderpath);
344
-		return $node->getType();
345
-	}
333
+    /**
334
+     * Get sorting-order for custom sorting
335
+     *
336
+     * @NoAdminRequired
337
+     *
338
+     * @param string $folderpath
339
+     * @return string
340
+     * @throws \OCP\Files\NotFoundException
341
+     */
342
+    public function getNodeType($folderpath) {
343
+        $node = $this->userFolder->get($folderpath);
344
+        return $node->getType();
345
+    }
346 346
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -177,14 +177,14 @@  discard block
 block discarded – undo
177 177
 	 * @return array
178 178
 	 */
179 179
 	private function formatNodes(array $nodes) {
180
-		return array_values(array_map(function (Node $node) {
180
+		return array_values(array_map(function(Node $node) {
181 181
 			/** @var \OC\Files\Node\Node $shareTypes */
182 182
 			$shareTypes = $this->getShareTypes($node);
183 183
 			$file = \OCA\Files\Helper::formatFileInfo($node->getFileInfo());
184 184
 			$file['hasPreview'] = $this->previewManager->isAvailable($node);
185 185
 			$parts = explode('/', dirname($node->getPath()), 4);
186 186
 			if (isset($parts[3])) {
187
-				$file['path'] = '/' . $parts[3];
187
+				$file['path'] = '/'.$parts[3];
188 188
 			} else {
189 189
 				$file['path'] = '/';
190 190
 			}
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
 	 * @throws \OCP\PreConditionNotMetException
277 277
 	 */
278 278
 	public function showHiddenFiles($show) {
279
-		$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', (int)$show);
279
+		$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_hidden', (int) $show);
280 280
 		return new Response();
281 281
 	}
282 282
 
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 	 * @throws \OCP\PreConditionNotMetException
291 291
 	 */
292 292
 	public function showGridView($show) {
293
-		$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', (int)$show);
293
+		$this->config->setUserValue($this->userSession->getUser()->getUID(), 'files', 'show_grid', (int) $show);
294 294
 		return new Response();
295 295
 	}
296 296
 
Please login to merge, or discard this patch.
apps/federation/lib/Controller/SettingsController.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -33,90 +33,90 @@
 block discarded – undo
33 33
 
34 34
 class SettingsController extends Controller {
35 35
 
36
-	/** @var IL10N */
37
-	private $l;
36
+    /** @var IL10N */
37
+    private $l;
38 38
 
39
-	/** @var  TrustedServers */
40
-	private $trustedServers;
39
+    /** @var  TrustedServers */
40
+    private $trustedServers;
41 41
 
42
-	/**
43
-	 * @param string $AppName
44
-	 * @param IRequest $request
45
-	 * @param IL10N $l10n
46
-	 * @param TrustedServers $trustedServers
47
-	 */
48
-	public function __construct($AppName,
49
-								IRequest $request,
50
-								IL10N $l10n,
51
-								TrustedServers $trustedServers
52
-	) {
53
-		parent::__construct($AppName, $request);
54
-		$this->l = $l10n;
55
-		$this->trustedServers = $trustedServers;
56
-	}
42
+    /**
43
+     * @param string $AppName
44
+     * @param IRequest $request
45
+     * @param IL10N $l10n
46
+     * @param TrustedServers $trustedServers
47
+     */
48
+    public function __construct($AppName,
49
+                                IRequest $request,
50
+                                IL10N $l10n,
51
+                                TrustedServers $trustedServers
52
+    ) {
53
+        parent::__construct($AppName, $request);
54
+        $this->l = $l10n;
55
+        $this->trustedServers = $trustedServers;
56
+    }
57 57
 
58 58
 
59
-	/**
60
-	 * add server to the list of trusted Nextclouds
61
-	 *
62
-	 * @param string $url
63
-	 * @return DataResponse
64
-	 * @throws HintException
65
-	 */
66
-	public function addServer($url) {
67
-		$this->checkServer($url);
68
-		$id = $this->trustedServers->addServer($url);
59
+    /**
60
+     * add server to the list of trusted Nextclouds
61
+     *
62
+     * @param string $url
63
+     * @return DataResponse
64
+     * @throws HintException
65
+     */
66
+    public function addServer($url) {
67
+        $this->checkServer($url);
68
+        $id = $this->trustedServers->addServer($url);
69 69
 
70
-		return new DataResponse(
71
-			[
72
-				'url' => $url,
73
-				'id' => $id,
74
-				'message' => $this->l->t('Added to the list of trusted servers')
75
-			]
76
-		);
77
-	}
70
+        return new DataResponse(
71
+            [
72
+                'url' => $url,
73
+                'id' => $id,
74
+                'message' => $this->l->t('Added to the list of trusted servers')
75
+            ]
76
+        );
77
+    }
78 78
 
79
-	/**
80
-	 * add server to the list of trusted Nextclouds
81
-	 *
82
-	 * @param int $id
83
-	 * @return DataResponse
84
-	 */
85
-	public function removeServer($id) {
86
-		$this->trustedServers->removeServer($id);
87
-		return new DataResponse();
88
-	}
79
+    /**
80
+     * add server to the list of trusted Nextclouds
81
+     *
82
+     * @param int $id
83
+     * @return DataResponse
84
+     */
85
+    public function removeServer($id) {
86
+        $this->trustedServers->removeServer($id);
87
+        return new DataResponse();
88
+    }
89 89
 
90
-	/**
91
-	 * enable/disable to automatically add servers to the list of trusted servers
92
-	 * once a federated share was created and accepted successfully
93
-	 *
94
-	 * @param bool $autoAddServers
95
-	 */
96
-	public function autoAddServers($autoAddServers) {
97
-		$this->trustedServers->setAutoAddServers($autoAddServers);
98
-	}
90
+    /**
91
+     * enable/disable to automatically add servers to the list of trusted servers
92
+     * once a federated share was created and accepted successfully
93
+     *
94
+     * @param bool $autoAddServers
95
+     */
96
+    public function autoAddServers($autoAddServers) {
97
+        $this->trustedServers->setAutoAddServers($autoAddServers);
98
+    }
99 99
 
100
-	/**
101
-	 * check if the server should be added to the list of trusted servers or not
102
-	 *
103
-	 * @param string $url
104
-	 * @return bool
105
-	 * @throws HintException
106
-	 */
107
-	protected function checkServer($url) {
108
-		if ($this->trustedServers->isTrustedServer($url) === true) {
109
-			$message = 'Server is already in the list of trusted servers.';
110
-			$hint = $this->l->t('Server is already in the list of trusted servers.');
111
-			throw new HintException($message, $hint);
112
-		}
100
+    /**
101
+     * check if the server should be added to the list of trusted servers or not
102
+     *
103
+     * @param string $url
104
+     * @return bool
105
+     * @throws HintException
106
+     */
107
+    protected function checkServer($url) {
108
+        if ($this->trustedServers->isTrustedServer($url) === true) {
109
+            $message = 'Server is already in the list of trusted servers.';
110
+            $hint = $this->l->t('Server is already in the list of trusted servers.');
111
+            throw new HintException($message, $hint);
112
+        }
113 113
 
114
-		if ($this->trustedServers->isOwnCloudServer($url) === false) {
115
-			$message = 'No server to federate with found';
116
-			$hint = $this->l->t('No server to federate with found');
117
-			throw new HintException($message, $hint);
118
-		}
114
+        if ($this->trustedServers->isOwnCloudServer($url) === false) {
115
+            $message = 'No server to federate with found';
116
+            $hint = $this->l->t('No server to federate with found');
117
+            throw new HintException($message, $hint);
118
+        }
119 119
 
120
-		return true;
121
-	}
120
+        return true;
121
+    }
122 122
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/Activity.php 1 patch
Indentation   +352 added lines, -352 removed lines patch added patch discarded remove patch
@@ -38,356 +38,356 @@
 block discarded – undo
38 38
 
39 39
 class Activity implements IProvider {
40 40
 
41
-	/** @var IFactory */
42
-	protected $languageFactory;
43
-
44
-	/** @var IL10N */
45
-	protected $l;
46
-
47
-	/** @var IURLGenerator */
48
-	protected $url;
49
-
50
-	/** @var IManager */
51
-	protected $activityManager;
52
-
53
-	/** @var IUserManager */
54
-	protected $userManager;
55
-	/** @var IContactsManager */
56
-	protected $contactsManager;
57
-
58
-	/** @var array */
59
-	protected $displayNames = [];
60
-
61
-	/** @var array */
62
-	protected $contactNames = [];
63
-
64
-	public const SUBJECT_SHARED_EMAIL_SELF = 'shared_with_email_self';
65
-	public const SUBJECT_SHARED_EMAIL_BY = 'shared_with_email_by';
66
-	public const SUBJECT_SHARED_EMAIL_PASSWORD_SEND = 'shared_with_email_password_send';
67
-	public const SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF = 'shared_with_email_password_send_self';
68
-	public const SUBJECT_UNSHARED_EMAIL_SELF = 'unshared_with_email_self';
69
-	public const SUBJECT_UNSHARED_EMAIL_BY = 'unshared_with_email_by';
70
-
71
-	/**
72
-	 * @param IFactory $languageFactory
73
-	 * @param IURLGenerator $url
74
-	 * @param IManager $activityManager
75
-	 * @param IUserManager $userManager
76
-	 * @param IContactsManager $contactsManager
77
-	 */
78
-	public function __construct(IFactory $languageFactory, IURLGenerator $url, IManager $activityManager, IUserManager $userManager, IContactsManager $contactsManager) {
79
-		$this->languageFactory = $languageFactory;
80
-		$this->url = $url;
81
-		$this->activityManager = $activityManager;
82
-		$this->userManager = $userManager;
83
-		$this->contactsManager = $contactsManager;
84
-	}
85
-
86
-	/**
87
-	 * @param string $language
88
-	 * @param IEvent $event
89
-	 * @param IEvent|null $previousEvent
90
-	 * @return IEvent
91
-	 * @throws \InvalidArgumentException
92
-	 * @since 11.0.0
93
-	 */
94
-	public function parse($language, IEvent $event, IEvent $previousEvent = null) {
95
-		if ($event->getApp() !== 'sharebymail') {
96
-			throw new \InvalidArgumentException();
97
-		}
98
-
99
-		$this->l = $this->languageFactory->get('sharebymail', $language);
100
-
101
-		if ($this->activityManager->isFormattingFilteredObject()) {
102
-			try {
103
-				return $this->parseShortVersion($event);
104
-			} catch (\InvalidArgumentException $e) {
105
-				// Ignore and simply use the long version...
106
-			}
107
-		}
108
-
109
-		return $this->parseLongVersion($event);
110
-	}
111
-
112
-	/**
113
-	 * @param IEvent $event
114
-	 * @return IEvent
115
-	 * @throws \InvalidArgumentException
116
-	 * @since 11.0.0
117
-	 */
118
-	public function parseShortVersion(IEvent $event) {
119
-		$parsedParameters = $this->getParsedParameters($event);
120
-
121
-		if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
122
-			$event->setParsedSubject($this->l->t('Shared with %1$s', [
123
-				$parsedParameters['email']['name'],
124
-			]))
125
-				->setRichSubject($this->l->t('Shared with {email}'), [
126
-					'email' => $parsedParameters['email'],
127
-				]);
128
-			if ($this->activityManager->getRequirePNG()) {
129
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
130
-			} else {
131
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
132
-			}
133
-		} elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
134
-			$event->setParsedSubject($this->l->t('Shared with %1$s by %2$s', [
135
-				$parsedParameters['email']['name'],
136
-				$parsedParameters['actor']['name'],
137
-			]))
138
-				->setRichSubject($this->l->t('Shared with {email} by {actor}'), [
139
-					'email' => $parsedParameters['email'],
140
-					'actor' => $parsedParameters['actor'],
141
-				]);
142
-			if ($this->activityManager->getRequirePNG()) {
143
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
144
-			} else {
145
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
146
-			}
147
-		} elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_SELF) {
148
-			$event->setParsedSubject($this->l->t('Unshared from %1$s', [
149
-				$parsedParameters['email']['name'],
150
-			]))
151
-				->setRichSubject($this->l->t('Unshared from {email}'), [
152
-					'email' => $parsedParameters['email'],
153
-				]);
154
-			if ($this->activityManager->getRequirePNG()) {
155
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
156
-			} else {
157
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
158
-			}
159
-		} elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_BY) {
160
-			$event->setParsedSubject($this->l->t('Unshared from %1$s by %2$s', [
161
-				$parsedParameters['email']['name'],
162
-				$parsedParameters['actor']['name'],
163
-			]))
164
-				->setRichSubject($this->l->t('Unshared from {email} by {actor}'), [
165
-					'email' => $parsedParameters['email'],
166
-					'actor' => $parsedParameters['actor'],
167
-				]);
168
-			if ($this->activityManager->getRequirePNG()) {
169
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
170
-			} else {
171
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
172
-			}
173
-		} elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
174
-			$event->setParsedSubject($this->l->t('Password for mail share sent to %1$s', [
175
-				$parsedParameters['email']['name']
176
-			]))
177
-				->setRichSubject($this->l->t('Password for mail share sent to {email}'), [
178
-					'email' => $parsedParameters['email']
179
-				]);
180
-			if ($this->activityManager->getRequirePNG()) {
181
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
182
-			} else {
183
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
184
-			}
185
-		} elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
186
-			$event->setParsedSubject($this->l->t('Password for mail share sent to you'))
187
-				->setRichSubject($this->l->t('Password for mail share sent to you'));
188
-			if ($this->activityManager->getRequirePNG()) {
189
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
190
-			} else {
191
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
192
-			}
193
-		} else {
194
-			throw new \InvalidArgumentException();
195
-		}
196
-
197
-		return $event;
198
-	}
199
-
200
-	/**
201
-	 * @param IEvent $event
202
-	 * @return IEvent
203
-	 * @throws \InvalidArgumentException
204
-	 * @since 11.0.0
205
-	 */
206
-	public function parseLongVersion(IEvent $event) {
207
-		$parsedParameters = $this->getParsedParameters($event);
208
-
209
-		if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
210
-			$event->setParsedSubject($this->l->t('You shared %1$s with %2$s by mail', [
211
-				$parsedParameters['file']['path'],
212
-				$parsedParameters['email']['name'],
213
-			]))
214
-				->setRichSubject($this->l->t('You shared {file} with {email} by mail'), $parsedParameters);
215
-			if ($this->activityManager->getRequirePNG()) {
216
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
217
-			} else {
218
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
219
-			}
220
-		} elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
221
-			$event->setParsedSubject($this->l->t('%3$s shared %1$s with %2$s by mail', [
222
-				$parsedParameters['file']['path'],
223
-				$parsedParameters['email']['name'],
224
-				$parsedParameters['actor']['name'],
225
-			]))
226
-				->setRichSubject($this->l->t('{actor} shared {file} with {email} by mail'), $parsedParameters);
227
-			if ($this->activityManager->getRequirePNG()) {
228
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
229
-			} else {
230
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
231
-			}
232
-		} elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_SELF) {
233
-			$event->setParsedSubject($this->l->t('You unshared %1$s from %2$s by mail', [
234
-				$parsedParameters['file']['path'],
235
-				$parsedParameters['email']['name'],
236
-			]))
237
-				->setRichSubject($this->l->t('You unshared {file} from {email} by mail'), $parsedParameters);
238
-			if ($this->activityManager->getRequirePNG()) {
239
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
240
-			} else {
241
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
242
-			}
243
-		} elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_BY) {
244
-			$event->setParsedSubject($this->l->t('%3$s unshared %1$s from %2$s by mail', [
245
-				$parsedParameters['file']['path'],
246
-				$parsedParameters['email']['name'],
247
-				$parsedParameters['actor']['name'],
248
-			]))
249
-				->setRichSubject($this->l->t('{actor} unshared {file} from {email} by mail'), $parsedParameters);
250
-			if ($this->activityManager->getRequirePNG()) {
251
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
252
-			} else {
253
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
254
-			}
255
-		} elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
256
-			$event->setParsedSubject($this->l->t('Password to access %1$s was sent to %2s', [
257
-				$parsedParameters['file']['path'],
258
-				$parsedParameters['email']['name']
259
-			]))
260
-				->setRichSubject($this->l->t('Password to access {file} was sent to {email}'), $parsedParameters);
261
-			if ($this->activityManager->getRequirePNG()) {
262
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
263
-			} else {
264
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
265
-			}
266
-		} elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
267
-			$event->setParsedSubject(
268
-				$this->l->t('Password to access %1$s was sent to you',
269
-					[$parsedParameters['file']['path']]))
270
-				->setRichSubject($this->l->t('Password to access {file} was sent to you'), $parsedParameters);
271
-			if ($this->activityManager->getRequirePNG()) {
272
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
273
-			} else {
274
-				$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
275
-			}
276
-		} else {
277
-			throw new \InvalidArgumentException();
278
-		}
279
-
280
-		return $event;
281
-	}
282
-
283
-	protected function getParsedParameters(IEvent $event) {
284
-		$subject = $event->getSubject();
285
-		$parameters = $event->getSubjectParameters();
286
-
287
-		switch ($subject) {
288
-			case self::SUBJECT_SHARED_EMAIL_SELF:
289
-			case self::SUBJECT_UNSHARED_EMAIL_SELF:
290
-				return [
291
-					'file' => $this->generateFileParameter($event->getObjectId(), $parameters[0]),
292
-					'email' => $this->generateEmailParameter($parameters[1]),
293
-				];
294
-			case self::SUBJECT_SHARED_EMAIL_BY:
295
-			case self::SUBJECT_UNSHARED_EMAIL_BY:
296
-				return [
297
-					'file' => $this->generateFileParameter($event->getObjectId(), $parameters[0]),
298
-					'email' => $this->generateEmailParameter($parameters[1]),
299
-					'actor' => $this->generateUserParameter($parameters[2]),
300
-				];
301
-			case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND:
302
-				return [
303
-					'file' => $this->generateFileParameter($event->getObjectId(), $parameters[0]),
304
-					'email' => $this->generateEmailParameter($parameters[1]),
305
-				];
306
-			case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF:
307
-				return [
308
-					'file' => $this->generateFileParameter($event->getObjectId(), $parameters[0]),
309
-				];
310
-		}
311
-		throw new \InvalidArgumentException();
312
-	}
313
-
314
-	/**
315
-	 * @param int $id
316
-	 * @param string $path
317
-	 * @return array
318
-	 */
319
-	protected function generateFileParameter($id, $path) {
320
-		return [
321
-			'type' => 'file',
322
-			'id' => $id,
323
-			'name' => basename($path),
324
-			'path' => trim($path, '/'),
325
-			'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $id]),
326
-		];
327
-	}
328
-
329
-	/**
330
-	 * @param string $email
331
-	 * @return array
332
-	 */
333
-	protected function generateEmailParameter($email) {
334
-		if (!isset($this->contactNames[$email])) {
335
-			$this->contactNames[$email] = $this->getContactName($email);
336
-		}
337
-
338
-		return [
339
-			'type' => 'email',
340
-			'id' => $email,
341
-			'name' => $this->contactNames[$email],
342
-		];
343
-	}
344
-
345
-	/**
346
-	 * @param string $uid
347
-	 * @return array
348
-	 */
349
-	protected function generateUserParameter($uid) {
350
-		if (!isset($this->displayNames[$uid])) {
351
-			$this->displayNames[$uid] = $this->getDisplayName($uid);
352
-		}
353
-
354
-		return [
355
-			'type' => 'user',
356
-			'id' => $uid,
357
-			'name' => $this->displayNames[$uid],
358
-		];
359
-	}
360
-
361
-	/**
362
-	 * @param string $email
363
-	 * @return string
364
-	 */
365
-	protected function getContactName($email) {
366
-		$addressBookContacts = $this->contactsManager->search($email, ['EMAIL']);
367
-
368
-		foreach ($addressBookContacts as $contact) {
369
-			if (isset($contact['isLocalSystemBook'])) {
370
-				continue;
371
-			}
372
-
373
-			if (in_array($email, $contact['EMAIL'])) {
374
-				return $contact['FN'];
375
-			}
376
-		}
377
-
378
-		return $email;
379
-	}
380
-
381
-	/**
382
-	 * @param string $uid
383
-	 * @return string
384
-	 */
385
-	protected function getDisplayName($uid) {
386
-		$user = $this->userManager->get($uid);
387
-		if ($user instanceof IUser) {
388
-			return $user->getDisplayName();
389
-		} else {
390
-			return $uid;
391
-		}
392
-	}
41
+    /** @var IFactory */
42
+    protected $languageFactory;
43
+
44
+    /** @var IL10N */
45
+    protected $l;
46
+
47
+    /** @var IURLGenerator */
48
+    protected $url;
49
+
50
+    /** @var IManager */
51
+    protected $activityManager;
52
+
53
+    /** @var IUserManager */
54
+    protected $userManager;
55
+    /** @var IContactsManager */
56
+    protected $contactsManager;
57
+
58
+    /** @var array */
59
+    protected $displayNames = [];
60
+
61
+    /** @var array */
62
+    protected $contactNames = [];
63
+
64
+    public const SUBJECT_SHARED_EMAIL_SELF = 'shared_with_email_self';
65
+    public const SUBJECT_SHARED_EMAIL_BY = 'shared_with_email_by';
66
+    public const SUBJECT_SHARED_EMAIL_PASSWORD_SEND = 'shared_with_email_password_send';
67
+    public const SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF = 'shared_with_email_password_send_self';
68
+    public const SUBJECT_UNSHARED_EMAIL_SELF = 'unshared_with_email_self';
69
+    public const SUBJECT_UNSHARED_EMAIL_BY = 'unshared_with_email_by';
70
+
71
+    /**
72
+     * @param IFactory $languageFactory
73
+     * @param IURLGenerator $url
74
+     * @param IManager $activityManager
75
+     * @param IUserManager $userManager
76
+     * @param IContactsManager $contactsManager
77
+     */
78
+    public function __construct(IFactory $languageFactory, IURLGenerator $url, IManager $activityManager, IUserManager $userManager, IContactsManager $contactsManager) {
79
+        $this->languageFactory = $languageFactory;
80
+        $this->url = $url;
81
+        $this->activityManager = $activityManager;
82
+        $this->userManager = $userManager;
83
+        $this->contactsManager = $contactsManager;
84
+    }
85
+
86
+    /**
87
+     * @param string $language
88
+     * @param IEvent $event
89
+     * @param IEvent|null $previousEvent
90
+     * @return IEvent
91
+     * @throws \InvalidArgumentException
92
+     * @since 11.0.0
93
+     */
94
+    public function parse($language, IEvent $event, IEvent $previousEvent = null) {
95
+        if ($event->getApp() !== 'sharebymail') {
96
+            throw new \InvalidArgumentException();
97
+        }
98
+
99
+        $this->l = $this->languageFactory->get('sharebymail', $language);
100
+
101
+        if ($this->activityManager->isFormattingFilteredObject()) {
102
+            try {
103
+                return $this->parseShortVersion($event);
104
+            } catch (\InvalidArgumentException $e) {
105
+                // Ignore and simply use the long version...
106
+            }
107
+        }
108
+
109
+        return $this->parseLongVersion($event);
110
+    }
111
+
112
+    /**
113
+     * @param IEvent $event
114
+     * @return IEvent
115
+     * @throws \InvalidArgumentException
116
+     * @since 11.0.0
117
+     */
118
+    public function parseShortVersion(IEvent $event) {
119
+        $parsedParameters = $this->getParsedParameters($event);
120
+
121
+        if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
122
+            $event->setParsedSubject($this->l->t('Shared with %1$s', [
123
+                $parsedParameters['email']['name'],
124
+            ]))
125
+                ->setRichSubject($this->l->t('Shared with {email}'), [
126
+                    'email' => $parsedParameters['email'],
127
+                ]);
128
+            if ($this->activityManager->getRequirePNG()) {
129
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
130
+            } else {
131
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
132
+            }
133
+        } elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
134
+            $event->setParsedSubject($this->l->t('Shared with %1$s by %2$s', [
135
+                $parsedParameters['email']['name'],
136
+                $parsedParameters['actor']['name'],
137
+            ]))
138
+                ->setRichSubject($this->l->t('Shared with {email} by {actor}'), [
139
+                    'email' => $parsedParameters['email'],
140
+                    'actor' => $parsedParameters['actor'],
141
+                ]);
142
+            if ($this->activityManager->getRequirePNG()) {
143
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
144
+            } else {
145
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
146
+            }
147
+        } elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_SELF) {
148
+            $event->setParsedSubject($this->l->t('Unshared from %1$s', [
149
+                $parsedParameters['email']['name'],
150
+            ]))
151
+                ->setRichSubject($this->l->t('Unshared from {email}'), [
152
+                    'email' => $parsedParameters['email'],
153
+                ]);
154
+            if ($this->activityManager->getRequirePNG()) {
155
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
156
+            } else {
157
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
158
+            }
159
+        } elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_BY) {
160
+            $event->setParsedSubject($this->l->t('Unshared from %1$s by %2$s', [
161
+                $parsedParameters['email']['name'],
162
+                $parsedParameters['actor']['name'],
163
+            ]))
164
+                ->setRichSubject($this->l->t('Unshared from {email} by {actor}'), [
165
+                    'email' => $parsedParameters['email'],
166
+                    'actor' => $parsedParameters['actor'],
167
+                ]);
168
+            if ($this->activityManager->getRequirePNG()) {
169
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
170
+            } else {
171
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
172
+            }
173
+        } elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
174
+            $event->setParsedSubject($this->l->t('Password for mail share sent to %1$s', [
175
+                $parsedParameters['email']['name']
176
+            ]))
177
+                ->setRichSubject($this->l->t('Password for mail share sent to {email}'), [
178
+                    'email' => $parsedParameters['email']
179
+                ]);
180
+            if ($this->activityManager->getRequirePNG()) {
181
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
182
+            } else {
183
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
184
+            }
185
+        } elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
186
+            $event->setParsedSubject($this->l->t('Password for mail share sent to you'))
187
+                ->setRichSubject($this->l->t('Password for mail share sent to you'));
188
+            if ($this->activityManager->getRequirePNG()) {
189
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
190
+            } else {
191
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
192
+            }
193
+        } else {
194
+            throw new \InvalidArgumentException();
195
+        }
196
+
197
+        return $event;
198
+    }
199
+
200
+    /**
201
+     * @param IEvent $event
202
+     * @return IEvent
203
+     * @throws \InvalidArgumentException
204
+     * @since 11.0.0
205
+     */
206
+    public function parseLongVersion(IEvent $event) {
207
+        $parsedParameters = $this->getParsedParameters($event);
208
+
209
+        if ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_SELF) {
210
+            $event->setParsedSubject($this->l->t('You shared %1$s with %2$s by mail', [
211
+                $parsedParameters['file']['path'],
212
+                $parsedParameters['email']['name'],
213
+            ]))
214
+                ->setRichSubject($this->l->t('You shared {file} with {email} by mail'), $parsedParameters);
215
+            if ($this->activityManager->getRequirePNG()) {
216
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
217
+            } else {
218
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
219
+            }
220
+        } elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_BY) {
221
+            $event->setParsedSubject($this->l->t('%3$s shared %1$s with %2$s by mail', [
222
+                $parsedParameters['file']['path'],
223
+                $parsedParameters['email']['name'],
224
+                $parsedParameters['actor']['name'],
225
+            ]))
226
+                ->setRichSubject($this->l->t('{actor} shared {file} with {email} by mail'), $parsedParameters);
227
+            if ($this->activityManager->getRequirePNG()) {
228
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
229
+            } else {
230
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
231
+            }
232
+        } elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_SELF) {
233
+            $event->setParsedSubject($this->l->t('You unshared %1$s from %2$s by mail', [
234
+                $parsedParameters['file']['path'],
235
+                $parsedParameters['email']['name'],
236
+            ]))
237
+                ->setRichSubject($this->l->t('You unshared {file} from {email} by mail'), $parsedParameters);
238
+            if ($this->activityManager->getRequirePNG()) {
239
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
240
+            } else {
241
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
242
+            }
243
+        } elseif ($event->getSubject() === self::SUBJECT_UNSHARED_EMAIL_BY) {
244
+            $event->setParsedSubject($this->l->t('%3$s unshared %1$s from %2$s by mail', [
245
+                $parsedParameters['file']['path'],
246
+                $parsedParameters['email']['name'],
247
+                $parsedParameters['actor']['name'],
248
+            ]))
249
+                ->setRichSubject($this->l->t('{actor} unshared {file} from {email} by mail'), $parsedParameters);
250
+            if ($this->activityManager->getRequirePNG()) {
251
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
252
+            } else {
253
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
254
+            }
255
+        } elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND) {
256
+            $event->setParsedSubject($this->l->t('Password to access %1$s was sent to %2s', [
257
+                $parsedParameters['file']['path'],
258
+                $parsedParameters['email']['name']
259
+            ]))
260
+                ->setRichSubject($this->l->t('Password to access {file} was sent to {email}'), $parsedParameters);
261
+            if ($this->activityManager->getRequirePNG()) {
262
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
263
+            } else {
264
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
265
+            }
266
+        } elseif ($event->getSubject() === self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF) {
267
+            $event->setParsedSubject(
268
+                $this->l->t('Password to access %1$s was sent to you',
269
+                    [$parsedParameters['file']['path']]))
270
+                ->setRichSubject($this->l->t('Password to access {file} was sent to you'), $parsedParameters);
271
+            if ($this->activityManager->getRequirePNG()) {
272
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.png')));
273
+            } else {
274
+                $event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
275
+            }
276
+        } else {
277
+            throw new \InvalidArgumentException();
278
+        }
279
+
280
+        return $event;
281
+    }
282
+
283
+    protected function getParsedParameters(IEvent $event) {
284
+        $subject = $event->getSubject();
285
+        $parameters = $event->getSubjectParameters();
286
+
287
+        switch ($subject) {
288
+            case self::SUBJECT_SHARED_EMAIL_SELF:
289
+            case self::SUBJECT_UNSHARED_EMAIL_SELF:
290
+                return [
291
+                    'file' => $this->generateFileParameter($event->getObjectId(), $parameters[0]),
292
+                    'email' => $this->generateEmailParameter($parameters[1]),
293
+                ];
294
+            case self::SUBJECT_SHARED_EMAIL_BY:
295
+            case self::SUBJECT_UNSHARED_EMAIL_BY:
296
+                return [
297
+                    'file' => $this->generateFileParameter($event->getObjectId(), $parameters[0]),
298
+                    'email' => $this->generateEmailParameter($parameters[1]),
299
+                    'actor' => $this->generateUserParameter($parameters[2]),
300
+                ];
301
+            case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND:
302
+                return [
303
+                    'file' => $this->generateFileParameter($event->getObjectId(), $parameters[0]),
304
+                    'email' => $this->generateEmailParameter($parameters[1]),
305
+                ];
306
+            case self::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF:
307
+                return [
308
+                    'file' => $this->generateFileParameter($event->getObjectId(), $parameters[0]),
309
+                ];
310
+        }
311
+        throw new \InvalidArgumentException();
312
+    }
313
+
314
+    /**
315
+     * @param int $id
316
+     * @param string $path
317
+     * @return array
318
+     */
319
+    protected function generateFileParameter($id, $path) {
320
+        return [
321
+            'type' => 'file',
322
+            'id' => $id,
323
+            'name' => basename($path),
324
+            'path' => trim($path, '/'),
325
+            'link' => $this->url->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $id]),
326
+        ];
327
+    }
328
+
329
+    /**
330
+     * @param string $email
331
+     * @return array
332
+     */
333
+    protected function generateEmailParameter($email) {
334
+        if (!isset($this->contactNames[$email])) {
335
+            $this->contactNames[$email] = $this->getContactName($email);
336
+        }
337
+
338
+        return [
339
+            'type' => 'email',
340
+            'id' => $email,
341
+            'name' => $this->contactNames[$email],
342
+        ];
343
+    }
344
+
345
+    /**
346
+     * @param string $uid
347
+     * @return array
348
+     */
349
+    protected function generateUserParameter($uid) {
350
+        if (!isset($this->displayNames[$uid])) {
351
+            $this->displayNames[$uid] = $this->getDisplayName($uid);
352
+        }
353
+
354
+        return [
355
+            'type' => 'user',
356
+            'id' => $uid,
357
+            'name' => $this->displayNames[$uid],
358
+        ];
359
+    }
360
+
361
+    /**
362
+     * @param string $email
363
+     * @return string
364
+     */
365
+    protected function getContactName($email) {
366
+        $addressBookContacts = $this->contactsManager->search($email, ['EMAIL']);
367
+
368
+        foreach ($addressBookContacts as $contact) {
369
+            if (isset($contact['isLocalSystemBook'])) {
370
+                continue;
371
+            }
372
+
373
+            if (in_array($email, $contact['EMAIL'])) {
374
+                return $contact['FN'];
375
+            }
376
+        }
377
+
378
+        return $email;
379
+    }
380
+
381
+    /**
382
+     * @param string $uid
383
+     * @return string
384
+     */
385
+    protected function getDisplayName($uid) {
386
+        $user = $this->userManager->get($uid);
387
+        if ($user instanceof IUser) {
388
+            return $user->getDisplayName();
389
+        } else {
390
+            return $uid;
391
+        }
392
+    }
393 393
 }
Please login to merge, or discard this patch.