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