Passed
Push — master ( 873501...d2df81 )
by Maxence
14:59 queued 12s
created
apps/user_ldap/lib/Jobs/Sync.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 	 */
104 104
 	protected function getMinPagingSize() {
105 105
 		$configKeys = $this->config->getAppKeys('user_ldap');
106
-		$configKeys = array_filter($configKeys, function ($key) {
106
+		$configKeys = array_filter($configKeys, function($key) {
107 107
 			return strpos($key, 'ldap_paging_size') !== false;
108 108
 		});
109 109
 		$minPagingSize = null;
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 			$pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
112 112
 			$minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
113 113
 		}
114
-		return (int)$minPagingSize;
114
+		return (int) $minPagingSize;
115 115
 	}
116 116
 
117 117
 	/**
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
 
165 165
 		$filter = $access->combineFilterWithAnd([
166 166
 			$access->connection->ldapUserFilter,
167
-			$access->connection->ldapUserDisplayName . '=*',
167
+			$access->connection->ldapUserDisplayName.'=*',
168 168
 			$access->getFilterPartForUserSearch('')
169 169
 		]);
170 170
 		$results = $access->fetchListOfUsers(
@@ -175,10 +175,10 @@  discard block
 block discarded – undo
175 175
 			true
176 176
 		);
177 177
 
178
-		if ((int)$connection->ldapPagingSize === 0) {
178
+		if ((int) $connection->ldapPagingSize === 0) {
179 179
 			return false;
180 180
 		}
181
-		return count($results) >= (int)$connection->ldapPagingSize;
181
+		return count($results) >= (int) $connection->ldapPagingSize;
182 182
 	}
183 183
 
184 184
 	/**
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 
196 196
 		$cycleData = [
197 197
 			'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
198
-			'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
198
+			'offset' => (int) $this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
199 199
 		];
200 200
 
201 201
 		if (
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 	 * @return bool
253 253
 	 */
254 254
 	public function qualifiesToRun($cycleData) {
255
-		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
255
+		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'].'_lastChange', 0);
256 256
 		if ((time() - $lastChange) > 60 * 30) {
257 257
 			return true;
258 258
 		}
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 	 */
267 267
 	protected function increaseOffset($cycleData) {
268 268
 		$ldapConfig = new Configuration($cycleData['prefix']);
269
-		$cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
269
+		$cycleData['offset'] += (int) $ldapConfig->ldapPagingSize;
270 270
 		$this->setCycle($cycleData);
271 271
 	}
272 272
 
Please login to merge, or discard this patch.
Indentation   +337 added lines, -337 removed lines patch added patch discarded remove patch
@@ -42,341 +42,341 @@
 block discarded – undo
42 42
 use Psr\Log\LoggerInterface;
43 43
 
44 44
 class Sync extends TimedJob {
45
-	public const MAX_INTERVAL = 12 * 60 * 60; // 12h
46
-	public const MIN_INTERVAL = 30 * 60; // 30min
47
-	/** @var  Helper */
48
-	protected $ldapHelper;
49
-	/** @var  LDAP */
50
-	protected $ldap;
51
-	/** @var  Manager */
52
-	protected $userManager;
53
-	/** @var UserMapping */
54
-	protected $mapper;
55
-	/** @var  IConfig */
56
-	protected $config;
57
-	/** @var  IAvatarManager */
58
-	protected $avatarManager;
59
-	/** @var  IDBConnection */
60
-	protected $dbc;
61
-	/** @var  IUserManager */
62
-	protected $ncUserManager;
63
-	/** @var  LoggerInterface */
64
-	protected $logger;
65
-	/** @var  IManager */
66
-	protected $notificationManager;
67
-	/** @var ConnectionFactory */
68
-	protected $connectionFactory;
69
-	/** @var AccessFactory */
70
-	protected $accessFactory;
71
-
72
-	public function __construct(Manager  $userManager, ITimeFactory $time) {
73
-		parent::__construct($time);
74
-		$this->userManager = $userManager;
75
-		$this->setInterval(
76
-			\OC::$server->getConfig()->getAppValue(
77
-				'user_ldap',
78
-				'background_sync_interval',
79
-				self::MIN_INTERVAL
80
-			)
81
-		);
82
-	}
83
-
84
-	/**
85
-	 * updates the interval
86
-	 *
87
-	 * the idea is to adjust the interval depending on the amount of known users
88
-	 * and the attempt to update each user one day. At most it would run every
89
-	 * 30 minutes, and at least every 12 hours.
90
-	 */
91
-	public function updateInterval() {
92
-		$minPagingSize = $this->getMinPagingSize();
93
-		$mappedUsers = $this->mapper->count();
94
-
95
-		$runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL
96
-			: $mappedUsers / $minPagingSize;
97
-		$interval = floor(24 * 60 * 60 / $runsPerDay);
98
-		$interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL);
99
-
100
-		$this->config->setAppValue('user_ldap', 'background_sync_interval', $interval);
101
-	}
102
-
103
-	/**
104
-	 * returns the smallest configured paging size
105
-	 * @return int
106
-	 */
107
-	protected function getMinPagingSize() {
108
-		$configKeys = $this->config->getAppKeys('user_ldap');
109
-		$configKeys = array_filter($configKeys, function ($key) {
110
-			return strpos($key, 'ldap_paging_size') !== false;
111
-		});
112
-		$minPagingSize = null;
113
-		foreach ($configKeys as $configKey) {
114
-			$pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
115
-			$minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
116
-		}
117
-		return (int)$minPagingSize;
118
-	}
119
-
120
-	/**
121
-	 * @param array $argument
122
-	 */
123
-	public function run($argument) {
124
-		$this->setArgument($argument);
125
-
126
-		$isBackgroundJobModeAjax = $this->config
127
-				->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
128
-		if ($isBackgroundJobModeAjax) {
129
-			return;
130
-		}
131
-
132
-		$cycleData = $this->getCycle();
133
-		if ($cycleData === null) {
134
-			$cycleData = $this->determineNextCycle();
135
-			if ($cycleData === null) {
136
-				$this->updateInterval();
137
-				return;
138
-			}
139
-		}
140
-
141
-		if (!$this->qualifiesToRun($cycleData)) {
142
-			$this->updateInterval();
143
-			return;
144
-		}
145
-
146
-		try {
147
-			$expectMoreResults = $this->runCycle($cycleData);
148
-			if ($expectMoreResults) {
149
-				$this->increaseOffset($cycleData);
150
-			} else {
151
-				$this->determineNextCycle($cycleData);
152
-			}
153
-			$this->updateInterval();
154
-		} catch (ServerNotAvailableException $e) {
155
-			$this->determineNextCycle($cycleData);
156
-		}
157
-	}
158
-
159
-	/**
160
-	 * @param array $cycleData
161
-	 * @return bool whether more results are expected from the same configuration
162
-	 */
163
-	public function runCycle($cycleData) {
164
-		$connection = $this->connectionFactory->get($cycleData['prefix']);
165
-		$access = $this->accessFactory->get($connection);
166
-		$access->setUserMapper($this->mapper);
167
-
168
-		$filter = $access->combineFilterWithAnd([
169
-			$access->connection->ldapUserFilter,
170
-			$access->connection->ldapUserDisplayName . '=*',
171
-			$access->getFilterPartForUserSearch('')
172
-		]);
173
-		$results = $access->fetchListOfUsers(
174
-			$filter,
175
-			$access->userManager->getAttributes(),
176
-			$connection->ldapPagingSize,
177
-			$cycleData['offset'],
178
-			true
179
-		);
180
-
181
-		if ((int)$connection->ldapPagingSize === 0) {
182
-			return false;
183
-		}
184
-		return count($results) >= (int)$connection->ldapPagingSize;
185
-	}
186
-
187
-	/**
188
-	 * returns the info about the current cycle that should be run, if any,
189
-	 * otherwise null
190
-	 *
191
-	 * @return array|null
192
-	 */
193
-	public function getCycle() {
194
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
195
-		if (count($prefixes) === 0) {
196
-			return null;
197
-		}
198
-
199
-		$cycleData = [
200
-			'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
201
-			'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
202
-		];
203
-
204
-		if (
205
-			$cycleData['prefix'] !== null
206
-			&& in_array($cycleData['prefix'], $prefixes)
207
-		) {
208
-			return $cycleData;
209
-		}
210
-
211
-		return null;
212
-	}
213
-
214
-	/**
215
-	 * Save the provided cycle information in the DB
216
-	 *
217
-	 * @param array $cycleData
218
-	 */
219
-	public function setCycle(array $cycleData) {
220
-		$this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']);
221
-		$this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']);
222
-	}
223
-
224
-	/**
225
-	 * returns data about the next cycle that should run, if any, otherwise
226
-	 * null. It also always goes for the next LDAP configuration!
227
-	 *
228
-	 * @param array|null $cycleData the old cycle
229
-	 * @return array|null
230
-	 */
231
-	public function determineNextCycle(array $cycleData = null) {
232
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
233
-		if (count($prefixes) === 0) {
234
-			return null;
235
-		}
236
-
237
-		// get the next prefix in line and remember it
238
-		$oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
239
-		$prefix = $this->getNextPrefix($oldPrefix);
240
-		if ($prefix === null) {
241
-			return null;
242
-		}
243
-		$cycleData['prefix'] = $prefix;
244
-		$cycleData['offset'] = 0;
245
-		$this->setCycle(['prefix' => $prefix, 'offset' => 0]);
246
-
247
-		return $cycleData;
248
-	}
249
-
250
-	/**
251
-	 * Checks whether the provided cycle should be run. Currently only the
252
-	 * last configuration change goes into account (at least one hour).
253
-	 *
254
-	 * @param $cycleData
255
-	 * @return bool
256
-	 */
257
-	public function qualifiesToRun($cycleData) {
258
-		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
259
-		if ((time() - $lastChange) > 60 * 30) {
260
-			return true;
261
-		}
262
-		return false;
263
-	}
264
-
265
-	/**
266
-	 * increases the offset of the current cycle for the next run
267
-	 *
268
-	 * @param $cycleData
269
-	 */
270
-	protected function increaseOffset($cycleData) {
271
-		$ldapConfig = new Configuration($cycleData['prefix']);
272
-		$cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
273
-		$this->setCycle($cycleData);
274
-	}
275
-
276
-	/**
277
-	 * determines the next configuration prefix based on the last one (if any)
278
-	 *
279
-	 * @param string|null $lastPrefix
280
-	 * @return string|null
281
-	 */
282
-	protected function getNextPrefix($lastPrefix) {
283
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
284
-		$noOfPrefixes = count($prefixes);
285
-		if ($noOfPrefixes === 0) {
286
-			return null;
287
-		}
288
-		$i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
289
-		if ($i === false) {
290
-			$i = -1;
291
-		} else {
292
-			$i++;
293
-		}
294
-
295
-		if (!isset($prefixes[$i])) {
296
-			$i = 0;
297
-		}
298
-		return $prefixes[$i];
299
-	}
300
-
301
-	/**
302
-	 * "fixes" DI
303
-	 */
304
-	public function setArgument($argument) {
305
-		if (isset($argument['config'])) {
306
-			$this->config = $argument['config'];
307
-		} else {
308
-			$this->config = \OC::$server->getConfig();
309
-		}
310
-
311
-		if (isset($argument['helper'])) {
312
-			$this->ldapHelper = $argument['helper'];
313
-		} else {
314
-			$this->ldapHelper = new Helper($this->config, \OC::$server->getDatabaseConnection());
315
-		}
316
-
317
-		if (isset($argument['ldapWrapper'])) {
318
-			$this->ldap = $argument['ldapWrapper'];
319
-		} else {
320
-			$this->ldap = new LDAP($this->config->getSystemValueString('ldap_log_file'));
321
-		}
322
-
323
-		if (isset($argument['avatarManager'])) {
324
-			$this->avatarManager = $argument['avatarManager'];
325
-		} else {
326
-			$this->avatarManager = \OC::$server->getAvatarManager();
327
-		}
328
-
329
-		if (isset($argument['dbc'])) {
330
-			$this->dbc = $argument['dbc'];
331
-		} else {
332
-			$this->dbc = \OC::$server->getDatabaseConnection();
333
-		}
334
-
335
-		if (isset($argument['ncUserManager'])) {
336
-			$this->ncUserManager = $argument['ncUserManager'];
337
-		} else {
338
-			$this->ncUserManager = \OC::$server->getUserManager();
339
-		}
340
-
341
-		if (isset($argument['logger'])) {
342
-			$this->logger = $argument['logger'];
343
-		} else {
344
-			$this->logger = \OC::$server->get(LoggerInterface::class);
345
-		}
346
-
347
-		if (isset($argument['notificationManager'])) {
348
-			$this->notificationManager = $argument['notificationManager'];
349
-		} else {
350
-			$this->notificationManager = \OC::$server->getNotificationManager();
351
-		}
352
-
353
-		if (isset($argument['userManager'])) {
354
-			$this->userManager = $argument['userManager'];
355
-		}
356
-
357
-		if (isset($argument['mapper'])) {
358
-			$this->mapper = $argument['mapper'];
359
-		} else {
360
-			$this->mapper = \OCP\Server::get(UserMapping::class);
361
-		}
362
-
363
-		if (isset($argument['connectionFactory'])) {
364
-			$this->connectionFactory = $argument['connectionFactory'];
365
-		} else {
366
-			$this->connectionFactory = new ConnectionFactory($this->ldap);
367
-		}
368
-
369
-		if (isset($argument['accessFactory'])) {
370
-			$this->accessFactory = $argument['accessFactory'];
371
-		} else {
372
-			$this->accessFactory = new AccessFactory(
373
-				$this->ldap,
374
-				$this->userManager,
375
-				$this->ldapHelper,
376
-				$this->config,
377
-				$this->ncUserManager,
378
-				$this->logger
379
-			);
380
-		}
381
-	}
45
+    public const MAX_INTERVAL = 12 * 60 * 60; // 12h
46
+    public const MIN_INTERVAL = 30 * 60; // 30min
47
+    /** @var  Helper */
48
+    protected $ldapHelper;
49
+    /** @var  LDAP */
50
+    protected $ldap;
51
+    /** @var  Manager */
52
+    protected $userManager;
53
+    /** @var UserMapping */
54
+    protected $mapper;
55
+    /** @var  IConfig */
56
+    protected $config;
57
+    /** @var  IAvatarManager */
58
+    protected $avatarManager;
59
+    /** @var  IDBConnection */
60
+    protected $dbc;
61
+    /** @var  IUserManager */
62
+    protected $ncUserManager;
63
+    /** @var  LoggerInterface */
64
+    protected $logger;
65
+    /** @var  IManager */
66
+    protected $notificationManager;
67
+    /** @var ConnectionFactory */
68
+    protected $connectionFactory;
69
+    /** @var AccessFactory */
70
+    protected $accessFactory;
71
+
72
+    public function __construct(Manager  $userManager, ITimeFactory $time) {
73
+        parent::__construct($time);
74
+        $this->userManager = $userManager;
75
+        $this->setInterval(
76
+            \OC::$server->getConfig()->getAppValue(
77
+                'user_ldap',
78
+                'background_sync_interval',
79
+                self::MIN_INTERVAL
80
+            )
81
+        );
82
+    }
83
+
84
+    /**
85
+     * updates the interval
86
+     *
87
+     * the idea is to adjust the interval depending on the amount of known users
88
+     * and the attempt to update each user one day. At most it would run every
89
+     * 30 minutes, and at least every 12 hours.
90
+     */
91
+    public function updateInterval() {
92
+        $minPagingSize = $this->getMinPagingSize();
93
+        $mappedUsers = $this->mapper->count();
94
+
95
+        $runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL
96
+            : $mappedUsers / $minPagingSize;
97
+        $interval = floor(24 * 60 * 60 / $runsPerDay);
98
+        $interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL);
99
+
100
+        $this->config->setAppValue('user_ldap', 'background_sync_interval', $interval);
101
+    }
102
+
103
+    /**
104
+     * returns the smallest configured paging size
105
+     * @return int
106
+     */
107
+    protected function getMinPagingSize() {
108
+        $configKeys = $this->config->getAppKeys('user_ldap');
109
+        $configKeys = array_filter($configKeys, function ($key) {
110
+            return strpos($key, 'ldap_paging_size') !== false;
111
+        });
112
+        $minPagingSize = null;
113
+        foreach ($configKeys as $configKey) {
114
+            $pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
115
+            $minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
116
+        }
117
+        return (int)$minPagingSize;
118
+    }
119
+
120
+    /**
121
+     * @param array $argument
122
+     */
123
+    public function run($argument) {
124
+        $this->setArgument($argument);
125
+
126
+        $isBackgroundJobModeAjax = $this->config
127
+                ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
128
+        if ($isBackgroundJobModeAjax) {
129
+            return;
130
+        }
131
+
132
+        $cycleData = $this->getCycle();
133
+        if ($cycleData === null) {
134
+            $cycleData = $this->determineNextCycle();
135
+            if ($cycleData === null) {
136
+                $this->updateInterval();
137
+                return;
138
+            }
139
+        }
140
+
141
+        if (!$this->qualifiesToRun($cycleData)) {
142
+            $this->updateInterval();
143
+            return;
144
+        }
145
+
146
+        try {
147
+            $expectMoreResults = $this->runCycle($cycleData);
148
+            if ($expectMoreResults) {
149
+                $this->increaseOffset($cycleData);
150
+            } else {
151
+                $this->determineNextCycle($cycleData);
152
+            }
153
+            $this->updateInterval();
154
+        } catch (ServerNotAvailableException $e) {
155
+            $this->determineNextCycle($cycleData);
156
+        }
157
+    }
158
+
159
+    /**
160
+     * @param array $cycleData
161
+     * @return bool whether more results are expected from the same configuration
162
+     */
163
+    public function runCycle($cycleData) {
164
+        $connection = $this->connectionFactory->get($cycleData['prefix']);
165
+        $access = $this->accessFactory->get($connection);
166
+        $access->setUserMapper($this->mapper);
167
+
168
+        $filter = $access->combineFilterWithAnd([
169
+            $access->connection->ldapUserFilter,
170
+            $access->connection->ldapUserDisplayName . '=*',
171
+            $access->getFilterPartForUserSearch('')
172
+        ]);
173
+        $results = $access->fetchListOfUsers(
174
+            $filter,
175
+            $access->userManager->getAttributes(),
176
+            $connection->ldapPagingSize,
177
+            $cycleData['offset'],
178
+            true
179
+        );
180
+
181
+        if ((int)$connection->ldapPagingSize === 0) {
182
+            return false;
183
+        }
184
+        return count($results) >= (int)$connection->ldapPagingSize;
185
+    }
186
+
187
+    /**
188
+     * returns the info about the current cycle that should be run, if any,
189
+     * otherwise null
190
+     *
191
+     * @return array|null
192
+     */
193
+    public function getCycle() {
194
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
195
+        if (count($prefixes) === 0) {
196
+            return null;
197
+        }
198
+
199
+        $cycleData = [
200
+            'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
201
+            'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
202
+        ];
203
+
204
+        if (
205
+            $cycleData['prefix'] !== null
206
+            && in_array($cycleData['prefix'], $prefixes)
207
+        ) {
208
+            return $cycleData;
209
+        }
210
+
211
+        return null;
212
+    }
213
+
214
+    /**
215
+     * Save the provided cycle information in the DB
216
+     *
217
+     * @param array $cycleData
218
+     */
219
+    public function setCycle(array $cycleData) {
220
+        $this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']);
221
+        $this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']);
222
+    }
223
+
224
+    /**
225
+     * returns data about the next cycle that should run, if any, otherwise
226
+     * null. It also always goes for the next LDAP configuration!
227
+     *
228
+     * @param array|null $cycleData the old cycle
229
+     * @return array|null
230
+     */
231
+    public function determineNextCycle(array $cycleData = null) {
232
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
233
+        if (count($prefixes) === 0) {
234
+            return null;
235
+        }
236
+
237
+        // get the next prefix in line and remember it
238
+        $oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
239
+        $prefix = $this->getNextPrefix($oldPrefix);
240
+        if ($prefix === null) {
241
+            return null;
242
+        }
243
+        $cycleData['prefix'] = $prefix;
244
+        $cycleData['offset'] = 0;
245
+        $this->setCycle(['prefix' => $prefix, 'offset' => 0]);
246
+
247
+        return $cycleData;
248
+    }
249
+
250
+    /**
251
+     * Checks whether the provided cycle should be run. Currently only the
252
+     * last configuration change goes into account (at least one hour).
253
+     *
254
+     * @param $cycleData
255
+     * @return bool
256
+     */
257
+    public function qualifiesToRun($cycleData) {
258
+        $lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
259
+        if ((time() - $lastChange) > 60 * 30) {
260
+            return true;
261
+        }
262
+        return false;
263
+    }
264
+
265
+    /**
266
+     * increases the offset of the current cycle for the next run
267
+     *
268
+     * @param $cycleData
269
+     */
270
+    protected function increaseOffset($cycleData) {
271
+        $ldapConfig = new Configuration($cycleData['prefix']);
272
+        $cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
273
+        $this->setCycle($cycleData);
274
+    }
275
+
276
+    /**
277
+     * determines the next configuration prefix based on the last one (if any)
278
+     *
279
+     * @param string|null $lastPrefix
280
+     * @return string|null
281
+     */
282
+    protected function getNextPrefix($lastPrefix) {
283
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
284
+        $noOfPrefixes = count($prefixes);
285
+        if ($noOfPrefixes === 0) {
286
+            return null;
287
+        }
288
+        $i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
289
+        if ($i === false) {
290
+            $i = -1;
291
+        } else {
292
+            $i++;
293
+        }
294
+
295
+        if (!isset($prefixes[$i])) {
296
+            $i = 0;
297
+        }
298
+        return $prefixes[$i];
299
+    }
300
+
301
+    /**
302
+     * "fixes" DI
303
+     */
304
+    public function setArgument($argument) {
305
+        if (isset($argument['config'])) {
306
+            $this->config = $argument['config'];
307
+        } else {
308
+            $this->config = \OC::$server->getConfig();
309
+        }
310
+
311
+        if (isset($argument['helper'])) {
312
+            $this->ldapHelper = $argument['helper'];
313
+        } else {
314
+            $this->ldapHelper = new Helper($this->config, \OC::$server->getDatabaseConnection());
315
+        }
316
+
317
+        if (isset($argument['ldapWrapper'])) {
318
+            $this->ldap = $argument['ldapWrapper'];
319
+        } else {
320
+            $this->ldap = new LDAP($this->config->getSystemValueString('ldap_log_file'));
321
+        }
322
+
323
+        if (isset($argument['avatarManager'])) {
324
+            $this->avatarManager = $argument['avatarManager'];
325
+        } else {
326
+            $this->avatarManager = \OC::$server->getAvatarManager();
327
+        }
328
+
329
+        if (isset($argument['dbc'])) {
330
+            $this->dbc = $argument['dbc'];
331
+        } else {
332
+            $this->dbc = \OC::$server->getDatabaseConnection();
333
+        }
334
+
335
+        if (isset($argument['ncUserManager'])) {
336
+            $this->ncUserManager = $argument['ncUserManager'];
337
+        } else {
338
+            $this->ncUserManager = \OC::$server->getUserManager();
339
+        }
340
+
341
+        if (isset($argument['logger'])) {
342
+            $this->logger = $argument['logger'];
343
+        } else {
344
+            $this->logger = \OC::$server->get(LoggerInterface::class);
345
+        }
346
+
347
+        if (isset($argument['notificationManager'])) {
348
+            $this->notificationManager = $argument['notificationManager'];
349
+        } else {
350
+            $this->notificationManager = \OC::$server->getNotificationManager();
351
+        }
352
+
353
+        if (isset($argument['userManager'])) {
354
+            $this->userManager = $argument['userManager'];
355
+        }
356
+
357
+        if (isset($argument['mapper'])) {
358
+            $this->mapper = $argument['mapper'];
359
+        } else {
360
+            $this->mapper = \OCP\Server::get(UserMapping::class);
361
+        }
362
+
363
+        if (isset($argument['connectionFactory'])) {
364
+            $this->connectionFactory = $argument['connectionFactory'];
365
+        } else {
366
+            $this->connectionFactory = new ConnectionFactory($this->ldap);
367
+        }
368
+
369
+        if (isset($argument['accessFactory'])) {
370
+            $this->accessFactory = $argument['accessFactory'];
371
+        } else {
372
+            $this->accessFactory = new AccessFactory(
373
+                $this->ldap,
374
+                $this->userManager,
375
+                $this->ldapHelper,
376
+                $this->config,
377
+                $this->ncUserManager,
378
+                $this->logger
379
+            );
380
+        }
381
+    }
382 382
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Migration/UUIDFixInsert.php 2 patches
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -33,69 +33,69 @@
 block discarded – undo
33 33
 
34 34
 class UUIDFixInsert implements IRepairStep {
35 35
 
36
-	/** @var IConfig */
37
-	protected $config;
36
+    /** @var IConfig */
37
+    protected $config;
38 38
 
39
-	/** @var UserMapping */
40
-	protected $userMapper;
39
+    /** @var UserMapping */
40
+    protected $userMapper;
41 41
 
42
-	/** @var GroupMapping */
43
-	protected $groupMapper;
42
+    /** @var GroupMapping */
43
+    protected $groupMapper;
44 44
 
45
-	/** @var IJobList */
46
-	protected $jobList;
45
+    /** @var IJobList */
46
+    protected $jobList;
47 47
 
48
-	public function __construct(IConfig $config, UserMapping $userMapper, GroupMapping $groupMapper, IJobList $jobList) {
49
-		$this->config = $config;
50
-		$this->userMapper = $userMapper;
51
-		$this->groupMapper = $groupMapper;
52
-		$this->jobList = $jobList;
53
-	}
48
+    public function __construct(IConfig $config, UserMapping $userMapper, GroupMapping $groupMapper, IJobList $jobList) {
49
+        $this->config = $config;
50
+        $this->userMapper = $userMapper;
51
+        $this->groupMapper = $groupMapper;
52
+        $this->jobList = $jobList;
53
+    }
54 54
 
55
-	/**
56
-	 * Returns the step's name
57
-	 *
58
-	 * @return string
59
-	 * @since 9.1.0
60
-	 */
61
-	public function getName() {
62
-		return 'Insert UUIDFix background job for user and group in batches';
63
-	}
55
+    /**
56
+     * Returns the step's name
57
+     *
58
+     * @return string
59
+     * @since 9.1.0
60
+     */
61
+    public function getName() {
62
+        return 'Insert UUIDFix background job for user and group in batches';
63
+    }
64 64
 
65
-	/**
66
-	 * Run repair step.
67
-	 * Must throw exception on error.
68
-	 *
69
-	 * @param IOutput $output
70
-	 * @throws \Exception in case of failure
71
-	 * @since 9.1.0
72
-	 */
73
-	public function run(IOutput $output) {
74
-		$installedVersion = $this->config->getAppValue('user_ldap', 'installed_version', '1.2.1');
75
-		if (version_compare($installedVersion, '1.2.1') !== -1) {
76
-			return;
77
-		}
65
+    /**
66
+     * Run repair step.
67
+     * Must throw exception on error.
68
+     *
69
+     * @param IOutput $output
70
+     * @throws \Exception in case of failure
71
+     * @since 9.1.0
72
+     */
73
+    public function run(IOutput $output) {
74
+        $installedVersion = $this->config->getAppValue('user_ldap', 'installed_version', '1.2.1');
75
+        if (version_compare($installedVersion, '1.2.1') !== -1) {
76
+            return;
77
+        }
78 78
 
79
-		foreach ([$this->userMapper, $this->groupMapper] as $mapper) {
80
-			$offset = 0;
81
-			$batchSize = 50;
82
-			$jobClass = $mapper instanceof UserMapping ? UUIDFixUser::class : UUIDFixGroup::class;
83
-			do {
84
-				$retry = false;
85
-				$records = $mapper->getList($offset, $batchSize);
86
-				if (count($records) === 0) {
87
-					continue;
88
-				}
89
-				try {
90
-					$this->jobList->add($jobClass, ['records' => $records]);
91
-					$offset += $batchSize;
92
-				} catch (\InvalidArgumentException $e) {
93
-					if (strpos($e->getMessage(), 'Background job arguments can\'t exceed 4000') !== false) {
94
-						$batchSize = (int)floor(count($records) * 0.8);
95
-						$retry = true;
96
-					}
97
-				}
98
-			} while (count($records) === $batchSize || $retry);
99
-		}
100
-	}
79
+        foreach ([$this->userMapper, $this->groupMapper] as $mapper) {
80
+            $offset = 0;
81
+            $batchSize = 50;
82
+            $jobClass = $mapper instanceof UserMapping ? UUIDFixUser::class : UUIDFixGroup::class;
83
+            do {
84
+                $retry = false;
85
+                $records = $mapper->getList($offset, $batchSize);
86
+                if (count($records) === 0) {
87
+                    continue;
88
+                }
89
+                try {
90
+                    $this->jobList->add($jobClass, ['records' => $records]);
91
+                    $offset += $batchSize;
92
+                } catch (\InvalidArgumentException $e) {
93
+                    if (strpos($e->getMessage(), 'Background job arguments can\'t exceed 4000') !== false) {
94
+                        $batchSize = (int)floor(count($records) * 0.8);
95
+                        $retry = true;
96
+                    }
97
+                }
98
+            } while (count($records) === $batchSize || $retry);
99
+        }
100
+    }
101 101
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@
 block discarded – undo
91 91
 					$offset += $batchSize;
92 92
 				} catch (\InvalidArgumentException $e) {
93 93
 					if (strpos($e->getMessage(), 'Background job arguments can\'t exceed 4000') !== false) {
94
-						$batchSize = (int)floor(count($records) * 0.8);
94
+						$batchSize = (int) floor(count($records) * 0.8);
95 95
 						$retry = true;
96 96
 					}
97 97
 				}
Please login to merge, or discard this patch.
apps/user_ldap/templates/renewpassword.php 1 patch
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -24,14 +24,14 @@  discard block
 block discarded – undo
24 24
 		<?php endif; ?>
25 25
 		<div id="message" class="hidden">
26 26
 			<img class="float-spinner" alt=""
27
-				src="<?php p(image_path('core', 'loading-dark.gif'));?>">
27
+				src="<?php p(image_path('core', 'loading-dark.gif')); ?>">
28 28
 			<span id="messageText"></span>
29 29
 			<!-- the following div ensures that the spinner is always inside the #message div -->
30 30
 			<div style="clear: both;"></div>
31 31
 		</div>
32 32
 		<p class="grouptop">
33 33
 			<input type="password" id="oldPassword" name="oldPassword"
34
-				placeholder="<?php echo $l->t('Current password');?>"
34
+				placeholder="<?php echo $l->t('Current password'); ?>"
35 35
 				autofocus autocomplete="off" autocapitalize="off" autocorrect="off" required/>
36 36
 			<label for="oldPassword" class="infield"><?php p($l->t('Current password')); ?></label>
37 37
 		</p>
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 			<input type="checkbox" id="personal-show" name="show" class="hidden-visually" /><label for="personal-show"></label>
41 41
 			<label id="newPassword-label" for="newPassword" class="infield"><?php p($l->t('New password')); ?></label>
42 42
 			<input type="password" id="newPassword" name="newPassword"
43
-				placeholder="<?php echo $l->t('New password');?>"
43
+				placeholder="<?php echo $l->t('New password'); ?>"
44 44
 				data-typetoggle="#personal-show" autofocus autocomplete="off" autocapitalize="off" autocorrect="off" required/>
45 45
 		</p>
46 46
 		
Please login to merge, or discard this patch.
apps/user_ldap/templates/part.wizard-server.php 2 patches
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -2,15 +2,15 @@
 block discarded – undo
2 2
 		<p>
3 3
 		<select id="ldap_serverconfig_chooser" name="ldap_serverconfig_chooser">
4 4
 		<?php
5
-		$i = 1;
6
-		$sel = ' selected';
7
-		foreach ($_['serverConfigurationPrefixes'] as $prefix) {
8
-			?>
5
+        $i = 1;
6
+        $sel = ' selected';
7
+        foreach ($_['serverConfigurationPrefixes'] as $prefix) {
8
+            ?>
9 9
 			<option value="<?php p($prefix); ?>"<?php p($sel);
10
-			$sel = ''; ?>><?php p($l->t('%s. Server:', [$i++])); ?> <?php p(' '.$_['serverConfigurationHosts'][$prefix]); ?></option>
10
+            $sel = ''; ?>><?php p($l->t('%s. Server:', [$i++])); ?> <?php p(' '.$_['serverConfigurationHosts'][$prefix]); ?></option>
11 11
 			<?php
12
-		}
13
-		?>
12
+        }
13
+        ?>
14 14
 		</select>
15 15
 		<button type="button" id="ldap_action_add_configuration"
16 16
 			name="ldap_action_add_configuration" class="icon-add icon-default-style"
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -14,14 +14,14 @@  discard block
 block discarded – undo
14 14
 		</select>
15 15
 		<button type="button" id="ldap_action_add_configuration"
16 16
 			name="ldap_action_add_configuration" class="icon-add icon-default-style"
17
-			title="<?php p($l->t('Add a new configuration'));?>">&nbsp;</button>
17
+			title="<?php p($l->t('Add a new configuration')); ?>">&nbsp;</button>
18 18
 		<button type="button" id="ldap_action_copy_configuration"
19 19
 			name="ldap_action_copy_configuration"
20 20
 			class="ldapIconCopy icon-default-style"
21
-			title="<?php p($l->t('Copy current configuration into new directory binding'));?>">&nbsp;</button>
21
+			title="<?php p($l->t('Copy current configuration into new directory binding')); ?>">&nbsp;</button>
22 22
 		<button type="button" id="ldap_action_delete_configuration"
23 23
 			name="ldap_action_delete_configuration" class="icon-delete icon-default-style"
24
-			title="<?php p($l->t('Delete the current configuration'));?>">&nbsp;</button>
24
+			title="<?php p($l->t('Delete the current configuration')); ?>">&nbsp;</button>
25 25
 		</p>
26 26
 
27 27
 		<div class="hostPortCombinator">
@@ -30,14 +30,14 @@  discard block
 block discarded – undo
30 30
 					<div class="table">
31 31
 						<input type="text" class="host" id="ldap_host"
32 32
 							name="ldap_host"
33
-							placeholder="<?php p($l->t('Host'));?>"
34
-							title="<?php p($l->t('You can omit the protocol, unless you require SSL. If so, start with ldaps://'));?>"
33
+							placeholder="<?php p($l->t('Host')); ?>"
34
+							title="<?php p($l->t('You can omit the protocol, unless you require SSL. If so, start with ldaps://')); ?>"
35 35
 							/>
36 36
 						<span class="hostPortCombinatorSpan">
37 37
 							<input type="number" id="ldap_port" name="ldap_port"
38
-								placeholder="<?php p($l->t('Port'));?>" />
38
+								placeholder="<?php p($l->t('Port')); ?>" />
39 39
 							<button class="ldapDetectPort" name="ldapDetectPort" type="button">
40
-								<?php p($l->t('Detect Port'));?>
40
+								<?php p($l->t('Detect Port')); ?>
41 41
 							</button>
42 42
 						</span>
43 43
 					</div>
@@ -47,19 +47,19 @@  discard block
 block discarded – undo
47 47
 			<div class="tablerow">
48 48
 				<input type="text" id="ldap_dn" name="ldap_dn"
49 49
 				class="tablecell"
50
-				placeholder="<?php p($l->t('User DN'));?>" autocomplete="off"
51
-				title="<?php p($l->t('The DN of the client user with which the bind shall be done, e.g. uid=agent,dc=example,dc=com. For anonymous access, leave DN and Password empty.'));?>"
50
+				placeholder="<?php p($l->t('User DN')); ?>" autocomplete="off"
51
+				title="<?php p($l->t('The DN of the client user with which the bind shall be done, e.g. uid=agent,dc=example,dc=com. For anonymous access, leave DN and Password empty.')); ?>"
52 52
 				/>
53 53
 			</div>
54 54
 
55 55
 			<div class="tablerow">
56 56
 				<input type="password" id="ldap_agent_password"
57 57
 				class="tablecell" name="ldap_agent_password"
58
-				placeholder="<?php p($l->t('Password'));?>" autocomplete="off"
59
-				title="<?php p($l->t('For anonymous access, leave DN and Password empty.'));?>"
58
+				placeholder="<?php p($l->t('Password')); ?>" autocomplete="off"
59
+				title="<?php p($l->t('For anonymous access, leave DN and Password empty.')); ?>"
60 60
 				/>
61 61
 				<button class="ldapSaveAgentCredentials" name="ldapSaveAgentCredentials" type="button">
62
-					<?php p($l->t('Save Credentials'));?>
62
+					<?php p($l->t('Save Credentials')); ?>
63 63
 				</button>
64 64
 			</div>
65 65
 			<div class="tablerow">&nbsp;</div>
@@ -67,24 +67,24 @@  discard block
 block discarded – undo
67 67
 			<div class="tablerow">
68 68
 				<textarea id="ldap_base" name="ldap_base"
69 69
 					class="tablecell"
70
-					placeholder="<?php p($l->t('One Base DN per line'));?>"
71
-					title="<?php p($l->t('You can specify Base DN for users and groups in the Advanced tab'));?>">
70
+					placeholder="<?php p($l->t('One Base DN per line')); ?>"
71
+					title="<?php p($l->t('You can specify Base DN for users and groups in the Advanced tab')); ?>">
72 72
 				</textarea>
73 73
 				<button class="ldapDetectBase" name="ldapDetectBase" type="button">
74
-					<?php p($l->t('Detect Base DN'));?>
74
+					<?php p($l->t('Detect Base DN')); ?>
75 75
 				</button>
76 76
 				<button class="ldapTestBase" name="ldapTestBase" type="button">
77
-					<?php p($l->t('Test Base DN'));?>
77
+					<?php p($l->t('Test Base DN')); ?>
78 78
 				</button>
79 79
 			</div>
80 80
 
81 81
 			<div class="tablerow left">
82 82
 				<input type="checkbox" id="ldap_experienced_admin" value="1"
83 83
 					name="ldap_experienced_admin" class="tablecell"
84
-					title="<?php p($l->t('Avoids automatic LDAP requests. Better for bigger setups, but requires some LDAP knowledge.'));?>"
84
+					title="<?php p($l->t('Avoids automatic LDAP requests. Better for bigger setups, but requires some LDAP knowledge.')); ?>"
85 85
 					/>
86 86
 				<label for="ldap_experienced_admin" class="tablecell">
87
-					<?php p($l->t('Manually enter LDAP filters (recommended for large directories)'));?>
87
+					<?php p($l->t('Manually enter LDAP filters (recommended for large directories)')); ?>
88 88
 				</label>
89 89
 			</div>
90 90
 
Please login to merge, or discard this patch.
apps/user_ldap/ajax/setConfiguration.php 2 patches
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -36,11 +36,11 @@
 block discarded – undo
36 36
 // only legacy checkboxes (Advanced and Expert tab) need to be handled here,
37 37
 // the Wizard-like tabs handle it on their own
38 38
 $chkboxes = ['ldap_configuration_active', 'ldap_override_main_server',
39
-	'ldap_turn_off_cert_check'];
39
+    'ldap_turn_off_cert_check'];
40 40
 foreach ($chkboxes as $boxid) {
41
-	if (!isset($_POST[$boxid])) {
42
-		$_POST[$boxid] = 0;
43
-	}
41
+    if (!isset($_POST[$boxid])) {
42
+        $_POST[$boxid] = 0;
43
+    }
44 44
 }
45 45
 
46 46
 $ldapWrapper = new OCA\User_LDAP\LDAP();
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
 \OC_JSON::checkAppEnabled('user_ldap');
31 31
 \OC_JSON::callCheck();
32 32
 
33
-$prefix = (string)$_POST['ldap_serverconfig_chooser'];
33
+$prefix = (string) $_POST['ldap_serverconfig_chooser'];
34 34
 
35 35
 // Checkboxes are not submitted, when they are unchecked. Set them manually.
36 36
 // only legacy checkboxes (Advanced and Expert tab) need to be handled here,
Please login to merge, or discard this patch.
apps/user_ldap/ajax/wizard.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -39,13 +39,13 @@
 block discarded – undo
39 39
 if (!isset($_POST['action'])) {
40 40
 	\OC_JSON::error(['message' => $l->t('No action specified')]);
41 41
 }
42
-$action = (string)$_POST['action'];
42
+$action = (string) $_POST['action'];
43 43
 
44 44
 
45 45
 if (!isset($_POST['ldap_serverconfig_chooser'])) {
46 46
 	\OC_JSON::error(['message' => $l->t('No configuration specified')]);
47 47
 }
48
-$prefix = (string)$_POST['ldap_serverconfig_chooser'];
48
+$prefix = (string) $_POST['ldap_serverconfig_chooser'];
49 49
 
50 50
 $ldapWrapper = new \OCA\User_LDAP\LDAP();
51 51
 $configuration = new \OCA\User_LDAP\Configuration($prefix);
Please login to merge, or discard this patch.
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -34,12 +34,12 @@  discard block
 block discarded – undo
34 34
 $l = \OC::$server->getL10N('user_ldap');
35 35
 
36 36
 if (!isset($_POST['action'])) {
37
-	\OC_JSON::error(['message' => $l->t('No action specified')]);
37
+    \OC_JSON::error(['message' => $l->t('No action specified')]);
38 38
 }
39 39
 $action = (string)$_POST['action'];
40 40
 
41 41
 if (!isset($_POST['ldap_serverconfig_chooser'])) {
42
-	\OC_JSON::error(['message' => $l->t('No configuration specified')]);
42
+    \OC_JSON::error(['message' => $l->t('No configuration specified')]);
43 43
 }
44 44
 $prefix = (string)$_POST['ldap_serverconfig_chooser'];
45 45
 
@@ -57,79 +57,79 @@  discard block
 block discarded – undo
57 57
 $wizard = new \OCA\User_LDAP\Wizard($configuration, $ldapWrapper, $access);
58 58
 
59 59
 switch ($action) {
60
-	case 'guessPortAndTLS':
61
-	case 'guessBaseDN':
62
-	case 'detectEmailAttribute':
63
-	case 'detectUserDisplayNameAttribute':
64
-	case 'determineGroupMemberAssoc':
65
-	case 'determineUserObjectClasses':
66
-	case 'determineGroupObjectClasses':
67
-	case 'determineGroupsForUsers':
68
-	case 'determineGroupsForGroups':
69
-	case 'determineAttributes':
70
-	case 'getUserListFilter':
71
-	case 'getUserLoginFilter':
72
-	case 'getGroupFilter':
73
-	case 'countUsers':
74
-	case 'countGroups':
75
-	case 'countInBaseDN':
76
-		try {
77
-			$result = $wizard->$action();
78
-			if ($result !== false) {
79
-				\OC_JSON::success($result->getResultArray());
80
-				exit;
81
-			}
82
-		} catch (\Exception $e) {
83
-			\OC_JSON::error(['message' => $e->getMessage(), 'code' => $e->getCode()]);
84
-			exit;
85
-		}
86
-		\OC_JSON::error();
87
-		exit;
88
-		break;
60
+    case 'guessPortAndTLS':
61
+    case 'guessBaseDN':
62
+    case 'detectEmailAttribute':
63
+    case 'detectUserDisplayNameAttribute':
64
+    case 'determineGroupMemberAssoc':
65
+    case 'determineUserObjectClasses':
66
+    case 'determineGroupObjectClasses':
67
+    case 'determineGroupsForUsers':
68
+    case 'determineGroupsForGroups':
69
+    case 'determineAttributes':
70
+    case 'getUserListFilter':
71
+    case 'getUserLoginFilter':
72
+    case 'getGroupFilter':
73
+    case 'countUsers':
74
+    case 'countGroups':
75
+    case 'countInBaseDN':
76
+        try {
77
+            $result = $wizard->$action();
78
+            if ($result !== false) {
79
+                \OC_JSON::success($result->getResultArray());
80
+                exit;
81
+            }
82
+        } catch (\Exception $e) {
83
+            \OC_JSON::error(['message' => $e->getMessage(), 'code' => $e->getCode()]);
84
+            exit;
85
+        }
86
+        \OC_JSON::error();
87
+        exit;
88
+        break;
89 89
 
90
-	case 'testLoginName': {
91
-		try {
92
-			$loginName = $_POST['ldap_test_loginname'];
93
-			$result = $wizard->$action($loginName);
94
-			if ($result !== false) {
95
-				\OC_JSON::success($result->getResultArray());
96
-				exit;
97
-			}
98
-		} catch (\Exception $e) {
99
-			\OC_JSON::error(['message' => $e->getMessage()]);
100
-			exit;
101
-		}
102
-		\OC_JSON::error();
103
-		exit;
104
-		break;
105
-	}
90
+    case 'testLoginName': {
91
+        try {
92
+            $loginName = $_POST['ldap_test_loginname'];
93
+            $result = $wizard->$action($loginName);
94
+            if ($result !== false) {
95
+                \OC_JSON::success($result->getResultArray());
96
+                exit;
97
+            }
98
+        } catch (\Exception $e) {
99
+            \OC_JSON::error(['message' => $e->getMessage()]);
100
+            exit;
101
+        }
102
+        \OC_JSON::error();
103
+        exit;
104
+        break;
105
+    }
106 106
 
107
-	case 'save':
108
-		$key = isset($_POST['cfgkey']) ? $_POST['cfgkey'] : false;
109
-		$val = isset($_POST['cfgval']) ? $_POST['cfgval'] : null;
110
-		if ($key === false || is_null($val)) {
111
-			\OC_JSON::error(['message' => $l->t('No data specified')]);
112
-			exit;
113
-		}
114
-		if (is_array($key)) {
115
-			\OC_JSON::error(['message' => $l->t('Invalid data specified')]);
116
-			exit;
117
-		}
118
-		$cfg = [$key => $val];
119
-		$setParameters = [];
120
-		$configuration->setConfiguration($cfg, $setParameters);
121
-		if (!in_array($key, $setParameters)) {
122
-			\OC_JSON::error(['message' => $l->t($key.
123
-				' Could not set configuration %s', $setParameters[0])]);
124
-			exit;
125
-		}
126
-		$configuration->saveConfiguration();
127
-		//clear the cache on save
128
-		$connection = new \OCA\User_LDAP\Connection($ldapWrapper, $prefix);
129
-		$connection->clearCache();
130
-		\OC_JSON::success();
131
-		break;
132
-	default:
133
-		\OC_JSON::error(['message' => $l->t('Action does not exist')]);
134
-		break;
107
+    case 'save':
108
+        $key = isset($_POST['cfgkey']) ? $_POST['cfgkey'] : false;
109
+        $val = isset($_POST['cfgval']) ? $_POST['cfgval'] : null;
110
+        if ($key === false || is_null($val)) {
111
+            \OC_JSON::error(['message' => $l->t('No data specified')]);
112
+            exit;
113
+        }
114
+        if (is_array($key)) {
115
+            \OC_JSON::error(['message' => $l->t('Invalid data specified')]);
116
+            exit;
117
+        }
118
+        $cfg = [$key => $val];
119
+        $setParameters = [];
120
+        $configuration->setConfiguration($cfg, $setParameters);
121
+        if (!in_array($key, $setParameters)) {
122
+            \OC_JSON::error(['message' => $l->t($key.
123
+                ' Could not set configuration %s', $setParameters[0])]);
124
+            exit;
125
+        }
126
+        $configuration->saveConfiguration();
127
+        //clear the cache on save
128
+        $connection = new \OCA\User_LDAP\Connection($ldapWrapper, $prefix);
129
+        $connection->clearCache();
130
+        \OC_JSON::success();
131
+        break;
132
+    default:
133
+        \OC_JSON::error(['message' => $l->t('Action does not exist')]);
134
+        break;
135 135
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Recovery.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 		$encryptedRecoveryKey = $this->crypt->encryptPrivateKey($decryptedRecoveryKey, $newPassword);
127 127
 		$header = $this->crypt->generateHeader();
128 128
 		if ($encryptedRecoveryKey) {
129
-			$this->keyManager->setSystemPrivateKey($this->keyManager->getRecoveryKeyId(), $header . $encryptedRecoveryKey);
129
+			$this->keyManager->setSystemPrivateKey($this->keyManager->getRecoveryKeyId(), $header.$encryptedRecoveryKey);
130 130
 			return true;
131 131
 		}
132 132
 		return false;
@@ -187,9 +187,9 @@  discard block
 block discarded – undo
187 187
 				$value);
188 188
 
189 189
 			if ($value === '1') {
190
-				$this->addRecoveryKeys('/' . $this->user->getUID() . '/files/');
190
+				$this->addRecoveryKeys('/'.$this->user->getUID().'/files/');
191 191
 			} else {
192
-				$this->removeRecoveryKeys('/' . $this->user->getUID() . '/files/');
192
+				$this->removeRecoveryKeys('/'.$this->user->getUID().'/files/');
193 193
 			}
194 194
 
195 195
 			return true;
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 		foreach ($dirContent as $item) {
208 208
 			$filePath = $item->getPath();
209 209
 			if ($item['type'] === 'dir') {
210
-				$this->addRecoveryKeys($filePath . '/');
210
+				$this->addRecoveryKeys($filePath.'/');
211 211
 			} else {
212 212
 				$fileKey = $this->keyManager->getFileKey($filePath, $this->user->getUID());
213 213
 				if (!empty($fileKey)) {
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 		foreach ($dirContent as $item) {
236 236
 			$filePath = $item->getPath();
237 237
 			if ($item['type'] === 'dir') {
238
-				$this->removeRecoveryKeys($filePath . '/');
238
+				$this->removeRecoveryKeys($filePath.'/');
239 239
 			} else {
240 240
 				$this->keyManager->deleteShareKey($filePath, $this->keyManager->getRecoveryKeyId());
241 241
 			}
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 
254 254
 		$privateKey = $this->crypt->decryptPrivateKey($encryptedKey, $recoveryPassword);
255 255
 		if ($privateKey !== false) {
256
-			$this->recoverAllFiles('/' . $user . '/files/', $privateKey, $user);
256
+			$this->recoverAllFiles('/'.$user.'/files/', $privateKey, $user);
257 257
 		}
258 258
 	}
259 259
 
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 			// Get relative path from encryption/keyfiles
272 272
 			$filePath = $item->getPath();
273 273
 			if ($this->view->is_dir($filePath)) {
274
-				$this->recoverAllFiles($filePath . '/', $privateKey, $uid);
274
+				$this->recoverAllFiles($filePath.'/', $privateKey, $uid);
275 275
 			} else {
276 276
 				$this->recoverFile($filePath, $privateKey, $uid);
277 277
 			}
Please login to merge, or discard this patch.
Indentation   +270 added lines, -270 removed lines patch added patch discarded remove patch
@@ -37,274 +37,274 @@
 block discarded – undo
37 37
 class Recovery {
38 38
 
39 39
 
40
-	/**
41
-	 * @var null|IUser
42
-	 */
43
-	protected $user;
44
-	/**
45
-	 * @var Crypt
46
-	 */
47
-	protected $crypt;
48
-	/**
49
-	 * @var KeyManager
50
-	 */
51
-	private $keyManager;
52
-	/**
53
-	 * @var IConfig
54
-	 */
55
-	private $config;
56
-	/**
57
-	 * @var View
58
-	 */
59
-	private $view;
60
-	/**
61
-	 * @var IFile
62
-	 */
63
-	private $file;
64
-
65
-	/**
66
-	 * @param IUserSession $userSession
67
-	 * @param Crypt $crypt
68
-	 * @param KeyManager $keyManager
69
-	 * @param IConfig $config
70
-	 * @param IFile $file
71
-	 * @param View $view
72
-	 */
73
-	public function __construct(IUserSession $userSession,
74
-								Crypt $crypt,
75
-								KeyManager $keyManager,
76
-								IConfig $config,
77
-								IFile $file,
78
-								View $view) {
79
-		$this->user = ($userSession->isLoggedIn()) ? $userSession->getUser() : null;
80
-		$this->crypt = $crypt;
81
-		$this->keyManager = $keyManager;
82
-		$this->config = $config;
83
-		$this->view = $view;
84
-		$this->file = $file;
85
-	}
86
-
87
-	/**
88
-	 * @param string $password
89
-	 * @return bool
90
-	 */
91
-	public function enableAdminRecovery($password) {
92
-		$appConfig = $this->config;
93
-		$keyManager = $this->keyManager;
94
-
95
-		if (!$keyManager->recoveryKeyExists()) {
96
-			$keyPair = $this->crypt->createKeyPair();
97
-			if (!is_array($keyPair)) {
98
-				return false;
99
-			}
100
-
101
-			$this->keyManager->setRecoveryKey($password, $keyPair);
102
-		}
103
-
104
-		if ($keyManager->checkRecoveryPassword($password)) {
105
-			$appConfig->setAppValue('encryption', 'recoveryAdminEnabled', 1);
106
-			return true;
107
-		}
108
-
109
-		return false;
110
-	}
111
-
112
-	/**
113
-	 * change recovery key id
114
-	 *
115
-	 * @param string $newPassword
116
-	 * @param string $oldPassword
117
-	 * @return bool
118
-	 */
119
-	public function changeRecoveryKeyPassword($newPassword, $oldPassword) {
120
-		$recoveryKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
121
-		$decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $oldPassword);
122
-		if ($decryptedRecoveryKey === false) {
123
-			return false;
124
-		}
125
-		$encryptedRecoveryKey = $this->crypt->encryptPrivateKey($decryptedRecoveryKey, $newPassword);
126
-		$header = $this->crypt->generateHeader();
127
-		if ($encryptedRecoveryKey) {
128
-			$this->keyManager->setSystemPrivateKey($this->keyManager->getRecoveryKeyId(), $header . $encryptedRecoveryKey);
129
-			return true;
130
-		}
131
-		return false;
132
-	}
133
-
134
-	/**
135
-	 * @param string $recoveryPassword
136
-	 * @return bool
137
-	 */
138
-	public function disableAdminRecovery($recoveryPassword) {
139
-		$keyManager = $this->keyManager;
140
-
141
-		if ($keyManager->checkRecoveryPassword($recoveryPassword)) {
142
-			// Set recoveryAdmin as disabled
143
-			$this->config->setAppValue('encryption', 'recoveryAdminEnabled', 0);
144
-			return true;
145
-		}
146
-		return false;
147
-	}
148
-
149
-	/**
150
-	 * check if recovery is enabled for user
151
-	 *
152
-	 * @param string $user if no user is given we check the current logged-in user
153
-	 *
154
-	 * @return bool
155
-	 */
156
-	public function isRecoveryEnabledForUser($user = '') {
157
-		$uid = $user === '' ? $this->user->getUID() : $user;
158
-		$recoveryMode = $this->config->getUserValue($uid,
159
-			'encryption',
160
-			'recoveryEnabled',
161
-			0);
162
-
163
-		return ($recoveryMode === '1');
164
-	}
165
-
166
-	/**
167
-	 * check if recovery is key is enabled by the administrator
168
-	 *
169
-	 * @return bool
170
-	 */
171
-	public function isRecoveryKeyEnabled() {
172
-		$enabled = $this->config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
173
-
174
-		return ($enabled === '1');
175
-	}
176
-
177
-	/**
178
-	 * @param string $value
179
-	 * @return bool
180
-	 */
181
-	public function setRecoveryForUser($value) {
182
-		try {
183
-			$this->config->setUserValue($this->user->getUID(),
184
-				'encryption',
185
-				'recoveryEnabled',
186
-				$value);
187
-
188
-			if ($value === '1') {
189
-				$this->addRecoveryKeys('/' . $this->user->getUID() . '/files/');
190
-			} else {
191
-				$this->removeRecoveryKeys('/' . $this->user->getUID() . '/files/');
192
-			}
193
-
194
-			return true;
195
-		} catch (PreConditionNotMetException $e) {
196
-			return false;
197
-		}
198
-	}
199
-
200
-	/**
201
-	 * add recovery key to all encrypted files
202
-	 * @param string $path
203
-	 */
204
-	private function addRecoveryKeys($path) {
205
-		$dirContent = $this->view->getDirectoryContent($path);
206
-		foreach ($dirContent as $item) {
207
-			$filePath = $item->getPath();
208
-			if ($item['type'] === 'dir') {
209
-				$this->addRecoveryKeys($filePath . '/');
210
-			} else {
211
-				$fileKey = $this->keyManager->getFileKey($filePath, $this->user->getUID());
212
-				if (!empty($fileKey)) {
213
-					$accessList = $this->file->getAccessList($filePath);
214
-					$publicKeys = [];
215
-					foreach ($accessList['users'] as $uid) {
216
-						$publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
217
-					}
218
-
219
-					$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->user->getUID());
220
-
221
-					$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
222
-					$this->keyManager->setAllFileKeys($filePath, $encryptedKeyfiles);
223
-				}
224
-			}
225
-		}
226
-	}
227
-
228
-	/**
229
-	 * remove recovery key to all encrypted files
230
-	 * @param string $path
231
-	 */
232
-	private function removeRecoveryKeys($path) {
233
-		$dirContent = $this->view->getDirectoryContent($path);
234
-		foreach ($dirContent as $item) {
235
-			$filePath = $item->getPath();
236
-			if ($item['type'] === 'dir') {
237
-				$this->removeRecoveryKeys($filePath . '/');
238
-			} else {
239
-				$this->keyManager->deleteShareKey($filePath, $this->keyManager->getRecoveryKeyId());
240
-			}
241
-		}
242
-	}
243
-
244
-	/**
245
-	 * recover users files with the recovery key
246
-	 *
247
-	 * @param string $recoveryPassword
248
-	 * @param string $user
249
-	 */
250
-	public function recoverUsersFiles($recoveryPassword, $user) {
251
-		$encryptedKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
252
-
253
-		$privateKey = $this->crypt->decryptPrivateKey($encryptedKey, $recoveryPassword);
254
-		if ($privateKey !== false) {
255
-			$this->recoverAllFiles('/' . $user . '/files/', $privateKey, $user);
256
-		}
257
-	}
258
-
259
-	/**
260
-	 * recover users files
261
-	 *
262
-	 * @param string $path
263
-	 * @param string $privateKey
264
-	 * @param string $uid
265
-	 */
266
-	private function recoverAllFiles($path, $privateKey, $uid) {
267
-		$dirContent = $this->view->getDirectoryContent($path);
268
-
269
-		foreach ($dirContent as $item) {
270
-			// Get relative path from encryption/keyfiles
271
-			$filePath = $item->getPath();
272
-			if ($this->view->is_dir($filePath)) {
273
-				$this->recoverAllFiles($filePath . '/', $privateKey, $uid);
274
-			} else {
275
-				$this->recoverFile($filePath, $privateKey, $uid);
276
-			}
277
-		}
278
-	}
279
-
280
-	/**
281
-	 * recover file
282
-	 *
283
-	 * @param string $path
284
-	 * @param string $privateKey
285
-	 * @param string $uid
286
-	 */
287
-	private function recoverFile($path, $privateKey, $uid) {
288
-		$encryptedFileKey = $this->keyManager->getEncryptedFileKey($path);
289
-		$shareKey = $this->keyManager->getShareKey($path, $this->keyManager->getRecoveryKeyId());
290
-
291
-		if ($encryptedFileKey && $shareKey && $privateKey) {
292
-			$fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
293
-				$shareKey,
294
-				$privateKey);
295
-		}
296
-
297
-		if (!empty($fileKey)) {
298
-			$accessList = $this->file->getAccessList($path);
299
-			$publicKeys = [];
300
-			foreach ($accessList['users'] as $user) {
301
-				$publicKeys[$user] = $this->keyManager->getPublicKey($user);
302
-			}
303
-
304
-			$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
305
-
306
-			$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
307
-			$this->keyManager->setAllFileKeys($path, $encryptedKeyfiles);
308
-		}
309
-	}
40
+    /**
41
+     * @var null|IUser
42
+     */
43
+    protected $user;
44
+    /**
45
+     * @var Crypt
46
+     */
47
+    protected $crypt;
48
+    /**
49
+     * @var KeyManager
50
+     */
51
+    private $keyManager;
52
+    /**
53
+     * @var IConfig
54
+     */
55
+    private $config;
56
+    /**
57
+     * @var View
58
+     */
59
+    private $view;
60
+    /**
61
+     * @var IFile
62
+     */
63
+    private $file;
64
+
65
+    /**
66
+     * @param IUserSession $userSession
67
+     * @param Crypt $crypt
68
+     * @param KeyManager $keyManager
69
+     * @param IConfig $config
70
+     * @param IFile $file
71
+     * @param View $view
72
+     */
73
+    public function __construct(IUserSession $userSession,
74
+                                Crypt $crypt,
75
+                                KeyManager $keyManager,
76
+                                IConfig $config,
77
+                                IFile $file,
78
+                                View $view) {
79
+        $this->user = ($userSession->isLoggedIn()) ? $userSession->getUser() : null;
80
+        $this->crypt = $crypt;
81
+        $this->keyManager = $keyManager;
82
+        $this->config = $config;
83
+        $this->view = $view;
84
+        $this->file = $file;
85
+    }
86
+
87
+    /**
88
+     * @param string $password
89
+     * @return bool
90
+     */
91
+    public function enableAdminRecovery($password) {
92
+        $appConfig = $this->config;
93
+        $keyManager = $this->keyManager;
94
+
95
+        if (!$keyManager->recoveryKeyExists()) {
96
+            $keyPair = $this->crypt->createKeyPair();
97
+            if (!is_array($keyPair)) {
98
+                return false;
99
+            }
100
+
101
+            $this->keyManager->setRecoveryKey($password, $keyPair);
102
+        }
103
+
104
+        if ($keyManager->checkRecoveryPassword($password)) {
105
+            $appConfig->setAppValue('encryption', 'recoveryAdminEnabled', 1);
106
+            return true;
107
+        }
108
+
109
+        return false;
110
+    }
111
+
112
+    /**
113
+     * change recovery key id
114
+     *
115
+     * @param string $newPassword
116
+     * @param string $oldPassword
117
+     * @return bool
118
+     */
119
+    public function changeRecoveryKeyPassword($newPassword, $oldPassword) {
120
+        $recoveryKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
121
+        $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $oldPassword);
122
+        if ($decryptedRecoveryKey === false) {
123
+            return false;
124
+        }
125
+        $encryptedRecoveryKey = $this->crypt->encryptPrivateKey($decryptedRecoveryKey, $newPassword);
126
+        $header = $this->crypt->generateHeader();
127
+        if ($encryptedRecoveryKey) {
128
+            $this->keyManager->setSystemPrivateKey($this->keyManager->getRecoveryKeyId(), $header . $encryptedRecoveryKey);
129
+            return true;
130
+        }
131
+        return false;
132
+    }
133
+
134
+    /**
135
+     * @param string $recoveryPassword
136
+     * @return bool
137
+     */
138
+    public function disableAdminRecovery($recoveryPassword) {
139
+        $keyManager = $this->keyManager;
140
+
141
+        if ($keyManager->checkRecoveryPassword($recoveryPassword)) {
142
+            // Set recoveryAdmin as disabled
143
+            $this->config->setAppValue('encryption', 'recoveryAdminEnabled', 0);
144
+            return true;
145
+        }
146
+        return false;
147
+    }
148
+
149
+    /**
150
+     * check if recovery is enabled for user
151
+     *
152
+     * @param string $user if no user is given we check the current logged-in user
153
+     *
154
+     * @return bool
155
+     */
156
+    public function isRecoveryEnabledForUser($user = '') {
157
+        $uid = $user === '' ? $this->user->getUID() : $user;
158
+        $recoveryMode = $this->config->getUserValue($uid,
159
+            'encryption',
160
+            'recoveryEnabled',
161
+            0);
162
+
163
+        return ($recoveryMode === '1');
164
+    }
165
+
166
+    /**
167
+     * check if recovery is key is enabled by the administrator
168
+     *
169
+     * @return bool
170
+     */
171
+    public function isRecoveryKeyEnabled() {
172
+        $enabled = $this->config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
173
+
174
+        return ($enabled === '1');
175
+    }
176
+
177
+    /**
178
+     * @param string $value
179
+     * @return bool
180
+     */
181
+    public function setRecoveryForUser($value) {
182
+        try {
183
+            $this->config->setUserValue($this->user->getUID(),
184
+                'encryption',
185
+                'recoveryEnabled',
186
+                $value);
187
+
188
+            if ($value === '1') {
189
+                $this->addRecoveryKeys('/' . $this->user->getUID() . '/files/');
190
+            } else {
191
+                $this->removeRecoveryKeys('/' . $this->user->getUID() . '/files/');
192
+            }
193
+
194
+            return true;
195
+        } catch (PreConditionNotMetException $e) {
196
+            return false;
197
+        }
198
+    }
199
+
200
+    /**
201
+     * add recovery key to all encrypted files
202
+     * @param string $path
203
+     */
204
+    private function addRecoveryKeys($path) {
205
+        $dirContent = $this->view->getDirectoryContent($path);
206
+        foreach ($dirContent as $item) {
207
+            $filePath = $item->getPath();
208
+            if ($item['type'] === 'dir') {
209
+                $this->addRecoveryKeys($filePath . '/');
210
+            } else {
211
+                $fileKey = $this->keyManager->getFileKey($filePath, $this->user->getUID());
212
+                if (!empty($fileKey)) {
213
+                    $accessList = $this->file->getAccessList($filePath);
214
+                    $publicKeys = [];
215
+                    foreach ($accessList['users'] as $uid) {
216
+                        $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
217
+                    }
218
+
219
+                    $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->user->getUID());
220
+
221
+                    $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
222
+                    $this->keyManager->setAllFileKeys($filePath, $encryptedKeyfiles);
223
+                }
224
+            }
225
+        }
226
+    }
227
+
228
+    /**
229
+     * remove recovery key to all encrypted files
230
+     * @param string $path
231
+     */
232
+    private function removeRecoveryKeys($path) {
233
+        $dirContent = $this->view->getDirectoryContent($path);
234
+        foreach ($dirContent as $item) {
235
+            $filePath = $item->getPath();
236
+            if ($item['type'] === 'dir') {
237
+                $this->removeRecoveryKeys($filePath . '/');
238
+            } else {
239
+                $this->keyManager->deleteShareKey($filePath, $this->keyManager->getRecoveryKeyId());
240
+            }
241
+        }
242
+    }
243
+
244
+    /**
245
+     * recover users files with the recovery key
246
+     *
247
+     * @param string $recoveryPassword
248
+     * @param string $user
249
+     */
250
+    public function recoverUsersFiles($recoveryPassword, $user) {
251
+        $encryptedKey = $this->keyManager->getSystemPrivateKey($this->keyManager->getRecoveryKeyId());
252
+
253
+        $privateKey = $this->crypt->decryptPrivateKey($encryptedKey, $recoveryPassword);
254
+        if ($privateKey !== false) {
255
+            $this->recoverAllFiles('/' . $user . '/files/', $privateKey, $user);
256
+        }
257
+    }
258
+
259
+    /**
260
+     * recover users files
261
+     *
262
+     * @param string $path
263
+     * @param string $privateKey
264
+     * @param string $uid
265
+     */
266
+    private function recoverAllFiles($path, $privateKey, $uid) {
267
+        $dirContent = $this->view->getDirectoryContent($path);
268
+
269
+        foreach ($dirContent as $item) {
270
+            // Get relative path from encryption/keyfiles
271
+            $filePath = $item->getPath();
272
+            if ($this->view->is_dir($filePath)) {
273
+                $this->recoverAllFiles($filePath . '/', $privateKey, $uid);
274
+            } else {
275
+                $this->recoverFile($filePath, $privateKey, $uid);
276
+            }
277
+        }
278
+    }
279
+
280
+    /**
281
+     * recover file
282
+     *
283
+     * @param string $path
284
+     * @param string $privateKey
285
+     * @param string $uid
286
+     */
287
+    private function recoverFile($path, $privateKey, $uid) {
288
+        $encryptedFileKey = $this->keyManager->getEncryptedFileKey($path);
289
+        $shareKey = $this->keyManager->getShareKey($path, $this->keyManager->getRecoveryKeyId());
290
+
291
+        if ($encryptedFileKey && $shareKey && $privateKey) {
292
+            $fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
293
+                $shareKey,
294
+                $privateKey);
295
+        }
296
+
297
+        if (!empty($fileKey)) {
298
+            $accessList = $this->file->getAccessList($path);
299
+            $publicKeys = [];
300
+            foreach ($accessList['users'] as $user) {
301
+                $publicKeys[$user] = $this->keyManager->getPublicKey($user);
302
+            }
303
+
304
+            $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
305
+
306
+            $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
307
+            $this->keyManager->setAllFileKeys($path, $encryptedKeyfiles);
308
+        }
309
+    }
310 310
 }
Please login to merge, or discard this patch.
apps/settings/lib/Controller/AdminSettingsController.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -87,9 +87,9 @@
 block discarded – undo
87 87
 	private function getLegacyForms() {
88 88
 		$forms = \OC_App::getForms('admin');
89 89
 
90
-		$forms = array_map(function ($form) {
90
+		$forms = array_map(function($form) {
91 91
 			if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
92
-				$sectionName = str_replace('<h2' . $regs['class'] . '>', '', $regs[0]);
92
+				$sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
93 93
 				$sectionName = str_replace('</h2>', '', $sectionName);
94 94
 				$anchor = strtolower($sectionName);
95 95
 				$anchor = str_replace(' ', '-', $anchor);
Please login to merge, or discard this patch.
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -38,83 +38,83 @@
 block discarded – undo
38 38
 use OCP\Template;
39 39
 
40 40
 class AdminSettingsController extends Controller {
41
-	use CommonSettingsTrait;
41
+    use CommonSettingsTrait;
42 42
 
43
-	public function __construct(
44
-		$appName,
45
-		IRequest $request,
46
-		INavigationManager $navigationManager,
47
-		ISettingsManager $settingsManager,
48
-		IUserSession $userSession,
49
-		IGroupManager $groupManager,
50
-		ISubAdmin $subAdmin
51
-	) {
52
-		parent::__construct($appName, $request);
53
-		$this->navigationManager = $navigationManager;
54
-		$this->settingsManager = $settingsManager;
55
-		$this->userSession = $userSession;
56
-		$this->groupManager = $groupManager;
57
-		$this->subAdmin = $subAdmin;
58
-	}
43
+    public function __construct(
44
+        $appName,
45
+        IRequest $request,
46
+        INavigationManager $navigationManager,
47
+        ISettingsManager $settingsManager,
48
+        IUserSession $userSession,
49
+        IGroupManager $groupManager,
50
+        ISubAdmin $subAdmin
51
+    ) {
52
+        parent::__construct($appName, $request);
53
+        $this->navigationManager = $navigationManager;
54
+        $this->settingsManager = $settingsManager;
55
+        $this->userSession = $userSession;
56
+        $this->groupManager = $groupManager;
57
+        $this->subAdmin = $subAdmin;
58
+    }
59 59
 
60
-	/**
61
-	 * @NoCSRFRequired
62
-	 * @NoAdminRequired
63
-	 * @NoSubAdminRequired
64
-	 * We are checking the permissions in the getSettings method. If there is no allowed
65
-	 * settings for the given section. The user will be gretted by an error message.
66
-	 */
67
-	public function index(string $section): TemplateResponse {
68
-		return $this->getIndexResponse('admin', $section);
69
-	}
60
+    /**
61
+     * @NoCSRFRequired
62
+     * @NoAdminRequired
63
+     * @NoSubAdminRequired
64
+     * We are checking the permissions in the getSettings method. If there is no allowed
65
+     * settings for the given section. The user will be gretted by an error message.
66
+     */
67
+    public function index(string $section): TemplateResponse {
68
+        return $this->getIndexResponse('admin', $section);
69
+    }
70 70
 
71
-	/**
72
-	 * @param string $section
73
-	 * @return array
74
-	 */
75
-	protected function getSettings($section) {
76
-		/** @var IUser $user */
77
-		$user = $this->userSession->getUser();
78
-		$isSubAdmin = !$this->groupManager->isAdmin($user->getUID()) && $this->subAdmin->isSubAdmin($user);
79
-		$settings = $this->settingsManager->getAllowedAdminSettings($section, $user);
80
-		if (empty($settings)) {
81
-			throw new NotAdminException("Logged in user doesn't have permission to access these settings.");
82
-		}
83
-		$formatted = $this->formatSettings($settings);
84
-		// Do not show legacy forms for sub admins
85
-		if ($section === 'additional' && !$isSubAdmin) {
86
-			$formatted['content'] .= $this->getLegacyForms();
87
-		}
88
-		return $formatted;
89
-	}
71
+    /**
72
+     * @param string $section
73
+     * @return array
74
+     */
75
+    protected function getSettings($section) {
76
+        /** @var IUser $user */
77
+        $user = $this->userSession->getUser();
78
+        $isSubAdmin = !$this->groupManager->isAdmin($user->getUID()) && $this->subAdmin->isSubAdmin($user);
79
+        $settings = $this->settingsManager->getAllowedAdminSettings($section, $user);
80
+        if (empty($settings)) {
81
+            throw new NotAdminException("Logged in user doesn't have permission to access these settings.");
82
+        }
83
+        $formatted = $this->formatSettings($settings);
84
+        // Do not show legacy forms for sub admins
85
+        if ($section === 'additional' && !$isSubAdmin) {
86
+            $formatted['content'] .= $this->getLegacyForms();
87
+        }
88
+        return $formatted;
89
+    }
90 90
 
91
-	/**
92
-	 * @return bool|string
93
-	 */
94
-	private function getLegacyForms() {
95
-		$forms = \OC_App::getForms('admin');
91
+    /**
92
+     * @return bool|string
93
+     */
94
+    private function getLegacyForms() {
95
+        $forms = \OC_App::getForms('admin');
96 96
 
97
-		$forms = array_map(function ($form) {
98
-			if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
99
-				$sectionName = str_replace('<h2' . $regs['class'] . '>', '', $regs[0]);
100
-				$sectionName = str_replace('</h2>', '', $sectionName);
101
-				$anchor = strtolower($sectionName);
102
-				$anchor = str_replace(' ', '-', $anchor);
97
+        $forms = array_map(function ($form) {
98
+            if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
99
+                $sectionName = str_replace('<h2' . $regs['class'] . '>', '', $regs[0]);
100
+                $sectionName = str_replace('</h2>', '', $sectionName);
101
+                $anchor = strtolower($sectionName);
102
+                $anchor = str_replace(' ', '-', $anchor);
103 103
 
104
-				return [
105
-					'anchor' => $anchor,
106
-					'section-name' => $sectionName,
107
-					'form' => $form
108
-				];
109
-			}
110
-			return [
111
-				'form' => $form
112
-			];
113
-		}, $forms);
104
+                return [
105
+                    'anchor' => $anchor,
106
+                    'section-name' => $sectionName,
107
+                    'form' => $form
108
+                ];
109
+            }
110
+            return [
111
+                'form' => $form
112
+            ];
113
+        }, $forms);
114 114
 
115
-		$out = new Template('settings', 'settings/additional');
116
-		$out->assign('forms', $forms);
115
+        $out = new Template('settings', 'settings/additional');
116
+        $out->assign('forms', $forms);
117 117
 
118
-		return $out->fetchPage();
119
-	}
118
+        return $out->fetchPage();
119
+    }
120 120
 }
Please login to merge, or discard this patch.
apps/settings/lib/Controller/PersonalSettingsController.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -79,9 +79,9 @@
 block discarded – undo
79 79
 	private function getLegacyForms() {
80 80
 		$forms = \OC_App::getForms('personal');
81 81
 
82
-		$forms = array_map(function ($form) {
82
+		$forms = array_map(function($form) {
83 83
 			if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
84
-				$sectionName = str_replace('<h2' . $regs['class'] . '>', '', $regs[0]);
84
+				$sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
85 85
 				$sectionName = str_replace('</h2>', '', $sectionName);
86 86
 				$anchor = strtolower($sectionName);
87 87
 				$anchor = str_replace(' ', '-', $anchor);
Please login to merge, or discard this patch.
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -36,74 +36,74 @@
 block discarded – undo
36 36
 use OCP\Template;
37 37
 
38 38
 class PersonalSettingsController extends Controller {
39
-	use CommonSettingsTrait;
39
+    use CommonSettingsTrait;
40 40
 
41
-	public function __construct(
42
-		$appName,
43
-		IRequest $request,
44
-		INavigationManager $navigationManager,
45
-		ISettingsManager $settingsManager,
46
-		IUserSession $userSession,
47
-		IGroupManager $groupManager,
48
-		ISubAdmin $subAdmin
49
-	) {
50
-		parent::__construct($appName, $request);
51
-		$this->navigationManager = $navigationManager;
52
-		$this->settingsManager = $settingsManager;
53
-		$this->userSession = $userSession;
54
-		$this->subAdmin = $subAdmin;
55
-		$this->groupManager = $groupManager;
56
-	}
41
+    public function __construct(
42
+        $appName,
43
+        IRequest $request,
44
+        INavigationManager $navigationManager,
45
+        ISettingsManager $settingsManager,
46
+        IUserSession $userSession,
47
+        IGroupManager $groupManager,
48
+        ISubAdmin $subAdmin
49
+    ) {
50
+        parent::__construct($appName, $request);
51
+        $this->navigationManager = $navigationManager;
52
+        $this->settingsManager = $settingsManager;
53
+        $this->userSession = $userSession;
54
+        $this->subAdmin = $subAdmin;
55
+        $this->groupManager = $groupManager;
56
+    }
57 57
 
58
-	/**
59
-	 * @NoCSRFRequired
60
-	 * @NoAdminRequired
61
-	 * @NoSubAdminRequired
62
-	 */
63
-	public function index(string $section): TemplateResponse {
64
-		return $this->getIndexResponse('personal', $section);
65
-	}
58
+    /**
59
+     * @NoCSRFRequired
60
+     * @NoAdminRequired
61
+     * @NoSubAdminRequired
62
+     */
63
+    public function index(string $section): TemplateResponse {
64
+        return $this->getIndexResponse('personal', $section);
65
+    }
66 66
 
67
-	/**
68
-	 * @param string $section
69
-	 * @return array
70
-	 */
71
-	protected function getSettings($section) {
72
-		$settings = $this->settingsManager->getPersonalSettings($section);
73
-		$formatted = $this->formatSettings($settings);
74
-		if ($section === 'additional') {
75
-			$formatted['content'] .= $this->getLegacyForms();
76
-		}
77
-		return $formatted;
78
-	}
67
+    /**
68
+     * @param string $section
69
+     * @return array
70
+     */
71
+    protected function getSettings($section) {
72
+        $settings = $this->settingsManager->getPersonalSettings($section);
73
+        $formatted = $this->formatSettings($settings);
74
+        if ($section === 'additional') {
75
+            $formatted['content'] .= $this->getLegacyForms();
76
+        }
77
+        return $formatted;
78
+    }
79 79
 
80
-	/**
81
-	 * @return bool|string
82
-	 */
83
-	private function getLegacyForms() {
84
-		$forms = \OC_App::getForms('personal');
80
+    /**
81
+     * @return bool|string
82
+     */
83
+    private function getLegacyForms() {
84
+        $forms = \OC_App::getForms('personal');
85 85
 
86
-		$forms = array_map(function ($form) {
87
-			if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
88
-				$sectionName = str_replace('<h2' . $regs['class'] . '>', '', $regs[0]);
89
-				$sectionName = str_replace('</h2>', '', $sectionName);
90
-				$anchor = strtolower($sectionName);
91
-				$anchor = str_replace(' ', '-', $anchor);
86
+        $forms = array_map(function ($form) {
87
+            if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
88
+                $sectionName = str_replace('<h2' . $regs['class'] . '>', '', $regs[0]);
89
+                $sectionName = str_replace('</h2>', '', $sectionName);
90
+                $anchor = strtolower($sectionName);
91
+                $anchor = str_replace(' ', '-', $anchor);
92 92
 
93
-				return [
94
-					'anchor' => $anchor,
95
-					'section-name' => $sectionName,
96
-					'form' => $form
97
-				];
98
-			}
99
-			return [
100
-				'form' => $form
101
-			];
102
-		}, $forms);
93
+                return [
94
+                    'anchor' => $anchor,
95
+                    'section-name' => $sectionName,
96
+                    'form' => $form
97
+                ];
98
+            }
99
+            return [
100
+                'form' => $form
101
+            ];
102
+        }, $forms);
103 103
 
104
-		$out = new Template('settings', 'settings/additional');
105
-		$out->assign('forms', $forms);
104
+        $out = new Template('settings', 'settings/additional');
105
+        $out->assign('forms', $forms);
106 106
 
107
-		return $out->fetchPage();
108
-	}
107
+        return $out->fetchPage();
108
+    }
109 109
 }
Please login to merge, or discard this patch.