Passed
Push — master ( fdf54e...22ba8f )
by Morris
25:54 queued 12s
created
apps/user_ldap/lib/User_Proxy.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 	 * @return string|false
198 198
 	 */
199 199
 	public function loginName2UserName($loginName) {
200
-		$id = 'LOGINNAME,' . $loginName;
200
+		$id = 'LOGINNAME,'.$loginName;
201 201
 		return $this->handleRequest($id, 'loginName2UserName', [$loginName]);
202 202
 	}
203 203
 	
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 	 * @return string|false with the username
209 209
 	 */
210 210
 	public function dn2UserName($dn) {
211
-		$id = 'DN,' . $dn;
211
+		$id = 'DN,'.$dn;
212 212
 		return $this->handleRequest($id, 'dn2UserName', [$dn]);
213 213
 	}
214 214
 
Please login to merge, or discard this patch.
Indentation   +323 added lines, -323 removed lines patch added patch discarded remove patch
@@ -38,352 +38,352 @@
 block discarded – undo
38 38
 use OCP\Notification\IManager as INotificationManager;
39 39
 
40 40
 class User_Proxy extends Proxy implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
41
-	private $backends = [];
42
-	/** @var User_LDAP */
43
-	private $refBackend = null;
41
+    private $backends = [];
42
+    /** @var User_LDAP */
43
+    private $refBackend = null;
44 44
 
45
-	public function __construct(
46
-		Helper $helper,
47
-		ILDAPWrapper $ldap,
48
-		IConfig $ocConfig,
49
-		INotificationManager $notificationManager,
50
-		IUserSession $userSession,
51
-		UserPluginManager $userPluginManager
52
-	) {
53
-		parent::__construct($ldap);
54
-		$serverConfigPrefixes = $helper->getServerConfigurationPrefixes(true);
55
-		foreach ($serverConfigPrefixes as $configPrefix) {
56
-			$this->backends[$configPrefix] =
57
-				new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager, $userSession, $userPluginManager);
45
+    public function __construct(
46
+        Helper $helper,
47
+        ILDAPWrapper $ldap,
48
+        IConfig $ocConfig,
49
+        INotificationManager $notificationManager,
50
+        IUserSession $userSession,
51
+        UserPluginManager $userPluginManager
52
+    ) {
53
+        parent::__construct($ldap);
54
+        $serverConfigPrefixes = $helper->getServerConfigurationPrefixes(true);
55
+        foreach ($serverConfigPrefixes as $configPrefix) {
56
+            $this->backends[$configPrefix] =
57
+                new User_LDAP($this->getAccess($configPrefix), $ocConfig, $notificationManager, $userSession, $userPluginManager);
58 58
 
59
-			if (is_null($this->refBackend)) {
60
-				$this->refBackend = &$this->backends[$configPrefix];
61
-			}
62
-		}
63
-	}
59
+            if (is_null($this->refBackend)) {
60
+                $this->refBackend = &$this->backends[$configPrefix];
61
+            }
62
+        }
63
+    }
64 64
 
65
-	/**
66
-	 * Tries the backends one after the other until a positive result is returned from the specified method
67
-	 *
68
-	 * @param string $id the uid connected to the request
69
-	 * @param string $method the method of the user backend that shall be called
70
-	 * @param array $parameters an array of parameters to be passed
71
-	 * @return mixed the result of the method or false
72
-	 */
73
-	protected function walkBackends($id, $method, $parameters) {
74
-		$uid = $id;
75
-		$cacheKey = $this->getUserCacheKey($uid);
76
-		foreach ($this->backends as $configPrefix => $backend) {
77
-			$instance = $backend;
78
-			if (!method_exists($instance, $method)
79
-				&& method_exists($this->getAccess($configPrefix), $method)) {
80
-				$instance = $this->getAccess($configPrefix);
81
-			}
82
-			if ($result = call_user_func_array([$instance, $method], $parameters)) {
83
-				if (!$this->isSingleBackend()) {
84
-					$this->writeToCache($cacheKey, $configPrefix);
85
-				}
86
-				return $result;
87
-			}
88
-		}
89
-		return false;
90
-	}
65
+    /**
66
+     * Tries the backends one after the other until a positive result is returned from the specified method
67
+     *
68
+     * @param string $id the uid connected to the request
69
+     * @param string $method the method of the user backend that shall be called
70
+     * @param array $parameters an array of parameters to be passed
71
+     * @return mixed the result of the method or false
72
+     */
73
+    protected function walkBackends($id, $method, $parameters) {
74
+        $uid = $id;
75
+        $cacheKey = $this->getUserCacheKey($uid);
76
+        foreach ($this->backends as $configPrefix => $backend) {
77
+            $instance = $backend;
78
+            if (!method_exists($instance, $method)
79
+                && method_exists($this->getAccess($configPrefix), $method)) {
80
+                $instance = $this->getAccess($configPrefix);
81
+            }
82
+            if ($result = call_user_func_array([$instance, $method], $parameters)) {
83
+                if (!$this->isSingleBackend()) {
84
+                    $this->writeToCache($cacheKey, $configPrefix);
85
+                }
86
+                return $result;
87
+            }
88
+        }
89
+        return false;
90
+    }
91 91
 
92
-	/**
93
-	 * Asks the backend connected to the server that supposely takes care of the uid from the request.
94
-	 *
95
-	 * @param string $id the uid connected to the request
96
-	 * @param string $method the method of the user backend that shall be called
97
-	 * @param array $parameters an array of parameters to be passed
98
-	 * @param mixed $passOnWhen the result matches this variable
99
-	 * @return mixed the result of the method or false
100
-	 */
101
-	protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen) {
102
-		$uid = $id;
103
-		$cacheKey = $this->getUserCacheKey($uid);
104
-		$prefix = $this->getFromCache($cacheKey);
105
-		//in case the uid has been found in the past, try this stored connection first
106
-		if (!is_null($prefix)) {
107
-			if (isset($this->backends[$prefix])) {
108
-				$instance = $this->backends[$prefix];
109
-				if (!method_exists($instance, $method)
110
-					&& method_exists($this->getAccess($prefix), $method)) {
111
-					$instance = $this->getAccess($prefix);
112
-				}
113
-				$result = call_user_func_array([$instance, $method], $parameters);
114
-				if ($result === $passOnWhen) {
115
-					//not found here, reset cache to null if user vanished
116
-					//because sometimes methods return false with a reason
117
-					$userExists = call_user_func_array(
118
-						[$this->backends[$prefix], 'userExistsOnLDAP'],
119
-						[$uid]
120
-					);
121
-					if (!$userExists) {
122
-						$this->writeToCache($cacheKey, null);
123
-					}
124
-				}
125
-				return $result;
126
-			}
127
-		}
128
-		return false;
129
-	}
92
+    /**
93
+     * Asks the backend connected to the server that supposely takes care of the uid from the request.
94
+     *
95
+     * @param string $id the uid connected to the request
96
+     * @param string $method the method of the user backend that shall be called
97
+     * @param array $parameters an array of parameters to be passed
98
+     * @param mixed $passOnWhen the result matches this variable
99
+     * @return mixed the result of the method or false
100
+     */
101
+    protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen) {
102
+        $uid = $id;
103
+        $cacheKey = $this->getUserCacheKey($uid);
104
+        $prefix = $this->getFromCache($cacheKey);
105
+        //in case the uid has been found in the past, try this stored connection first
106
+        if (!is_null($prefix)) {
107
+            if (isset($this->backends[$prefix])) {
108
+                $instance = $this->backends[$prefix];
109
+                if (!method_exists($instance, $method)
110
+                    && method_exists($this->getAccess($prefix), $method)) {
111
+                    $instance = $this->getAccess($prefix);
112
+                }
113
+                $result = call_user_func_array([$instance, $method], $parameters);
114
+                if ($result === $passOnWhen) {
115
+                    //not found here, reset cache to null if user vanished
116
+                    //because sometimes methods return false with a reason
117
+                    $userExists = call_user_func_array(
118
+                        [$this->backends[$prefix], 'userExistsOnLDAP'],
119
+                        [$uid]
120
+                    );
121
+                    if (!$userExists) {
122
+                        $this->writeToCache($cacheKey, null);
123
+                    }
124
+                }
125
+                return $result;
126
+            }
127
+        }
128
+        return false;
129
+    }
130 130
 
131
-	protected function activeBackends(): int {
132
-		return count($this->backends);
133
-	}
131
+    protected function activeBackends(): int {
132
+        return count($this->backends);
133
+    }
134 134
 
135
-	/**
136
-	 * Check if backend implements actions
137
-	 *
138
-	 * @param int $actions bitwise-or'ed actions
139
-	 * @return boolean
140
-	 *
141
-	 * Returns the supported actions as int to be
142
-	 * compared with \OC\User\Backend::CREATE_USER etc.
143
-	 */
144
-	public function implementsActions($actions) {
145
-		//it's the same across all our user backends obviously
146
-		return $this->refBackend->implementsActions($actions);
147
-	}
135
+    /**
136
+     * Check if backend implements actions
137
+     *
138
+     * @param int $actions bitwise-or'ed actions
139
+     * @return boolean
140
+     *
141
+     * Returns the supported actions as int to be
142
+     * compared with \OC\User\Backend::CREATE_USER etc.
143
+     */
144
+    public function implementsActions($actions) {
145
+        //it's the same across all our user backends obviously
146
+        return $this->refBackend->implementsActions($actions);
147
+    }
148 148
 
149
-	/**
150
-	 * Backend name to be shown in user management
151
-	 *
152
-	 * @return string the name of the backend to be shown
153
-	 */
154
-	public function getBackendName() {
155
-		return $this->refBackend->getBackendName();
156
-	}
149
+    /**
150
+     * Backend name to be shown in user management
151
+     *
152
+     * @return string the name of the backend to be shown
153
+     */
154
+    public function getBackendName() {
155
+        return $this->refBackend->getBackendName();
156
+    }
157 157
 
158
-	/**
159
-	 * Get a list of all users
160
-	 *
161
-	 * @param string $search
162
-	 * @param null|int $limit
163
-	 * @param null|int $offset
164
-	 * @return string[] an array of all uids
165
-	 */
166
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
167
-		//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
168
-		$users = [];
169
-		foreach ($this->backends as $backend) {
170
-			$backendUsers = $backend->getUsers($search, $limit, $offset);
171
-			if (is_array($backendUsers)) {
172
-				$users = array_merge($users, $backendUsers);
173
-			}
174
-		}
175
-		return $users;
176
-	}
158
+    /**
159
+     * Get a list of all users
160
+     *
161
+     * @param string $search
162
+     * @param null|int $limit
163
+     * @param null|int $offset
164
+     * @return string[] an array of all uids
165
+     */
166
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
167
+        //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
168
+        $users = [];
169
+        foreach ($this->backends as $backend) {
170
+            $backendUsers = $backend->getUsers($search, $limit, $offset);
171
+            if (is_array($backendUsers)) {
172
+                $users = array_merge($users, $backendUsers);
173
+            }
174
+        }
175
+        return $users;
176
+    }
177 177
 
178
-	/**
179
-	 * check if a user exists
180
-	 *
181
-	 * @param string $uid the username
182
-	 * @return boolean
183
-	 */
184
-	public function userExists($uid) {
185
-		$existsOnLDAP = false;
186
-		$existsLocally = $this->handleRequest($uid, 'userExists', [$uid]);
187
-		if ($existsLocally) {
188
-			$existsOnLDAP = $this->userExistsOnLDAP($uid);
189
-		}
190
-		if ($existsLocally && !$existsOnLDAP) {
191
-			try {
192
-				$user = $this->getLDAPAccess($uid)->userManager->get($uid);
193
-				if ($user instanceof User) {
194
-					$user->markUser();
195
-				}
196
-			} catch (\Exception $e) {
197
-				// ignore
198
-			}
199
-		}
200
-		return $existsLocally;
201
-	}
178
+    /**
179
+     * check if a user exists
180
+     *
181
+     * @param string $uid the username
182
+     * @return boolean
183
+     */
184
+    public function userExists($uid) {
185
+        $existsOnLDAP = false;
186
+        $existsLocally = $this->handleRequest($uid, 'userExists', [$uid]);
187
+        if ($existsLocally) {
188
+            $existsOnLDAP = $this->userExistsOnLDAP($uid);
189
+        }
190
+        if ($existsLocally && !$existsOnLDAP) {
191
+            try {
192
+                $user = $this->getLDAPAccess($uid)->userManager->get($uid);
193
+                if ($user instanceof User) {
194
+                    $user->markUser();
195
+                }
196
+            } catch (\Exception $e) {
197
+                // ignore
198
+            }
199
+        }
200
+        return $existsLocally;
201
+    }
202 202
 
203
-	/**
204
-	 * check if a user exists on LDAP
205
-	 *
206
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
207
-	 * name or an instance of that user
208
-	 * @return boolean
209
-	 */
210
-	public function userExistsOnLDAP($user) {
211
-		$id = ($user instanceof User) ? $user->getUsername() : $user;
212
-		return $this->handleRequest($id, 'userExistsOnLDAP', [$user]);
213
-	}
203
+    /**
204
+     * check if a user exists on LDAP
205
+     *
206
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
207
+     * name or an instance of that user
208
+     * @return boolean
209
+     */
210
+    public function userExistsOnLDAP($user) {
211
+        $id = ($user instanceof User) ? $user->getUsername() : $user;
212
+        return $this->handleRequest($id, 'userExistsOnLDAP', [$user]);
213
+    }
214 214
 
215
-	/**
216
-	 * Check if the password is correct
217
-	 *
218
-	 * @param string $uid The username
219
-	 * @param string $password The password
220
-	 * @return bool
221
-	 *
222
-	 * Check if the password is correct without logging in the user
223
-	 */
224
-	public function checkPassword($uid, $password) {
225
-		return $this->handleRequest($uid, 'checkPassword', [$uid, $password]);
226
-	}
215
+    /**
216
+     * Check if the password is correct
217
+     *
218
+     * @param string $uid The username
219
+     * @param string $password The password
220
+     * @return bool
221
+     *
222
+     * Check if the password is correct without logging in the user
223
+     */
224
+    public function checkPassword($uid, $password) {
225
+        return $this->handleRequest($uid, 'checkPassword', [$uid, $password]);
226
+    }
227 227
 
228
-	/**
229
-	 * returns the username for the given login name, if available
230
-	 *
231
-	 * @param string $loginName
232
-	 * @return string|false
233
-	 */
234
-	public function loginName2UserName($loginName) {
235
-		$id = 'LOGINNAME,' . $loginName;
236
-		return $this->handleRequest($id, 'loginName2UserName', [$loginName]);
237
-	}
228
+    /**
229
+     * returns the username for the given login name, if available
230
+     *
231
+     * @param string $loginName
232
+     * @return string|false
233
+     */
234
+    public function loginName2UserName($loginName) {
235
+        $id = 'LOGINNAME,' . $loginName;
236
+        return $this->handleRequest($id, 'loginName2UserName', [$loginName]);
237
+    }
238 238
 
239
-	/**
240
-	 * returns the username for the given LDAP DN, if available
241
-	 *
242
-	 * @param string $dn
243
-	 * @return string|false with the username
244
-	 */
245
-	public function dn2UserName($dn) {
246
-		$id = 'DN,' . $dn;
247
-		return $this->handleRequest($id, 'dn2UserName', [$dn]);
248
-	}
239
+    /**
240
+     * returns the username for the given LDAP DN, if available
241
+     *
242
+     * @param string $dn
243
+     * @return string|false with the username
244
+     */
245
+    public function dn2UserName($dn) {
246
+        $id = 'DN,' . $dn;
247
+        return $this->handleRequest($id, 'dn2UserName', [$dn]);
248
+    }
249 249
 
250
-	/**
251
-	 * get the user's home directory
252
-	 *
253
-	 * @param string $uid the username
254
-	 * @return boolean
255
-	 */
256
-	public function getHome($uid) {
257
-		return $this->handleRequest($uid, 'getHome', [$uid]);
258
-	}
250
+    /**
251
+     * get the user's home directory
252
+     *
253
+     * @param string $uid the username
254
+     * @return boolean
255
+     */
256
+    public function getHome($uid) {
257
+        return $this->handleRequest($uid, 'getHome', [$uid]);
258
+    }
259 259
 
260
-	/**
261
-	 * get display name of the user
262
-	 *
263
-	 * @param string $uid user ID of the user
264
-	 * @return string display name
265
-	 */
266
-	public function getDisplayName($uid) {
267
-		return $this->handleRequest($uid, 'getDisplayName', [$uid]);
268
-	}
260
+    /**
261
+     * get display name of the user
262
+     *
263
+     * @param string $uid user ID of the user
264
+     * @return string display name
265
+     */
266
+    public function getDisplayName($uid) {
267
+        return $this->handleRequest($uid, 'getDisplayName', [$uid]);
268
+    }
269 269
 
270
-	/**
271
-	 * set display name of the user
272
-	 *
273
-	 * @param string $uid user ID of the user
274
-	 * @param string $displayName new display name
275
-	 * @return string display name
276
-	 */
277
-	public function setDisplayName($uid, $displayName) {
278
-		return $this->handleRequest($uid, 'setDisplayName', [$uid, $displayName]);
279
-	}
270
+    /**
271
+     * set display name of the user
272
+     *
273
+     * @param string $uid user ID of the user
274
+     * @param string $displayName new display name
275
+     * @return string display name
276
+     */
277
+    public function setDisplayName($uid, $displayName) {
278
+        return $this->handleRequest($uid, 'setDisplayName', [$uid, $displayName]);
279
+    }
280 280
 
281
-	/**
282
-	 * checks whether the user is allowed to change his avatar in Nextcloud
283
-	 *
284
-	 * @param string $uid the Nextcloud user name
285
-	 * @return boolean either the user can or cannot
286
-	 */
287
-	public function canChangeAvatar($uid) {
288
-		return $this->handleRequest($uid, 'canChangeAvatar', [$uid], true);
289
-	}
281
+    /**
282
+     * checks whether the user is allowed to change his avatar in Nextcloud
283
+     *
284
+     * @param string $uid the Nextcloud user name
285
+     * @return boolean either the user can or cannot
286
+     */
287
+    public function canChangeAvatar($uid) {
288
+        return $this->handleRequest($uid, 'canChangeAvatar', [$uid], true);
289
+    }
290 290
 
291
-	/**
292
-	 * Get a list of all display names and user ids.
293
-	 *
294
-	 * @param string $search
295
-	 * @param int|null $limit
296
-	 * @param int|null $offset
297
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
298
-	 */
299
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
300
-		//we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
301
-		$users = [];
302
-		foreach ($this->backends as $backend) {
303
-			$backendUsers = $backend->getDisplayNames($search, $limit, $offset);
304
-			if (is_array($backendUsers)) {
305
-				$users = $users + $backendUsers;
306
-			}
307
-		}
308
-		return $users;
309
-	}
291
+    /**
292
+     * Get a list of all display names and user ids.
293
+     *
294
+     * @param string $search
295
+     * @param int|null $limit
296
+     * @param int|null $offset
297
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
298
+     */
299
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
300
+        //we do it just as the /OC_User implementation: do not play around with limit and offset but ask all backends
301
+        $users = [];
302
+        foreach ($this->backends as $backend) {
303
+            $backendUsers = $backend->getDisplayNames($search, $limit, $offset);
304
+            if (is_array($backendUsers)) {
305
+                $users = $users + $backendUsers;
306
+            }
307
+        }
308
+        return $users;
309
+    }
310 310
 
311
-	/**
312
-	 * delete a user
313
-	 *
314
-	 * @param string $uid The username of the user to delete
315
-	 * @return bool
316
-	 *
317
-	 * Deletes a user
318
-	 */
319
-	public function deleteUser($uid) {
320
-		return $this->handleRequest($uid, 'deleteUser', [$uid]);
321
-	}
311
+    /**
312
+     * delete a user
313
+     *
314
+     * @param string $uid The username of the user to delete
315
+     * @return bool
316
+     *
317
+     * Deletes a user
318
+     */
319
+    public function deleteUser($uid) {
320
+        return $this->handleRequest($uid, 'deleteUser', [$uid]);
321
+    }
322 322
 
323
-	/**
324
-	 * Set password
325
-	 *
326
-	 * @param string $uid The username
327
-	 * @param string $password The new password
328
-	 * @return bool
329
-	 *
330
-	 */
331
-	public function setPassword($uid, $password) {
332
-		return $this->handleRequest($uid, 'setPassword', [$uid, $password]);
333
-	}
323
+    /**
324
+     * Set password
325
+     *
326
+     * @param string $uid The username
327
+     * @param string $password The new password
328
+     * @return bool
329
+     *
330
+     */
331
+    public function setPassword($uid, $password) {
332
+        return $this->handleRequest($uid, 'setPassword', [$uid, $password]);
333
+    }
334 334
 
335
-	/**
336
-	 * @return bool
337
-	 */
338
-	public function hasUserListings() {
339
-		return $this->refBackend->hasUserListings();
340
-	}
335
+    /**
336
+     * @return bool
337
+     */
338
+    public function hasUserListings() {
339
+        return $this->refBackend->hasUserListings();
340
+    }
341 341
 
342
-	/**
343
-	 * Count the number of users
344
-	 *
345
-	 * @return int|bool
346
-	 */
347
-	public function countUsers() {
348
-		$users = false;
349
-		foreach ($this->backends as $backend) {
350
-			$backendUsers = $backend->countUsers();
351
-			if ($backendUsers !== false) {
352
-				$users += $backendUsers;
353
-			}
354
-		}
355
-		return $users;
356
-	}
342
+    /**
343
+     * Count the number of users
344
+     *
345
+     * @return int|bool
346
+     */
347
+    public function countUsers() {
348
+        $users = false;
349
+        foreach ($this->backends as $backend) {
350
+            $backendUsers = $backend->countUsers();
351
+            if ($backendUsers !== false) {
352
+                $users += $backendUsers;
353
+            }
354
+        }
355
+        return $users;
356
+    }
357 357
 
358
-	/**
359
-	 * Return access for LDAP interaction.
360
-	 *
361
-	 * @param string $uid
362
-	 * @return Access instance of Access for LDAP interaction
363
-	 */
364
-	public function getLDAPAccess($uid) {
365
-		return $this->handleRequest($uid, 'getLDAPAccess', [$uid]);
366
-	}
358
+    /**
359
+     * Return access for LDAP interaction.
360
+     *
361
+     * @param string $uid
362
+     * @return Access instance of Access for LDAP interaction
363
+     */
364
+    public function getLDAPAccess($uid) {
365
+        return $this->handleRequest($uid, 'getLDAPAccess', [$uid]);
366
+    }
367 367
 
368
-	/**
369
-	 * Return a new LDAP connection for the specified user.
370
-	 * The connection needs to be closed manually.
371
-	 *
372
-	 * @param string $uid
373
-	 * @return resource of the LDAP connection
374
-	 */
375
-	public function getNewLDAPConnection($uid) {
376
-		return $this->handleRequest($uid, 'getNewLDAPConnection', [$uid]);
377
-	}
368
+    /**
369
+     * Return a new LDAP connection for the specified user.
370
+     * The connection needs to be closed manually.
371
+     *
372
+     * @param string $uid
373
+     * @return resource of the LDAP connection
374
+     */
375
+    public function getNewLDAPConnection($uid) {
376
+        return $this->handleRequest($uid, 'getNewLDAPConnection', [$uid]);
377
+    }
378 378
 
379
-	/**
380
-	 * Creates a new user in LDAP
381
-	 *
382
-	 * @param $username
383
-	 * @param $password
384
-	 * @return bool
385
-	 */
386
-	public function createUser($username, $password) {
387
-		return $this->handleRequest($username, 'createUser', [$username, $password]);
388
-	}
379
+    /**
380
+     * Creates a new user in LDAP
381
+     *
382
+     * @param $username
383
+     * @param $password
384
+     * @return bool
385
+     */
386
+    public function createUser($username, $password) {
387
+        return $this->handleRequest($username, 'createUser', [$username, $password]);
388
+    }
389 389
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/BackendUtility.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -26,13 +26,13 @@
 block discarded – undo
26 26
 namespace OCA\User_LDAP;
27 27
 
28 28
 abstract class BackendUtility {
29
-	protected $access;
29
+    protected $access;
30 30
 
31
-	/**
32
-	 * constructor, make sure the subclasses call this one!
33
-	 * @param Access $access an instance of Access for LDAP interaction
34
-	 */
35
-	public function __construct(Access $access) {
36
-		$this->access = $access;
37
-	}
31
+    /**
32
+     * constructor, make sure the subclasses call this one!
33
+     * @param Access $access an instance of Access for LDAP interaction
34
+     */
35
+    public function __construct(Access $access) {
36
+        $this->access = $access;
37
+    }
38 38
 }
Please login to merge, or discard this patch.
apps/user_ldap/ajax/getNewServerConfigPrefix.php 2 patches
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -38,12 +38,12 @@
 block discarded – undo
38 38
 
39 39
 $newConfig = new \OCA\User_LDAP\Configuration($nk, false);
40 40
 if (isset($_POST['copyConfig'])) {
41
-	$originalConfig = new \OCA\User_LDAP\Configuration($_POST['copyConfig']);
42
-	$newConfig->setConfiguration($originalConfig->getConfiguration());
41
+    $originalConfig = new \OCA\User_LDAP\Configuration($_POST['copyConfig']);
42
+    $newConfig->setConfiguration($originalConfig->getConfiguration());
43 43
 } else {
44
-	$configuration = new \OCA\User_LDAP\Configuration($nk, false);
45
-	$newConfig->setConfiguration($configuration->getDefaults());
46
-	$resultData['defaults'] = $configuration->getDefaults();
44
+    $configuration = new \OCA\User_LDAP\Configuration($nk, false);
45
+    $newConfig->setConfiguration($configuration->getDefaults());
46
+    $resultData['defaults'] = $configuration->getDefaults();
47 47
 }
48 48
 $newConfig->saveConfiguration();
49 49
 
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@
 block discarded – undo
33 33
 $serverConnections = $helper->getServerConfigurationPrefixes();
34 34
 sort($serverConnections);
35 35
 $lk = array_pop($serverConnections);
36
-$ln = (int)str_replace('s', '', $lk);
36
+$ln = (int) str_replace('s', '', $lk);
37 37
 $nk = 's'.str_pad($ln + 1, 2, '0', STR_PAD_LEFT);
38 38
 
39 39
 $resultData = ['configPrefix' => $nk];
Please login to merge, or discard this patch.
apps/encryption/lib/Util.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	 * @return bool
168 168
 	 */
169 169
 	public function userHasFiles($uid) {
170
-		return $this->files->file_exists($uid . '/files');
170
+		return $this->files->file_exists($uid.'/files');
171 171
 	}
172 172
 
173 173
 	/**
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 		if (count($parts) > 1) {
184 184
 			$owner = $parts[1];
185 185
 			if ($this->userManager->userExists($owner) === false) {
186
-				throw new \BadMethodCallException('Unknown user: ' .
186
+				throw new \BadMethodCallException('Unknown user: '.
187 187
 				'method expects path to a user folder relative to the data folder');
188 188
 			}
189 189
 		}
Please login to merge, or discard this patch.
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -36,164 +36,164 @@
 block discarded – undo
36 36
 use OCP\PreConditionNotMetException;
37 37
 
38 38
 class Util {
39
-	/**
40
-	 * @var View
41
-	 */
42
-	private $files;
43
-	/**
44
-	 * @var Crypt
45
-	 */
46
-	private $crypt;
47
-	/**
48
-	 * @var ILogger
49
-	 */
50
-	private $logger;
51
-	/**
52
-	 * @var bool|IUser
53
-	 */
54
-	private $user;
55
-	/**
56
-	 * @var IConfig
57
-	 */
58
-	private $config;
59
-	/**
60
-	 * @var IUserManager
61
-	 */
62
-	private $userManager;
63
-
64
-	/**
65
-	 * Util constructor.
66
-	 *
67
-	 * @param View $files
68
-	 * @param Crypt $crypt
69
-	 * @param ILogger $logger
70
-	 * @param IUserSession $userSession
71
-	 * @param IConfig $config
72
-	 * @param IUserManager $userManager
73
-	 */
74
-	public function __construct(View $files,
75
-								Crypt $crypt,
76
-								ILogger $logger,
77
-								IUserSession $userSession,
78
-								IConfig $config,
79
-								IUserManager $userManager
80
-	) {
81
-		$this->files = $files;
82
-		$this->crypt = $crypt;
83
-		$this->logger = $logger;
84
-		$this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser() : false;
85
-		$this->config = $config;
86
-		$this->userManager = $userManager;
87
-	}
88
-
89
-	/**
90
-	 * check if recovery key is enabled for user
91
-	 *
92
-	 * @param string $uid
93
-	 * @return bool
94
-	 */
95
-	public function isRecoveryEnabledForUser($uid) {
96
-		$recoveryMode = $this->config->getUserValue($uid,
97
-			'encryption',
98
-			'recoveryEnabled',
99
-			'0');
100
-
101
-		return ($recoveryMode === '1');
102
-	}
103
-
104
-	/**
105
-	 * check if the home storage should be encrypted
106
-	 *
107
-	 * @return bool
108
-	 */
109
-	public function shouldEncryptHomeStorage() {
110
-		$encryptHomeStorage = $this->config->getAppValue(
111
-			'encryption',
112
-			'encryptHomeStorage',
113
-			'1'
114
-		);
115
-
116
-		return ($encryptHomeStorage === '1');
117
-	}
118
-
119
-	/**
120
-	 * set the home storage encryption on/off
121
-	 *
122
-	 * @param bool $encryptHomeStorage
123
-	 */
124
-	public function setEncryptHomeStorage($encryptHomeStorage) {
125
-		$value = $encryptHomeStorage ? '1' : '0';
126
-		$this->config->setAppValue(
127
-			'encryption',
128
-			'encryptHomeStorage',
129
-			$value
130
-		);
131
-	}
132
-
133
-	/**
134
-	 * check if master key is enabled
135
-	 *
136
-	 * @return bool
137
-	 */
138
-	public function isMasterKeyEnabled() {
139
-		$userMasterKey = $this->config->getAppValue('encryption', 'useMasterKey', '1');
140
-		return ($userMasterKey === '1');
141
-	}
142
-
143
-	/**
144
-	 * @param $enabled
145
-	 * @return bool
146
-	 */
147
-	public function setRecoveryForUser($enabled) {
148
-		$value = $enabled ? '1' : '0';
149
-
150
-		try {
151
-			$this->config->setUserValue($this->user->getUID(),
152
-				'encryption',
153
-				'recoveryEnabled',
154
-				$value);
155
-			return true;
156
-		} catch (PreConditionNotMetException $e) {
157
-			return false;
158
-		}
159
-	}
160
-
161
-	/**
162
-	 * @param string $uid
163
-	 * @return bool
164
-	 */
165
-	public function userHasFiles($uid) {
166
-		return $this->files->file_exists($uid . '/files');
167
-	}
168
-
169
-	/**
170
-	 * get owner from give path, path relative to data/ expected
171
-	 *
172
-	 * @param string $path relative to data/
173
-	 * @return string
174
-	 * @throws \BadMethodCallException
175
-	 */
176
-	public function getOwner($path) {
177
-		$owner = '';
178
-		$parts = explode('/', $path, 3);
179
-		if (count($parts) > 1) {
180
-			$owner = $parts[1];
181
-			if ($this->userManager->userExists($owner) === false) {
182
-				throw new \BadMethodCallException('Unknown user: ' .
183
-				'method expects path to a user folder relative to the data folder');
184
-			}
185
-		}
186
-
187
-		return $owner;
188
-	}
189
-
190
-	/**
191
-	 * get storage of path
192
-	 *
193
-	 * @param string $path
194
-	 * @return \OC\Files\Storage\Storage|null
195
-	 */
196
-	public function getStorage($path) {
197
-		return $this->files->getMount($path)->getStorage();
198
-	}
39
+    /**
40
+     * @var View
41
+     */
42
+    private $files;
43
+    /**
44
+     * @var Crypt
45
+     */
46
+    private $crypt;
47
+    /**
48
+     * @var ILogger
49
+     */
50
+    private $logger;
51
+    /**
52
+     * @var bool|IUser
53
+     */
54
+    private $user;
55
+    /**
56
+     * @var IConfig
57
+     */
58
+    private $config;
59
+    /**
60
+     * @var IUserManager
61
+     */
62
+    private $userManager;
63
+
64
+    /**
65
+     * Util constructor.
66
+     *
67
+     * @param View $files
68
+     * @param Crypt $crypt
69
+     * @param ILogger $logger
70
+     * @param IUserSession $userSession
71
+     * @param IConfig $config
72
+     * @param IUserManager $userManager
73
+     */
74
+    public function __construct(View $files,
75
+                                Crypt $crypt,
76
+                                ILogger $logger,
77
+                                IUserSession $userSession,
78
+                                IConfig $config,
79
+                                IUserManager $userManager
80
+    ) {
81
+        $this->files = $files;
82
+        $this->crypt = $crypt;
83
+        $this->logger = $logger;
84
+        $this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser() : false;
85
+        $this->config = $config;
86
+        $this->userManager = $userManager;
87
+    }
88
+
89
+    /**
90
+     * check if recovery key is enabled for user
91
+     *
92
+     * @param string $uid
93
+     * @return bool
94
+     */
95
+    public function isRecoveryEnabledForUser($uid) {
96
+        $recoveryMode = $this->config->getUserValue($uid,
97
+            'encryption',
98
+            'recoveryEnabled',
99
+            '0');
100
+
101
+        return ($recoveryMode === '1');
102
+    }
103
+
104
+    /**
105
+     * check if the home storage should be encrypted
106
+     *
107
+     * @return bool
108
+     */
109
+    public function shouldEncryptHomeStorage() {
110
+        $encryptHomeStorage = $this->config->getAppValue(
111
+            'encryption',
112
+            'encryptHomeStorage',
113
+            '1'
114
+        );
115
+
116
+        return ($encryptHomeStorage === '1');
117
+    }
118
+
119
+    /**
120
+     * set the home storage encryption on/off
121
+     *
122
+     * @param bool $encryptHomeStorage
123
+     */
124
+    public function setEncryptHomeStorage($encryptHomeStorage) {
125
+        $value = $encryptHomeStorage ? '1' : '0';
126
+        $this->config->setAppValue(
127
+            'encryption',
128
+            'encryptHomeStorage',
129
+            $value
130
+        );
131
+    }
132
+
133
+    /**
134
+     * check if master key is enabled
135
+     *
136
+     * @return bool
137
+     */
138
+    public function isMasterKeyEnabled() {
139
+        $userMasterKey = $this->config->getAppValue('encryption', 'useMasterKey', '1');
140
+        return ($userMasterKey === '1');
141
+    }
142
+
143
+    /**
144
+     * @param $enabled
145
+     * @return bool
146
+     */
147
+    public function setRecoveryForUser($enabled) {
148
+        $value = $enabled ? '1' : '0';
149
+
150
+        try {
151
+            $this->config->setUserValue($this->user->getUID(),
152
+                'encryption',
153
+                'recoveryEnabled',
154
+                $value);
155
+            return true;
156
+        } catch (PreConditionNotMetException $e) {
157
+            return false;
158
+        }
159
+    }
160
+
161
+    /**
162
+     * @param string $uid
163
+     * @return bool
164
+     */
165
+    public function userHasFiles($uid) {
166
+        return $this->files->file_exists($uid . '/files');
167
+    }
168
+
169
+    /**
170
+     * get owner from give path, path relative to data/ expected
171
+     *
172
+     * @param string $path relative to data/
173
+     * @return string
174
+     * @throws \BadMethodCallException
175
+     */
176
+    public function getOwner($path) {
177
+        $owner = '';
178
+        $parts = explode('/', $path, 3);
179
+        if (count($parts) > 1) {
180
+            $owner = $parts[1];
181
+            if ($this->userManager->userExists($owner) === false) {
182
+                throw new \BadMethodCallException('Unknown user: ' .
183
+                'method expects path to a user folder relative to the data folder');
184
+            }
185
+        }
186
+
187
+        return $owner;
188
+    }
189
+
190
+    /**
191
+     * get storage of path
192
+     *
193
+     * @param string $path
194
+     * @return \OC\Files\Storage\Storage|null
195
+     */
196
+    public function getStorage($path) {
197
+        return $this->files->getMount($path)->getStorage();
198
+    }
199 199
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/Encryption.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 		// always use the version from the original file, also part files
205 205
 		// need to have a correct version number if they get moved over to the
206 206
 		// final location
207
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
207
+		$this->version = (int) $this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
208 208
 
209 209
 		if (
210 210
 			$mode === 'w'
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 		if ($this->writeCache) {
309 309
 
310 310
 			// Concat writeCache to start of $data
311
-			$data = $this->writeCache . $data;
311
+			$data = $this->writeCache.$data;
312 312
 
313 313
 			// Clear the write cache, ready for reuse - it has been
314 314
 			// flushed and its old contents processed
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
 					try {
405 405
 						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
406 406
 					} catch (PublicKeyMissingException $e) {
407
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
407
+						$this->logger->warning('Could not encrypt file for '.$user.': '.$e->getMessage());
408 408
 					}
409 409
 				}
410 410
 			}
@@ -492,8 +492,8 @@  discard block
 block discarded – undo
492 492
 				// error message because in this case it means that the file was
493 493
 				// shared with the user at a point where the user didn't had a
494 494
 				// valid private/public key
495
-				$msg = 'Encryption module "' . $this->getDisplayName() .
496
-					'" is not able to read ' . $path;
495
+				$msg = 'Encryption module "'.$this->getDisplayName().
496
+					'" is not able to read '.$path;
497 497
 				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
498 498
 				$this->logger->warning($msg);
499 499
 				throw new DecryptionFailedException($msg, $hint);
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
 		$realPath = $path;
536 536
 		$parts = explode('/', $path);
537 537
 		if ($parts[2] === 'files_versions') {
538
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
538
+			$realPath = '/'.$parts[1].'/files/'.implode('/', array_slice($parts, 3));
539 539
 			$length = strrpos($realPath, '.');
540 540
 			$realPath = substr($realPath, 0, $length);
541 541
 		}
Please login to merge, or discard this patch.
Indentation   +549 added lines, -549 removed lines patch added patch discarded remove patch
@@ -46,553 +46,553 @@
 block discarded – undo
46 46
 use Symfony\Component\Console\Output\OutputInterface;
47 47
 
48 48
 class Encryption implements IEncryptionModule {
49
-	public const ID = 'OC_DEFAULT_MODULE';
50
-	public const DISPLAY_NAME = 'Default encryption module';
51
-
52
-	/**
53
-	 * @var Crypt
54
-	 */
55
-	private $crypt;
56
-
57
-	/** @var string */
58
-	private $cipher;
59
-
60
-	/** @var string */
61
-	private $path;
62
-
63
-	/** @var string */
64
-	private $user;
65
-
66
-	/** @var  array */
67
-	private $owner;
68
-
69
-	/** @var string */
70
-	private $fileKey;
71
-
72
-	/** @var string */
73
-	private $writeCache;
74
-
75
-	/** @var KeyManager */
76
-	private $keyManager;
77
-
78
-	/** @var array */
79
-	private $accessList;
80
-
81
-	/** @var boolean */
82
-	private $isWriteOperation;
83
-
84
-	/** @var Util */
85
-	private $util;
86
-
87
-	/** @var  Session */
88
-	private $session;
89
-
90
-	/** @var  ILogger */
91
-	private $logger;
92
-
93
-	/** @var IL10N */
94
-	private $l;
95
-
96
-	/** @var EncryptAll */
97
-	private $encryptAll;
98
-
99
-	/** @var  bool */
100
-	private $useMasterPassword;
101
-
102
-	/** @var DecryptAll  */
103
-	private $decryptAll;
104
-
105
-	/** @var int unencrypted block size if block contains signature */
106
-	private $unencryptedBlockSizeSigned = 6072;
107
-
108
-	/** @var int unencrypted block size */
109
-	private $unencryptedBlockSize = 6126;
110
-
111
-	/** @var int Current version of the file */
112
-	private $version = 0;
113
-
114
-	/** @var array remember encryption signature version */
115
-	private static $rememberVersion = [];
116
-
117
-
118
-	/**
119
-	 *
120
-	 * @param Crypt $crypt
121
-	 * @param KeyManager $keyManager
122
-	 * @param Util $util
123
-	 * @param Session $session
124
-	 * @param EncryptAll $encryptAll
125
-	 * @param DecryptAll $decryptAll
126
-	 * @param ILogger $logger
127
-	 * @param IL10N $il10n
128
-	 */
129
-	public function __construct(Crypt $crypt,
130
-								KeyManager $keyManager,
131
-								Util $util,
132
-								Session $session,
133
-								EncryptAll $encryptAll,
134
-								DecryptAll $decryptAll,
135
-								ILogger $logger,
136
-								IL10N $il10n) {
137
-		$this->crypt = $crypt;
138
-		$this->keyManager = $keyManager;
139
-		$this->util = $util;
140
-		$this->session = $session;
141
-		$this->encryptAll = $encryptAll;
142
-		$this->decryptAll = $decryptAll;
143
-		$this->logger = $logger;
144
-		$this->l = $il10n;
145
-		$this->owner = [];
146
-		$this->useMasterPassword = $util->isMasterKeyEnabled();
147
-	}
148
-
149
-	/**
150
-	 * @return string defining the technical unique id
151
-	 */
152
-	public function getId() {
153
-		return self::ID;
154
-	}
155
-
156
-	/**
157
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
158
-	 *
159
-	 * @return string
160
-	 */
161
-	public function getDisplayName() {
162
-		return self::DISPLAY_NAME;
163
-	}
164
-
165
-	/**
166
-	 * start receiving chunks from a file. This is the place where you can
167
-	 * perform some initial step before starting encrypting/decrypting the
168
-	 * chunks
169
-	 *
170
-	 * @param string $path to the file
171
-	 * @param string $user who read/write the file
172
-	 * @param string $mode php stream open mode
173
-	 * @param array $header contains the header data read from the file
174
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
175
-	 *
176
-	 * @return array $header contain data as key-value pairs which should be
177
-	 *                       written to the header, in case of a write operation
178
-	 *                       or if no additional data is needed return a empty array
179
-	 */
180
-	public function begin($path, $user, $mode, array $header, array $accessList) {
181
-		$this->path = $this->getPathToRealFile($path);
182
-		$this->accessList = $accessList;
183
-		$this->user = $user;
184
-		$this->isWriteOperation = false;
185
-		$this->writeCache = '';
186
-
187
-		if ($this->session->isReady() === false) {
188
-			// if the master key is enabled we can initialize encryption
189
-			// with a empty password and user name
190
-			if ($this->util->isMasterKeyEnabled()) {
191
-				$this->keyManager->init('', '');
192
-			}
193
-		}
194
-
195
-		if ($this->session->decryptAllModeActivated()) {
196
-			$encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
197
-			$shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
198
-			$this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
199
-				$shareKey,
200
-				$this->session->getDecryptAllKey());
201
-		} else {
202
-			$this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
203
-		}
204
-
205
-		// always use the version from the original file, also part files
206
-		// need to have a correct version number if they get moved over to the
207
-		// final location
208
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
209
-
210
-		if (
211
-			$mode === 'w'
212
-			|| $mode === 'w+'
213
-			|| $mode === 'wb'
214
-			|| $mode === 'wb+'
215
-		) {
216
-			$this->isWriteOperation = true;
217
-			if (empty($this->fileKey)) {
218
-				$this->fileKey = $this->crypt->generateFileKey();
219
-			}
220
-		} else {
221
-			// if we read a part file we need to increase the version by 1
222
-			// because the version number was also increased by writing
223
-			// the part file
224
-			if (Scanner::isPartialFile($path)) {
225
-				$this->version = $this->version + 1;
226
-			}
227
-		}
228
-
229
-		if ($this->isWriteOperation) {
230
-			$this->cipher = $this->crypt->getCipher();
231
-		} elseif (isset($header['cipher'])) {
232
-			$this->cipher = $header['cipher'];
233
-		} else {
234
-			// if we read a file without a header we fall-back to the legacy cipher
235
-			// which was used in <=oC6
236
-			$this->cipher = $this->crypt->getLegacyCipher();
237
-		}
238
-
239
-		return ['cipher' => $this->cipher, 'signed' => 'true'];
240
-	}
241
-
242
-	/**
243
-	 * last chunk received. This is the place where you can perform some final
244
-	 * operation and return some remaining data if something is left in your
245
-	 * buffer.
246
-	 *
247
-	 * @param string $path to the file
248
-	 * @param int $position
249
-	 * @return string remained data which should be written to the file in case
250
-	 *                of a write operation
251
-	 * @throws PublicKeyMissingException
252
-	 * @throws \Exception
253
-	 * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
254
-	 */
255
-	public function end($path, $position = 0) {
256
-		$result = '';
257
-		if ($this->isWriteOperation) {
258
-			// in case of a part file we remember the new signature versions
259
-			// the version will be set later on update.
260
-			// This way we make sure that other apps listening to the pre-hooks
261
-			// still get the old version which should be the correct value for them
262
-			if (Scanner::isPartialFile($path)) {
263
-				self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
264
-			}
265
-			if (!empty($this->writeCache)) {
266
-				$result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
267
-				$this->writeCache = '';
268
-			}
269
-			$publicKeys = [];
270
-			if ($this->useMasterPassword === true) {
271
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
272
-			} else {
273
-				foreach ($this->accessList['users'] as $uid) {
274
-					try {
275
-						$publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
276
-					} catch (PublicKeyMissingException $e) {
277
-						$this->logger->warning(
278
-							'no public key found for user "{uid}", user will not be able to read the file',
279
-							['app' => 'encryption', 'uid' => $uid]
280
-						);
281
-						// if the public key of the owner is missing we should fail
282
-						if ($uid === $this->user) {
283
-							throw $e;
284
-						}
285
-					}
286
-				}
287
-			}
288
-
289
-			$publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
290
-			$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
291
-			$this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
292
-		}
293
-		return $result;
294
-	}
295
-
296
-
297
-
298
-	/**
299
-	 * encrypt data
300
-	 *
301
-	 * @param string $data you want to encrypt
302
-	 * @param int $position
303
-	 * @return string encrypted data
304
-	 */
305
-	public function encrypt($data, $position = 0) {
306
-		// If extra data is left over from the last round, make sure it
307
-		// is integrated into the next block
308
-		if ($this->writeCache) {
309
-
310
-			// Concat writeCache to start of $data
311
-			$data = $this->writeCache . $data;
312
-
313
-			// Clear the write cache, ready for reuse - it has been
314
-			// flushed and its old contents processed
315
-			$this->writeCache = '';
316
-		}
317
-
318
-		$encrypted = '';
319
-		// While there still remains some data to be processed & written
320
-		while (strlen($data) > 0) {
321
-
322
-			// Remaining length for this iteration, not of the
323
-			// entire file (may be greater than 8192 bytes)
324
-			$remainingLength = strlen($data);
325
-
326
-			// If data remaining to be written is less than the
327
-			// size of 1 6126 byte block
328
-			if ($remainingLength < $this->unencryptedBlockSizeSigned) {
329
-
330
-				// Set writeCache to contents of $data
331
-				// The writeCache will be carried over to the
332
-				// next write round, and added to the start of
333
-				// $data to ensure that written blocks are
334
-				// always the correct length. If there is still
335
-				// data in writeCache after the writing round
336
-				// has finished, then the data will be written
337
-				// to disk by $this->flush().
338
-				$this->writeCache = $data;
339
-
340
-				// Clear $data ready for next round
341
-				$data = '';
342
-			} else {
343
-
344
-				// Read the chunk from the start of $data
345
-				$chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
346
-
347
-				$encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
348
-
349
-				// Remove the chunk we just processed from
350
-				// $data, leaving only unprocessed data in $data
351
-				// var, for handling on the next round
352
-				$data = substr($data, $this->unencryptedBlockSizeSigned);
353
-			}
354
-		}
355
-
356
-		return $encrypted;
357
-	}
358
-
359
-	/**
360
-	 * decrypt data
361
-	 *
362
-	 * @param string $data you want to decrypt
363
-	 * @param int|string $position
364
-	 * @return string decrypted data
365
-	 * @throws DecryptionFailedException
366
-	 */
367
-	public function decrypt($data, $position = 0) {
368
-		if (empty($this->fileKey)) {
369
-			$msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
370
-			$hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
371
-			$this->logger->error($msg);
372
-
373
-			throw new DecryptionFailedException($msg, $hint);
374
-		}
375
-
376
-		return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
377
-	}
378
-
379
-	/**
380
-	 * update encrypted file, e.g. give additional users access to the file
381
-	 *
382
-	 * @param string $path path to the file which should be updated
383
-	 * @param string $uid of the user who performs the operation
384
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
385
-	 * @return boolean
386
-	 */
387
-	public function update($path, $uid, array $accessList) {
388
-		if (empty($accessList)) {
389
-			if (isset(self::$rememberVersion[$path])) {
390
-				$this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
391
-				unset(self::$rememberVersion[$path]);
392
-			}
393
-			return;
394
-		}
395
-
396
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
397
-
398
-		if (!empty($fileKey)) {
399
-			$publicKeys = [];
400
-			if ($this->useMasterPassword === true) {
401
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
402
-			} else {
403
-				foreach ($accessList['users'] as $user) {
404
-					try {
405
-						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
406
-					} catch (PublicKeyMissingException $e) {
407
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
408
-					}
409
-				}
410
-			}
411
-
412
-			$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
413
-
414
-			$encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
415
-
416
-			$this->keyManager->deleteAllFileKeys($path);
417
-
418
-			$this->keyManager->setAllFileKeys($path, $encryptedFileKey);
419
-		} else {
420
-			$this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
421
-				['file' => $path, 'app' => 'encryption']);
422
-
423
-			return false;
424
-		}
425
-
426
-		return true;
427
-	}
428
-
429
-	/**
430
-	 * should the file be encrypted or not
431
-	 *
432
-	 * @param string $path
433
-	 * @return boolean
434
-	 */
435
-	public function shouldEncrypt($path) {
436
-		if ($this->util->shouldEncryptHomeStorage() === false) {
437
-			$storage = $this->util->getStorage($path);
438
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
439
-				return false;
440
-			}
441
-		}
442
-		$parts = explode('/', $path);
443
-		if (count($parts) < 4) {
444
-			return false;
445
-		}
446
-
447
-		if ($parts[2] === 'files') {
448
-			return true;
449
-		}
450
-		if ($parts[2] === 'files_versions') {
451
-			return true;
452
-		}
453
-		if ($parts[2] === 'files_trashbin') {
454
-			return true;
455
-		}
456
-
457
-		return false;
458
-	}
459
-
460
-	/**
461
-	 * get size of the unencrypted payload per block.
462
-	 * Nextcloud read/write files with a block size of 8192 byte
463
-	 *
464
-	 * @param bool $signed
465
-	 * @return int
466
-	 */
467
-	public function getUnencryptedBlockSize($signed = false) {
468
-		if ($signed === false) {
469
-			return $this->unencryptedBlockSize;
470
-		}
471
-
472
-		return $this->unencryptedBlockSizeSigned;
473
-	}
474
-
475
-	/**
476
-	 * check if the encryption module is able to read the file,
477
-	 * e.g. if all encryption keys exists
478
-	 *
479
-	 * @param string $path
480
-	 * @param string $uid user for whom we want to check if he can read the file
481
-	 * @return bool
482
-	 * @throws DecryptionFailedException
483
-	 */
484
-	public function isReadable($path, $uid) {
485
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
486
-		if (empty($fileKey)) {
487
-			$owner = $this->util->getOwner($path);
488
-			if ($owner !== $uid) {
489
-				// if it is a shared file we throw a exception with a useful
490
-				// error message because in this case it means that the file was
491
-				// shared with the user at a point where the user didn't had a
492
-				// valid private/public key
493
-				$msg = 'Encryption module "' . $this->getDisplayName() .
494
-					'" is not able to read ' . $path;
495
-				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
496
-				$this->logger->warning($msg);
497
-				throw new DecryptionFailedException($msg, $hint);
498
-			}
499
-			return false;
500
-		}
501
-
502
-		return true;
503
-	}
504
-
505
-	/**
506
-	 * Initial encryption of all files
507
-	 *
508
-	 * @param InputInterface $input
509
-	 * @param OutputInterface $output write some status information to the terminal during encryption
510
-	 */
511
-	public function encryptAll(InputInterface $input, OutputInterface $output) {
512
-		$this->encryptAll->encryptAll($input, $output);
513
-	}
514
-
515
-	/**
516
-	 * prepare module to perform decrypt all operation
517
-	 *
518
-	 * @param InputInterface $input
519
-	 * @param OutputInterface $output
520
-	 * @param string $user
521
-	 * @return bool
522
-	 */
523
-	public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
524
-		return $this->decryptAll->prepare($input, $output, $user);
525
-	}
526
-
527
-
528
-	/**
529
-	 * @param string $path
530
-	 * @return string
531
-	 */
532
-	protected function getPathToRealFile($path) {
533
-		$realPath = $path;
534
-		$parts = explode('/', $path);
535
-		if ($parts[2] === 'files_versions') {
536
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
537
-			$length = strrpos($realPath, '.');
538
-			$realPath = substr($realPath, 0, $length);
539
-		}
540
-
541
-		return $realPath;
542
-	}
543
-
544
-	/**
545
-	 * remove .part file extension and the ocTransferId from the file to get the
546
-	 * original file name
547
-	 *
548
-	 * @param string $path
549
-	 * @return string
550
-	 */
551
-	protected function stripPartFileExtension($path) {
552
-		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
553
-			$pos = strrpos($path, '.', -6);
554
-			$path = substr($path, 0, $pos);
555
-		}
556
-
557
-		return $path;
558
-	}
559
-
560
-	/**
561
-	 * get owner of a file
562
-	 *
563
-	 * @param string $path
564
-	 * @return string
565
-	 */
566
-	protected function getOwner($path) {
567
-		if (!isset($this->owner[$path])) {
568
-			$this->owner[$path] = $this->util->getOwner($path);
569
-		}
570
-		return $this->owner[$path];
571
-	}
572
-
573
-	/**
574
-	 * Check if the module is ready to be used by that specific user.
575
-	 * In case a module is not ready - because e.g. key pairs have not been generated
576
-	 * upon login this method can return false before any operation starts and might
577
-	 * cause issues during operations.
578
-	 *
579
-	 * @param string $user
580
-	 * @return boolean
581
-	 * @since 9.1.0
582
-	 */
583
-	public function isReadyForUser($user) {
584
-		if ($this->util->isMasterKeyEnabled()) {
585
-			return true;
586
-		}
587
-		return $this->keyManager->userHasKeys($user);
588
-	}
589
-
590
-	/**
591
-	 * We only need a detailed access list if the master key is not enabled
592
-	 *
593
-	 * @return bool
594
-	 */
595
-	public function needDetailedAccessList() {
596
-		return !$this->util->isMasterKeyEnabled();
597
-	}
49
+    public const ID = 'OC_DEFAULT_MODULE';
50
+    public const DISPLAY_NAME = 'Default encryption module';
51
+
52
+    /**
53
+     * @var Crypt
54
+     */
55
+    private $crypt;
56
+
57
+    /** @var string */
58
+    private $cipher;
59
+
60
+    /** @var string */
61
+    private $path;
62
+
63
+    /** @var string */
64
+    private $user;
65
+
66
+    /** @var  array */
67
+    private $owner;
68
+
69
+    /** @var string */
70
+    private $fileKey;
71
+
72
+    /** @var string */
73
+    private $writeCache;
74
+
75
+    /** @var KeyManager */
76
+    private $keyManager;
77
+
78
+    /** @var array */
79
+    private $accessList;
80
+
81
+    /** @var boolean */
82
+    private $isWriteOperation;
83
+
84
+    /** @var Util */
85
+    private $util;
86
+
87
+    /** @var  Session */
88
+    private $session;
89
+
90
+    /** @var  ILogger */
91
+    private $logger;
92
+
93
+    /** @var IL10N */
94
+    private $l;
95
+
96
+    /** @var EncryptAll */
97
+    private $encryptAll;
98
+
99
+    /** @var  bool */
100
+    private $useMasterPassword;
101
+
102
+    /** @var DecryptAll  */
103
+    private $decryptAll;
104
+
105
+    /** @var int unencrypted block size if block contains signature */
106
+    private $unencryptedBlockSizeSigned = 6072;
107
+
108
+    /** @var int unencrypted block size */
109
+    private $unencryptedBlockSize = 6126;
110
+
111
+    /** @var int Current version of the file */
112
+    private $version = 0;
113
+
114
+    /** @var array remember encryption signature version */
115
+    private static $rememberVersion = [];
116
+
117
+
118
+    /**
119
+     *
120
+     * @param Crypt $crypt
121
+     * @param KeyManager $keyManager
122
+     * @param Util $util
123
+     * @param Session $session
124
+     * @param EncryptAll $encryptAll
125
+     * @param DecryptAll $decryptAll
126
+     * @param ILogger $logger
127
+     * @param IL10N $il10n
128
+     */
129
+    public function __construct(Crypt $crypt,
130
+                                KeyManager $keyManager,
131
+                                Util $util,
132
+                                Session $session,
133
+                                EncryptAll $encryptAll,
134
+                                DecryptAll $decryptAll,
135
+                                ILogger $logger,
136
+                                IL10N $il10n) {
137
+        $this->crypt = $crypt;
138
+        $this->keyManager = $keyManager;
139
+        $this->util = $util;
140
+        $this->session = $session;
141
+        $this->encryptAll = $encryptAll;
142
+        $this->decryptAll = $decryptAll;
143
+        $this->logger = $logger;
144
+        $this->l = $il10n;
145
+        $this->owner = [];
146
+        $this->useMasterPassword = $util->isMasterKeyEnabled();
147
+    }
148
+
149
+    /**
150
+     * @return string defining the technical unique id
151
+     */
152
+    public function getId() {
153
+        return self::ID;
154
+    }
155
+
156
+    /**
157
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
158
+     *
159
+     * @return string
160
+     */
161
+    public function getDisplayName() {
162
+        return self::DISPLAY_NAME;
163
+    }
164
+
165
+    /**
166
+     * start receiving chunks from a file. This is the place where you can
167
+     * perform some initial step before starting encrypting/decrypting the
168
+     * chunks
169
+     *
170
+     * @param string $path to the file
171
+     * @param string $user who read/write the file
172
+     * @param string $mode php stream open mode
173
+     * @param array $header contains the header data read from the file
174
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
175
+     *
176
+     * @return array $header contain data as key-value pairs which should be
177
+     *                       written to the header, in case of a write operation
178
+     *                       or if no additional data is needed return a empty array
179
+     */
180
+    public function begin($path, $user, $mode, array $header, array $accessList) {
181
+        $this->path = $this->getPathToRealFile($path);
182
+        $this->accessList = $accessList;
183
+        $this->user = $user;
184
+        $this->isWriteOperation = false;
185
+        $this->writeCache = '';
186
+
187
+        if ($this->session->isReady() === false) {
188
+            // if the master key is enabled we can initialize encryption
189
+            // with a empty password and user name
190
+            if ($this->util->isMasterKeyEnabled()) {
191
+                $this->keyManager->init('', '');
192
+            }
193
+        }
194
+
195
+        if ($this->session->decryptAllModeActivated()) {
196
+            $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
197
+            $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
198
+            $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
199
+                $shareKey,
200
+                $this->session->getDecryptAllKey());
201
+        } else {
202
+            $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
203
+        }
204
+
205
+        // always use the version from the original file, also part files
206
+        // need to have a correct version number if they get moved over to the
207
+        // final location
208
+        $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
209
+
210
+        if (
211
+            $mode === 'w'
212
+            || $mode === 'w+'
213
+            || $mode === 'wb'
214
+            || $mode === 'wb+'
215
+        ) {
216
+            $this->isWriteOperation = true;
217
+            if (empty($this->fileKey)) {
218
+                $this->fileKey = $this->crypt->generateFileKey();
219
+            }
220
+        } else {
221
+            // if we read a part file we need to increase the version by 1
222
+            // because the version number was also increased by writing
223
+            // the part file
224
+            if (Scanner::isPartialFile($path)) {
225
+                $this->version = $this->version + 1;
226
+            }
227
+        }
228
+
229
+        if ($this->isWriteOperation) {
230
+            $this->cipher = $this->crypt->getCipher();
231
+        } elseif (isset($header['cipher'])) {
232
+            $this->cipher = $header['cipher'];
233
+        } else {
234
+            // if we read a file without a header we fall-back to the legacy cipher
235
+            // which was used in <=oC6
236
+            $this->cipher = $this->crypt->getLegacyCipher();
237
+        }
238
+
239
+        return ['cipher' => $this->cipher, 'signed' => 'true'];
240
+    }
241
+
242
+    /**
243
+     * last chunk received. This is the place where you can perform some final
244
+     * operation and return some remaining data if something is left in your
245
+     * buffer.
246
+     *
247
+     * @param string $path to the file
248
+     * @param int $position
249
+     * @return string remained data which should be written to the file in case
250
+     *                of a write operation
251
+     * @throws PublicKeyMissingException
252
+     * @throws \Exception
253
+     * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
254
+     */
255
+    public function end($path, $position = 0) {
256
+        $result = '';
257
+        if ($this->isWriteOperation) {
258
+            // in case of a part file we remember the new signature versions
259
+            // the version will be set later on update.
260
+            // This way we make sure that other apps listening to the pre-hooks
261
+            // still get the old version which should be the correct value for them
262
+            if (Scanner::isPartialFile($path)) {
263
+                self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
264
+            }
265
+            if (!empty($this->writeCache)) {
266
+                $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
267
+                $this->writeCache = '';
268
+            }
269
+            $publicKeys = [];
270
+            if ($this->useMasterPassword === true) {
271
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
272
+            } else {
273
+                foreach ($this->accessList['users'] as $uid) {
274
+                    try {
275
+                        $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
276
+                    } catch (PublicKeyMissingException $e) {
277
+                        $this->logger->warning(
278
+                            'no public key found for user "{uid}", user will not be able to read the file',
279
+                            ['app' => 'encryption', 'uid' => $uid]
280
+                        );
281
+                        // if the public key of the owner is missing we should fail
282
+                        if ($uid === $this->user) {
283
+                            throw $e;
284
+                        }
285
+                    }
286
+                }
287
+            }
288
+
289
+            $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
290
+            $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
291
+            $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
292
+        }
293
+        return $result;
294
+    }
295
+
296
+
297
+
298
+    /**
299
+     * encrypt data
300
+     *
301
+     * @param string $data you want to encrypt
302
+     * @param int $position
303
+     * @return string encrypted data
304
+     */
305
+    public function encrypt($data, $position = 0) {
306
+        // If extra data is left over from the last round, make sure it
307
+        // is integrated into the next block
308
+        if ($this->writeCache) {
309
+
310
+            // Concat writeCache to start of $data
311
+            $data = $this->writeCache . $data;
312
+
313
+            // Clear the write cache, ready for reuse - it has been
314
+            // flushed and its old contents processed
315
+            $this->writeCache = '';
316
+        }
317
+
318
+        $encrypted = '';
319
+        // While there still remains some data to be processed & written
320
+        while (strlen($data) > 0) {
321
+
322
+            // Remaining length for this iteration, not of the
323
+            // entire file (may be greater than 8192 bytes)
324
+            $remainingLength = strlen($data);
325
+
326
+            // If data remaining to be written is less than the
327
+            // size of 1 6126 byte block
328
+            if ($remainingLength < $this->unencryptedBlockSizeSigned) {
329
+
330
+                // Set writeCache to contents of $data
331
+                // The writeCache will be carried over to the
332
+                // next write round, and added to the start of
333
+                // $data to ensure that written blocks are
334
+                // always the correct length. If there is still
335
+                // data in writeCache after the writing round
336
+                // has finished, then the data will be written
337
+                // to disk by $this->flush().
338
+                $this->writeCache = $data;
339
+
340
+                // Clear $data ready for next round
341
+                $data = '';
342
+            } else {
343
+
344
+                // Read the chunk from the start of $data
345
+                $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
346
+
347
+                $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
348
+
349
+                // Remove the chunk we just processed from
350
+                // $data, leaving only unprocessed data in $data
351
+                // var, for handling on the next round
352
+                $data = substr($data, $this->unencryptedBlockSizeSigned);
353
+            }
354
+        }
355
+
356
+        return $encrypted;
357
+    }
358
+
359
+    /**
360
+     * decrypt data
361
+     *
362
+     * @param string $data you want to decrypt
363
+     * @param int|string $position
364
+     * @return string decrypted data
365
+     * @throws DecryptionFailedException
366
+     */
367
+    public function decrypt($data, $position = 0) {
368
+        if (empty($this->fileKey)) {
369
+            $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
370
+            $hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
371
+            $this->logger->error($msg);
372
+
373
+            throw new DecryptionFailedException($msg, $hint);
374
+        }
375
+
376
+        return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
377
+    }
378
+
379
+    /**
380
+     * update encrypted file, e.g. give additional users access to the file
381
+     *
382
+     * @param string $path path to the file which should be updated
383
+     * @param string $uid of the user who performs the operation
384
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
385
+     * @return boolean
386
+     */
387
+    public function update($path, $uid, array $accessList) {
388
+        if (empty($accessList)) {
389
+            if (isset(self::$rememberVersion[$path])) {
390
+                $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
391
+                unset(self::$rememberVersion[$path]);
392
+            }
393
+            return;
394
+        }
395
+
396
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
397
+
398
+        if (!empty($fileKey)) {
399
+            $publicKeys = [];
400
+            if ($this->useMasterPassword === true) {
401
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
402
+            } else {
403
+                foreach ($accessList['users'] as $user) {
404
+                    try {
405
+                        $publicKeys[$user] = $this->keyManager->getPublicKey($user);
406
+                    } catch (PublicKeyMissingException $e) {
407
+                        $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
408
+                    }
409
+                }
410
+            }
411
+
412
+            $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
413
+
414
+            $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
415
+
416
+            $this->keyManager->deleteAllFileKeys($path);
417
+
418
+            $this->keyManager->setAllFileKeys($path, $encryptedFileKey);
419
+        } else {
420
+            $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
421
+                ['file' => $path, 'app' => 'encryption']);
422
+
423
+            return false;
424
+        }
425
+
426
+        return true;
427
+    }
428
+
429
+    /**
430
+     * should the file be encrypted or not
431
+     *
432
+     * @param string $path
433
+     * @return boolean
434
+     */
435
+    public function shouldEncrypt($path) {
436
+        if ($this->util->shouldEncryptHomeStorage() === false) {
437
+            $storage = $this->util->getStorage($path);
438
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
439
+                return false;
440
+            }
441
+        }
442
+        $parts = explode('/', $path);
443
+        if (count($parts) < 4) {
444
+            return false;
445
+        }
446
+
447
+        if ($parts[2] === 'files') {
448
+            return true;
449
+        }
450
+        if ($parts[2] === 'files_versions') {
451
+            return true;
452
+        }
453
+        if ($parts[2] === 'files_trashbin') {
454
+            return true;
455
+        }
456
+
457
+        return false;
458
+    }
459
+
460
+    /**
461
+     * get size of the unencrypted payload per block.
462
+     * Nextcloud read/write files with a block size of 8192 byte
463
+     *
464
+     * @param bool $signed
465
+     * @return int
466
+     */
467
+    public function getUnencryptedBlockSize($signed = false) {
468
+        if ($signed === false) {
469
+            return $this->unencryptedBlockSize;
470
+        }
471
+
472
+        return $this->unencryptedBlockSizeSigned;
473
+    }
474
+
475
+    /**
476
+     * check if the encryption module is able to read the file,
477
+     * e.g. if all encryption keys exists
478
+     *
479
+     * @param string $path
480
+     * @param string $uid user for whom we want to check if he can read the file
481
+     * @return bool
482
+     * @throws DecryptionFailedException
483
+     */
484
+    public function isReadable($path, $uid) {
485
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
486
+        if (empty($fileKey)) {
487
+            $owner = $this->util->getOwner($path);
488
+            if ($owner !== $uid) {
489
+                // if it is a shared file we throw a exception with a useful
490
+                // error message because in this case it means that the file was
491
+                // shared with the user at a point where the user didn't had a
492
+                // valid private/public key
493
+                $msg = 'Encryption module "' . $this->getDisplayName() .
494
+                    '" is not able to read ' . $path;
495
+                $hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
496
+                $this->logger->warning($msg);
497
+                throw new DecryptionFailedException($msg, $hint);
498
+            }
499
+            return false;
500
+        }
501
+
502
+        return true;
503
+    }
504
+
505
+    /**
506
+     * Initial encryption of all files
507
+     *
508
+     * @param InputInterface $input
509
+     * @param OutputInterface $output write some status information to the terminal during encryption
510
+     */
511
+    public function encryptAll(InputInterface $input, OutputInterface $output) {
512
+        $this->encryptAll->encryptAll($input, $output);
513
+    }
514
+
515
+    /**
516
+     * prepare module to perform decrypt all operation
517
+     *
518
+     * @param InputInterface $input
519
+     * @param OutputInterface $output
520
+     * @param string $user
521
+     * @return bool
522
+     */
523
+    public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
524
+        return $this->decryptAll->prepare($input, $output, $user);
525
+    }
526
+
527
+
528
+    /**
529
+     * @param string $path
530
+     * @return string
531
+     */
532
+    protected function getPathToRealFile($path) {
533
+        $realPath = $path;
534
+        $parts = explode('/', $path);
535
+        if ($parts[2] === 'files_versions') {
536
+            $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
537
+            $length = strrpos($realPath, '.');
538
+            $realPath = substr($realPath, 0, $length);
539
+        }
540
+
541
+        return $realPath;
542
+    }
543
+
544
+    /**
545
+     * remove .part file extension and the ocTransferId from the file to get the
546
+     * original file name
547
+     *
548
+     * @param string $path
549
+     * @return string
550
+     */
551
+    protected function stripPartFileExtension($path) {
552
+        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
553
+            $pos = strrpos($path, '.', -6);
554
+            $path = substr($path, 0, $pos);
555
+        }
556
+
557
+        return $path;
558
+    }
559
+
560
+    /**
561
+     * get owner of a file
562
+     *
563
+     * @param string $path
564
+     * @return string
565
+     */
566
+    protected function getOwner($path) {
567
+        if (!isset($this->owner[$path])) {
568
+            $this->owner[$path] = $this->util->getOwner($path);
569
+        }
570
+        return $this->owner[$path];
571
+    }
572
+
573
+    /**
574
+     * Check if the module is ready to be used by that specific user.
575
+     * In case a module is not ready - because e.g. key pairs have not been generated
576
+     * upon login this method can return false before any operation starts and might
577
+     * cause issues during operations.
578
+     *
579
+     * @param string $user
580
+     * @return boolean
581
+     * @since 9.1.0
582
+     */
583
+    public function isReadyForUser($user) {
584
+        if ($this->util->isMasterKeyEnabled()) {
585
+            return true;
586
+        }
587
+        return $this->keyManager->userHasKeys($user);
588
+    }
589
+
590
+    /**
591
+     * We only need a detailed access list if the master key is not enabled
592
+     *
593
+     * @return bool
594
+     */
595
+    public function needDetailedAccessList() {
596
+        return !$this->util->isMasterKeyEnabled();
597
+    }
598 598
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/DecryptAll.php 2 patches
Indentation   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -34,126 +34,126 @@
 block discarded – undo
34 34
 
35 35
 class DecryptAll {
36 36
 
37
-	/** @var Util  */
38
-	protected $util;
39
-
40
-	/** @var QuestionHelper  */
41
-	protected $questionHelper;
42
-
43
-	/** @var  Crypt */
44
-	protected $crypt;
45
-
46
-	/** @var  KeyManager */
47
-	protected $keyManager;
48
-
49
-	/** @var Session  */
50
-	protected $session;
51
-
52
-	/**
53
-	 * @param Util $util
54
-	 * @param KeyManager $keyManager
55
-	 * @param Crypt $crypt
56
-	 * @param Session $session
57
-	 * @param QuestionHelper $questionHelper
58
-	 */
59
-	public function __construct(
60
-		Util $util,
61
-		KeyManager $keyManager,
62
-		Crypt $crypt,
63
-		Session $session,
64
-		QuestionHelper $questionHelper
65
-	) {
66
-		$this->util = $util;
67
-		$this->keyManager = $keyManager;
68
-		$this->crypt = $crypt;
69
-		$this->session = $session;
70
-		$this->questionHelper = $questionHelper;
71
-	}
72
-
73
-	/**
74
-	 * prepare encryption module to decrypt all files
75
-	 *
76
-	 * @param InputInterface $input
77
-	 * @param OutputInterface $output
78
-	 * @param $user
79
-	 * @return bool
80
-	 */
81
-	public function prepare(InputInterface $input, OutputInterface $output, $user) {
82
-		$question = new Question('Please enter the recovery key password: ');
83
-
84
-		if ($this->util->isMasterKeyEnabled()) {
85
-			$output->writeln('Use master key to decrypt all files');
86
-			$user = $this->keyManager->getMasterKeyId();
87
-			$password = $this->keyManager->getMasterKeyPassword();
88
-		} else {
89
-			$recoveryKeyId = $this->keyManager->getRecoveryKeyId();
90
-			if (!empty($user)) {
91
-				$output->writeln('You can only decrypt the users files if you know');
92
-				$output->writeln('the users password or if he activated the recovery key.');
93
-				$output->writeln('');
94
-				$questionUseLoginPassword = new ConfirmationQuestion(
95
-					'Do you want to use the users login password to decrypt all files? (y/n) ',
96
-					false
97
-				);
98
-				$useLoginPassword = $this->questionHelper->ask($input, $output, $questionUseLoginPassword);
99
-				if ($useLoginPassword) {
100
-					$question = new Question('Please enter the user\'s login password: ');
101
-				} elseif ($this->util->isRecoveryEnabledForUser($user) === false) {
102
-					$output->writeln('No recovery key available for user ' . $user);
103
-					return false;
104
-				} else {
105
-					$user = $recoveryKeyId;
106
-				}
107
-			} else {
108
-				$output->writeln('You can only decrypt the files of all users if the');
109
-				$output->writeln('recovery key is enabled by the admin and activated by the users.');
110
-				$output->writeln('');
111
-				$user = $recoveryKeyId;
112
-			}
113
-
114
-			$question->setHidden(true);
115
-			$question->setHiddenFallback(false);
116
-			$password = $this->questionHelper->ask($input, $output, $question);
117
-		}
118
-
119
-		$privateKey = $this->getPrivateKey($user, $password);
120
-		if ($privateKey !== false) {
121
-			$this->updateSession($user, $privateKey);
122
-			return true;
123
-		} else {
124
-			$output->writeln('Could not decrypt private key, maybe you entered the wrong password?');
125
-		}
126
-
127
-
128
-		return false;
129
-	}
130
-
131
-	/**
132
-	 * get the private key which will be used to decrypt all files
133
-	 *
134
-	 * @param string $user
135
-	 * @param string $password
136
-	 * @return bool|string
137
-	 * @throws \OCA\Encryption\Exceptions\PrivateKeyMissingException
138
-	 */
139
-	protected function getPrivateKey($user, $password) {
140
-		$recoveryKeyId = $this->keyManager->getRecoveryKeyId();
141
-		$masterKeyId = $this->keyManager->getMasterKeyId();
142
-		if ($user === $recoveryKeyId) {
143
-			$recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
144
-			$privateKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
145
-		} elseif ($user === $masterKeyId) {
146
-			$masterKey = $this->keyManager->getSystemPrivateKey($masterKeyId);
147
-			$privateKey = $this->crypt->decryptPrivateKey($masterKey, $password, $masterKeyId);
148
-		} else {
149
-			$userKey = $this->keyManager->getPrivateKey($user);
150
-			$privateKey = $this->crypt->decryptPrivateKey($userKey, $password, $user);
151
-		}
152
-
153
-		return $privateKey;
154
-	}
155
-
156
-	protected function updateSession($user, $privateKey) {
157
-		$this->session->prepareDecryptAll($user, $privateKey);
158
-	}
37
+    /** @var Util  */
38
+    protected $util;
39
+
40
+    /** @var QuestionHelper  */
41
+    protected $questionHelper;
42
+
43
+    /** @var  Crypt */
44
+    protected $crypt;
45
+
46
+    /** @var  KeyManager */
47
+    protected $keyManager;
48
+
49
+    /** @var Session  */
50
+    protected $session;
51
+
52
+    /**
53
+     * @param Util $util
54
+     * @param KeyManager $keyManager
55
+     * @param Crypt $crypt
56
+     * @param Session $session
57
+     * @param QuestionHelper $questionHelper
58
+     */
59
+    public function __construct(
60
+        Util $util,
61
+        KeyManager $keyManager,
62
+        Crypt $crypt,
63
+        Session $session,
64
+        QuestionHelper $questionHelper
65
+    ) {
66
+        $this->util = $util;
67
+        $this->keyManager = $keyManager;
68
+        $this->crypt = $crypt;
69
+        $this->session = $session;
70
+        $this->questionHelper = $questionHelper;
71
+    }
72
+
73
+    /**
74
+     * prepare encryption module to decrypt all files
75
+     *
76
+     * @param InputInterface $input
77
+     * @param OutputInterface $output
78
+     * @param $user
79
+     * @return bool
80
+     */
81
+    public function prepare(InputInterface $input, OutputInterface $output, $user) {
82
+        $question = new Question('Please enter the recovery key password: ');
83
+
84
+        if ($this->util->isMasterKeyEnabled()) {
85
+            $output->writeln('Use master key to decrypt all files');
86
+            $user = $this->keyManager->getMasterKeyId();
87
+            $password = $this->keyManager->getMasterKeyPassword();
88
+        } else {
89
+            $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
90
+            if (!empty($user)) {
91
+                $output->writeln('You can only decrypt the users files if you know');
92
+                $output->writeln('the users password or if he activated the recovery key.');
93
+                $output->writeln('');
94
+                $questionUseLoginPassword = new ConfirmationQuestion(
95
+                    'Do you want to use the users login password to decrypt all files? (y/n) ',
96
+                    false
97
+                );
98
+                $useLoginPassword = $this->questionHelper->ask($input, $output, $questionUseLoginPassword);
99
+                if ($useLoginPassword) {
100
+                    $question = new Question('Please enter the user\'s login password: ');
101
+                } elseif ($this->util->isRecoveryEnabledForUser($user) === false) {
102
+                    $output->writeln('No recovery key available for user ' . $user);
103
+                    return false;
104
+                } else {
105
+                    $user = $recoveryKeyId;
106
+                }
107
+            } else {
108
+                $output->writeln('You can only decrypt the files of all users if the');
109
+                $output->writeln('recovery key is enabled by the admin and activated by the users.');
110
+                $output->writeln('');
111
+                $user = $recoveryKeyId;
112
+            }
113
+
114
+            $question->setHidden(true);
115
+            $question->setHiddenFallback(false);
116
+            $password = $this->questionHelper->ask($input, $output, $question);
117
+        }
118
+
119
+        $privateKey = $this->getPrivateKey($user, $password);
120
+        if ($privateKey !== false) {
121
+            $this->updateSession($user, $privateKey);
122
+            return true;
123
+        } else {
124
+            $output->writeln('Could not decrypt private key, maybe you entered the wrong password?');
125
+        }
126
+
127
+
128
+        return false;
129
+    }
130
+
131
+    /**
132
+     * get the private key which will be used to decrypt all files
133
+     *
134
+     * @param string $user
135
+     * @param string $password
136
+     * @return bool|string
137
+     * @throws \OCA\Encryption\Exceptions\PrivateKeyMissingException
138
+     */
139
+    protected function getPrivateKey($user, $password) {
140
+        $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
141
+        $masterKeyId = $this->keyManager->getMasterKeyId();
142
+        if ($user === $recoveryKeyId) {
143
+            $recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
144
+            $privateKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
145
+        } elseif ($user === $masterKeyId) {
146
+            $masterKey = $this->keyManager->getSystemPrivateKey($masterKeyId);
147
+            $privateKey = $this->crypt->decryptPrivateKey($masterKey, $password, $masterKeyId);
148
+        } else {
149
+            $userKey = $this->keyManager->getPrivateKey($user);
150
+            $privateKey = $this->crypt->decryptPrivateKey($userKey, $password, $user);
151
+        }
152
+
153
+        return $privateKey;
154
+    }
155
+
156
+    protected function updateSession($user, $privateKey) {
157
+        $this->session->prepareDecryptAll($user, $privateKey);
158
+    }
159 159
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@
 block discarded – undo
99 99
 				if ($useLoginPassword) {
100 100
 					$question = new Question('Please enter the user\'s login password: ');
101 101
 				} elseif ($this->util->isRecoveryEnabledForUser($user) === false) {
102
-					$output->writeln('No recovery key available for user ' . $user);
102
+					$output->writeln('No recovery key available for user '.$user);
103 103
 					return false;
104 104
 				} else {
105 105
 					$user = $recoveryKeyId;
Please login to merge, or discard this patch.
apps/encryption/lib/Exceptions/PrivateKeyMissingException.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -28,13 +28,13 @@
 block discarded – undo
28 28
 
29 29
 class PrivateKeyMissingException extends GenericEncryptionException {
30 30
 
31
-	/**
32
-	 * @param string $userId
33
-	 */
34
-	public function __construct($userId) {
35
-		if (empty($userId)) {
36
-			$userId = "<no-user-id-given>";
37
-		}
38
-		parent::__construct("Private Key missing for user: $userId");
39
-	}
31
+    /**
32
+     * @param string $userId
33
+     */
34
+    public function __construct($userId) {
35
+        if (empty($userId)) {
36
+            $userId = "<no-user-id-given>";
37
+        }
38
+        parent::__construct("Private Key missing for user: $userId");
39
+    }
40 40
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Exceptions/PublicKeyMissingException.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -25,13 +25,13 @@
 block discarded – undo
25 25
 
26 26
 class PublicKeyMissingException extends GenericEncryptionException {
27 27
 
28
-	/**
29
-	 * @param string $userId
30
-	 */
31
-	public function __construct($userId) {
32
-		if (empty($userId)) {
33
-			$userId = "<no-user-id-given>";
34
-		}
35
-		parent::__construct("Public Key missing for user: $userId");
36
-	}
28
+    /**
29
+     * @param string $userId
30
+     */
31
+    public function __construct($userId) {
32
+        if (empty($userId)) {
33
+            $userId = "<no-user-id-given>";
34
+        }
35
+        parent::__construct("Public Key missing for user: $userId");
36
+    }
37 37
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Settings/Personal.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -32,63 +32,63 @@
 block discarded – undo
32 32
 
33 33
 class Personal implements ISettings {
34 34
 
35
-	/** @var IConfig */
36
-	private $config;
37
-	/** @var Session */
38
-	private $session;
39
-	/** @var Util */
40
-	private $util;
41
-	/** @var IUserSession */
42
-	private $userSession;
35
+    /** @var IConfig */
36
+    private $config;
37
+    /** @var Session */
38
+    private $session;
39
+    /** @var Util */
40
+    private $util;
41
+    /** @var IUserSession */
42
+    private $userSession;
43 43
 
44
-	public function __construct(IConfig $config, Session $session, Util $util, IUserSession $userSession) {
45
-		$this->config = $config;
46
-		$this->session = $session;
47
-		$this->util = $util;
48
-		$this->userSession = $userSession;
49
-	}
44
+    public function __construct(IConfig $config, Session $session, Util $util, IUserSession $userSession) {
45
+        $this->config = $config;
46
+        $this->session = $session;
47
+        $this->util = $util;
48
+        $this->userSession = $userSession;
49
+    }
50 50
 
51
-	/**
52
-	 * @return TemplateResponse returns the instance with all parameters set, ready to be rendered
53
-	 * @since 9.1
54
-	 */
55
-	public function getForm() {
56
-		$recoveryAdminEnabled = $this->config->getAppValue('encryption', 'recoveryAdminEnabled');
57
-		$privateKeySet = $this->session->isPrivateKeySet();
51
+    /**
52
+     * @return TemplateResponse returns the instance with all parameters set, ready to be rendered
53
+     * @since 9.1
54
+     */
55
+    public function getForm() {
56
+        $recoveryAdminEnabled = $this->config->getAppValue('encryption', 'recoveryAdminEnabled');
57
+        $privateKeySet = $this->session->isPrivateKeySet();
58 58
 
59
-		if (!$recoveryAdminEnabled && $privateKeySet) {
60
-			return new TemplateResponse('settings', 'settings/empty', [], '');
61
-		}
59
+        if (!$recoveryAdminEnabled && $privateKeySet) {
60
+            return new TemplateResponse('settings', 'settings/empty', [], '');
61
+        }
62 62
 
63
-		$userId = $this->userSession->getUser()->getUID();
64
-		$recoveryEnabledForUser = $this->util->isRecoveryEnabledForUser($userId);
63
+        $userId = $this->userSession->getUser()->getUID();
64
+        $recoveryEnabledForUser = $this->util->isRecoveryEnabledForUser($userId);
65 65
 
66
-		$parameters = [
67
-			'recoveryEnabled' => $recoveryAdminEnabled,
68
-			'recoveryEnabledForUser' => $recoveryEnabledForUser,
69
-			'privateKeySet' => $privateKeySet,
70
-			'initialized' => $this->session->getStatus(),
71
-		];
72
-		return new TemplateResponse('encryption', 'settings-personal', $parameters, '');
73
-	}
66
+        $parameters = [
67
+            'recoveryEnabled' => $recoveryAdminEnabled,
68
+            'recoveryEnabledForUser' => $recoveryEnabledForUser,
69
+            'privateKeySet' => $privateKeySet,
70
+            'initialized' => $this->session->getStatus(),
71
+        ];
72
+        return new TemplateResponse('encryption', 'settings-personal', $parameters, '');
73
+    }
74 74
 
75
-	/**
76
-	 * @return string the section ID, e.g. 'sharing'
77
-	 * @since 9.1
78
-	 */
79
-	public function getSection() {
80
-		return 'security';
81
-	}
75
+    /**
76
+     * @return string the section ID, e.g. 'sharing'
77
+     * @since 9.1
78
+     */
79
+    public function getSection() {
80
+        return 'security';
81
+    }
82 82
 
83
-	/**
84
-	 * @return int whether the form should be rather on the top or bottom of
85
-	 * the admin section. The forms are arranged in ascending order of the
86
-	 * priority values. It is required to return a value between 0 and 100.
87
-	 *
88
-	 * E.g.: 70
89
-	 * @since 9.1
90
-	 */
91
-	public function getPriority() {
92
-		return 80;
93
-	}
83
+    /**
84
+     * @return int whether the form should be rather on the top or bottom of
85
+     * the admin section. The forms are arranged in ascending order of the
86
+     * priority values. It is required to return a value between 0 and 100.
87
+     *
88
+     * E.g.: 70
89
+     * @since 9.1
90
+     */
91
+    public function getPriority() {
92
+        return 80;
93
+    }
94 94
 }
Please login to merge, or discard this patch.