Completed
Pull Request — master (#6919)
by Morris
12:45
created
apps/encryption/lib/Migration.php 2 patches
Indentation   +358 added lines, -358 removed lines patch added patch discarded remove patch
@@ -33,362 +33,362 @@
 block discarded – undo
33 33
 
34 34
 class Migration {
35 35
 
36
-	private $moduleId;
37
-	/** @var \OC\Files\View */
38
-	private $view;
39
-	/** @var \OCP\IDBConnection */
40
-	private $connection;
41
-	/** @var IConfig */
42
-	private $config;
43
-	/** @var  ILogger */
44
-	private $logger;
45
-	/** @var string*/
46
-	protected $installedVersion;
47
-	/** @var IAppManager */
48
-	protected $appManager;
49
-
50
-	/**
51
-	 * @param IConfig $config
52
-	 * @param View $view
53
-	 * @param IDBConnection $connection
54
-	 * @param ILogger $logger
55
-	 */
56
-	public function __construct(IConfig $config, View $view, IDBConnection $connection, ILogger $logger, IAppManager $appManager) {
57
-		$this->view = $view;
58
-		$this->view->disableCacheUpdate();
59
-		$this->connection = $connection;
60
-		$this->moduleId = \OCA\Encryption\Crypto\Encryption::ID;
61
-		$this->config = $config;
62
-		$this->logger = $logger;
63
-		$this->installedVersion = $this->config->getAppValue('files_encryption', 'installed_version', '-1');
64
-		$this->appManager = $appManager;
65
-	}
66
-
67
-	public function finalCleanUp() {
68
-		$this->view->deleteAll('files_encryption/public_keys');
69
-		$this->updateFileCache();
70
-		$this->config->deleteAppValue('files_encryption', 'installed_version');
71
-	}
72
-
73
-	/**
74
-	 * update file cache, copy unencrypted_size to the 'size' column
75
-	 */
76
-	private function updateFileCache() {
77
-		// make sure that we don't update the file cache multiple times
78
-		// only update during the first run
79
-		if ($this->installedVersion !== '-1') {
80
-			$query = $this->connection->getQueryBuilder();
81
-			$query->update('filecache')
82
-				->set('size', 'unencrypted_size')
83
-				->where($query->expr()->eq('encrypted', $query->createParameter('encrypted')))
84
-				->setParameter('encrypted', 1);
85
-			$query->execute();
86
-		}
87
-	}
88
-
89
-	/**
90
-	 * iterate through users and reorganize the folder structure
91
-	 */
92
-	public function reorganizeFolderStructure() {
93
-		$this->reorganizeSystemFolderStructure();
94
-
95
-		$limit = 500;
96
-		$offset = 0;
97
-		do {
98
-			$users = \OCP\User::getUsers('', $limit, $offset);
99
-			foreach ($users as $user) {
100
-				$this->reorganizeFolderStructureForUser($user);
101
-			}
102
-			$offset += $limit;
103
-		} while (count($users) >= $limit);
104
-	}
105
-
106
-	/**
107
-	 * reorganize system wide folder structure
108
-	 */
109
-	public function reorganizeSystemFolderStructure() {
110
-
111
-		$this->createPathForKeys('/files_encryption');
112
-
113
-		// backup system wide folders
114
-		$this->backupSystemWideKeys();
115
-
116
-		// rename system wide mount point
117
-		$this->renameFileKeys('', '/files_encryption/keys');
118
-
119
-		// rename system private keys
120
-		$this->renameSystemPrivateKeys();
121
-
122
-		$storage = $this->view->getMount('')->getStorage();
123
-		$storage->getScanner()->scan('files_encryption');
124
-	}
125
-
126
-
127
-	/**
128
-	 * reorganize folder structure for user
129
-	 *
130
-	 * @param string $user
131
-	 */
132
-	public function reorganizeFolderStructureForUser($user) {
133
-		// backup all keys
134
-		\OC_Util::tearDownFS();
135
-		\OC_Util::setupFS($user);
136
-		if ($this->backupUserKeys($user)) {
137
-			// rename users private key
138
-			$this->renameUsersPrivateKey($user);
139
-			$this->renameUsersPublicKey($user);
140
-			// rename file keys
141
-			$path = '/files_encryption/keys';
142
-			$this->renameFileKeys($user, $path);
143
-			$trashPath = '/files_trashbin/keys';
144
-			if ($this->appManager->isEnabledForUser('files_trashbin') && $this->view->is_dir($user . '/' . $trashPath)) {
145
-				$this->renameFileKeys($user, $trashPath, true);
146
-				$this->view->deleteAll($trashPath);
147
-			}
148
-			// delete old folders
149
-			$this->deleteOldKeys($user);
150
-			$this->view->getMount('/' . $user)->getStorage()->getScanner()->scan('files_encryption');
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * update database
156
-	 */
157
-	public function updateDB() {
158
-
159
-		// make sure that we don't update the file cache multiple times
160
-		// only update during the first run
161
-		if ($this->installedVersion === '-1') {
162
-			return;
163
-		}
164
-
165
-		// delete left-over from old encryption which is no longer needed
166
-		$this->config->deleteAppValue('files_encryption', 'ocsid');
167
-		$this->config->deleteAppValue('files_encryption', 'types');
168
-		$this->config->deleteAppValue('files_encryption', 'enabled');
169
-
170
-		$oldAppValues = $this->connection->getQueryBuilder();
171
-		$oldAppValues->select('*')
172
-			->from('appconfig')
173
-			->where($oldAppValues->expr()->eq('appid', $oldAppValues->createParameter('appid')))
174
-			->setParameter('appid', 'files_encryption');
175
-		$appSettings = $oldAppValues->execute();
176
-
177
-		while ($row = $appSettings->fetch()) {
178
-			// 'installed_version' gets deleted at the end of the migration process
179
-			if ($row['configkey'] !== 'installed_version' ) {
180
-				$this->config->setAppValue('encryption', $row['configkey'], $row['configvalue']);
181
-				$this->config->deleteAppValue('files_encryption', $row['configkey']);
182
-			}
183
-		}
184
-
185
-		$oldPreferences = $this->connection->getQueryBuilder();
186
-		$oldPreferences->select('*')
187
-			->from('preferences')
188
-			->where($oldPreferences->expr()->eq('appid', $oldPreferences->createParameter('appid')))
189
-			->setParameter('appid', 'files_encryption');
190
-		$preferenceSettings = $oldPreferences->execute();
191
-
192
-		while ($row = $preferenceSettings->fetch()) {
193
-			$this->config->setUserValue($row['userid'], 'encryption', $row['configkey'], $row['configvalue']);
194
-			$this->config->deleteUserValue($row['userid'], 'files_encryption', $row['configkey']);
195
-		}
196
-	}
197
-
198
-	/**
199
-	 * create backup of system-wide keys
200
-	 */
201
-	private function backupSystemWideKeys() {
202
-		$backupDir = 'encryption_migration_backup_' . date("Y-m-d_H-i-s");
203
-		$this->view->mkdir($backupDir);
204
-		$this->view->copy('files_encryption', $backupDir . '/files_encryption');
205
-	}
206
-
207
-	/**
208
-	 * create backup of user specific keys
209
-	 *
210
-	 * @param string $user
211
-	 * @return bool
212
-	 */
213
-	private function backupUserKeys($user) {
214
-		$encryptionDir = $user . '/files_encryption';
215
-		if ($this->view->is_dir($encryptionDir)) {
216
-			$backupDir = $user . '/encryption_migration_backup_' . date("Y-m-d_H-i-s");
217
-			$this->view->mkdir($backupDir);
218
-			$this->view->copy($encryptionDir, $backupDir);
219
-			return true;
220
-		}
221
-		return false;
222
-	}
223
-
224
-	/**
225
-	 * rename system-wide private keys
226
-	 */
227
-	private function renameSystemPrivateKeys() {
228
-		$dh = $this->view->opendir('files_encryption');
229
-		$this->createPathForKeys('/files_encryption/' . $this->moduleId );
230
-		if (is_resource($dh)) {
231
-			while (($privateKey = readdir($dh)) !== false) {
232
-				if (!\OC\Files\Filesystem::isIgnoredDir($privateKey) ) {
233
-					if (!$this->view->is_dir('/files_encryption/' . $privateKey)) {
234
-						$this->view->rename('files_encryption/' . $privateKey, 'files_encryption/' . $this->moduleId . '/' . $privateKey);
235
-						$this->renameSystemPublicKey($privateKey);
236
-					}
237
-				}
238
-			}
239
-			closedir($dh);
240
-		}
241
-	}
242
-
243
-	/**
244
-	 * rename system wide public key
245
-	 *
246
-	 * @param string $privateKey private key for which we want to rename the corresponding public key
247
-	 */
248
-	private function renameSystemPublicKey($privateKey) {
249
-		$publicKey = substr($privateKey,0 , strrpos($privateKey, '.privateKey')) . '.publicKey';
250
-		$this->view->rename('files_encryption/public_keys/' . $publicKey, 'files_encryption/' . $this->moduleId . '/' . $publicKey);
251
-	}
252
-
253
-	/**
254
-	 * rename user-specific private keys
255
-	 *
256
-	 * @param string $user
257
-	 */
258
-	private function renameUsersPrivateKey($user) {
259
-		$oldPrivateKey = $user . '/files_encryption/' . $user . '.privateKey';
260
-		$newPrivateKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.privateKey';
261
-		if ($this->view->file_exists($oldPrivateKey)) {
262
-			$this->createPathForKeys(dirname($newPrivateKey));
263
-			$this->view->rename($oldPrivateKey, $newPrivateKey);
264
-		}
265
-	}
266
-
267
-	/**
268
-	 * rename user-specific public keys
269
-	 *
270
-	 * @param string $user
271
-	 */
272
-	private function renameUsersPublicKey($user) {
273
-		$oldPublicKey = '/files_encryption/public_keys/' . $user . '.publicKey';
274
-		$newPublicKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.publicKey';
275
-		if ($this->view->file_exists($oldPublicKey)) {
276
-			$this->createPathForKeys(dirname($newPublicKey));
277
-			$this->view->rename($oldPublicKey, $newPublicKey);
278
-		}
279
-	}
280
-
281
-	/**
282
-	 * rename file keys
283
-	 *
284
-	 * @param string $user
285
-	 * @param string $path
286
-	 * @param bool $trash
287
-	 */
288
-	private function renameFileKeys($user, $path, $trash = false) {
289
-
290
-		if ($this->view->is_dir($user . '/' . $path) === false) {
291
-			$this->logger->info('Skip dir /' . $user . '/' . $path . ': does not exist');
292
-			return;
293
-		}
294
-
295
-		$dh = $this->view->opendir($user . '/' . $path);
296
-
297
-		if (is_resource($dh)) {
298
-			while (($file = readdir($dh)) !== false) {
299
-				if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
300
-					if ($this->view->is_dir($user . '/' . $path . '/' . $file)) {
301
-						$this->renameFileKeys($user, $path . '/' . $file, $trash);
302
-					} else {
303
-						$target = $this->getTargetDir($user, $path, $file, $trash);
304
-						if ($target !== false) {
305
-							$this->createPathForKeys(dirname($target));
306
-							$this->view->rename($user . '/' . $path . '/' . $file, $target);
307
-						} else {
308
-							$this->logger->warning(
309
-								'did not move key "' . $file
310
-								. '" could not find the corresponding file in /data/' . $user . '/files.'
311
-							. 'Most likely the key was already moved in a previous migration run and is already on the right place.');
312
-						}
313
-					}
314
-				}
315
-			}
316
-			closedir($dh);
317
-		}
318
-	}
319
-
320
-	/**
321
-	 * get system mount points
322
-	 * wrap static method so that it can be mocked for testing
323
-	 *
324
-	 * @internal
325
-	 * @return array
326
-	 */
327
-	protected function getSystemMountPoints() {
328
-		return \OC_Mount_Config::getSystemMountPoints();
329
-	}
330
-
331
-	/**
332
-	 * generate target directory
333
-	 *
334
-	 * @param string $user
335
-	 * @param string $keyPath
336
-	 * @param string $filename
337
-	 * @param bool $trash
338
-	 * @return string
339
-	 */
340
-	private function getTargetDir($user, $keyPath, $filename, $trash) {
341
-		if ($trash) {
342
-			$filePath = substr($keyPath, strlen('/files_trashbin/keys/'));
343
-			$targetDir = $user . '/files_encryption/keys/files_trashbin/' . $filePath . '/' . $this->moduleId . '/' . $filename;
344
-		} else {
345
-			$filePath = substr($keyPath, strlen('/files_encryption/keys/'));
346
-			$targetDir = $user . '/files_encryption/keys/files/' . $filePath . '/' . $this->moduleId . '/' . $filename;
347
-		}
348
-
349
-		if ($user === '') {
350
-			// for system wide mounts we need to check if the mount point really exists
351
-			$normalized = \OC\Files\Filesystem::normalizePath($filePath);
352
-			$systemMountPoints = $this->getSystemMountPoints();
353
-			foreach ($systemMountPoints as $mountPoint) {
354
-				$normalizedMountPoint = \OC\Files\Filesystem::normalizePath($mountPoint['mountpoint']) . '/';
355
-				if (strpos($normalized, $normalizedMountPoint) === 0)
356
-					return $targetDir;
357
-			}
358
-		} else if ($trash === false && $this->view->file_exists('/' . $user. '/files/' . $filePath)) {
359
-			return $targetDir;
360
-		} else if ($trash === true && $this->view->file_exists('/' . $user. '/files_trashbin/' . $filePath)) {
361
-				return $targetDir;
362
-			}
363
-
364
-		return false;
365
-	}
366
-
367
-	/**
368
-	 * delete old keys
369
-	 *
370
-	 * @param string $user
371
-	 */
372
-	private function deleteOldKeys($user) {
373
-		$this->view->deleteAll($user . '/files_encryption/keyfiles');
374
-		$this->view->deleteAll($user . '/files_encryption/share-keys');
375
-	}
376
-
377
-	/**
378
-	 * create directories for the keys recursively
379
-	 *
380
-	 * @param string $path
381
-	 */
382
-	private function createPathForKeys($path) {
383
-		if (!$this->view->file_exists($path)) {
384
-			$sub_dirs = explode('/', $path);
385
-			$dir = '';
386
-			foreach ($sub_dirs as $sub_dir) {
387
-				$dir .= '/' . $sub_dir;
388
-				if (!$this->view->is_dir($dir)) {
389
-					$this->view->mkdir($dir);
390
-				}
391
-			}
392
-		}
393
-	}
36
+    private $moduleId;
37
+    /** @var \OC\Files\View */
38
+    private $view;
39
+    /** @var \OCP\IDBConnection */
40
+    private $connection;
41
+    /** @var IConfig */
42
+    private $config;
43
+    /** @var  ILogger */
44
+    private $logger;
45
+    /** @var string*/
46
+    protected $installedVersion;
47
+    /** @var IAppManager */
48
+    protected $appManager;
49
+
50
+    /**
51
+     * @param IConfig $config
52
+     * @param View $view
53
+     * @param IDBConnection $connection
54
+     * @param ILogger $logger
55
+     */
56
+    public function __construct(IConfig $config, View $view, IDBConnection $connection, ILogger $logger, IAppManager $appManager) {
57
+        $this->view = $view;
58
+        $this->view->disableCacheUpdate();
59
+        $this->connection = $connection;
60
+        $this->moduleId = \OCA\Encryption\Crypto\Encryption::ID;
61
+        $this->config = $config;
62
+        $this->logger = $logger;
63
+        $this->installedVersion = $this->config->getAppValue('files_encryption', 'installed_version', '-1');
64
+        $this->appManager = $appManager;
65
+    }
66
+
67
+    public function finalCleanUp() {
68
+        $this->view->deleteAll('files_encryption/public_keys');
69
+        $this->updateFileCache();
70
+        $this->config->deleteAppValue('files_encryption', 'installed_version');
71
+    }
72
+
73
+    /**
74
+     * update file cache, copy unencrypted_size to the 'size' column
75
+     */
76
+    private function updateFileCache() {
77
+        // make sure that we don't update the file cache multiple times
78
+        // only update during the first run
79
+        if ($this->installedVersion !== '-1') {
80
+            $query = $this->connection->getQueryBuilder();
81
+            $query->update('filecache')
82
+                ->set('size', 'unencrypted_size')
83
+                ->where($query->expr()->eq('encrypted', $query->createParameter('encrypted')))
84
+                ->setParameter('encrypted', 1);
85
+            $query->execute();
86
+        }
87
+    }
88
+
89
+    /**
90
+     * iterate through users and reorganize the folder structure
91
+     */
92
+    public function reorganizeFolderStructure() {
93
+        $this->reorganizeSystemFolderStructure();
94
+
95
+        $limit = 500;
96
+        $offset = 0;
97
+        do {
98
+            $users = \OCP\User::getUsers('', $limit, $offset);
99
+            foreach ($users as $user) {
100
+                $this->reorganizeFolderStructureForUser($user);
101
+            }
102
+            $offset += $limit;
103
+        } while (count($users) >= $limit);
104
+    }
105
+
106
+    /**
107
+     * reorganize system wide folder structure
108
+     */
109
+    public function reorganizeSystemFolderStructure() {
110
+
111
+        $this->createPathForKeys('/files_encryption');
112
+
113
+        // backup system wide folders
114
+        $this->backupSystemWideKeys();
115
+
116
+        // rename system wide mount point
117
+        $this->renameFileKeys('', '/files_encryption/keys');
118
+
119
+        // rename system private keys
120
+        $this->renameSystemPrivateKeys();
121
+
122
+        $storage = $this->view->getMount('')->getStorage();
123
+        $storage->getScanner()->scan('files_encryption');
124
+    }
125
+
126
+
127
+    /**
128
+     * reorganize folder structure for user
129
+     *
130
+     * @param string $user
131
+     */
132
+    public function reorganizeFolderStructureForUser($user) {
133
+        // backup all keys
134
+        \OC_Util::tearDownFS();
135
+        \OC_Util::setupFS($user);
136
+        if ($this->backupUserKeys($user)) {
137
+            // rename users private key
138
+            $this->renameUsersPrivateKey($user);
139
+            $this->renameUsersPublicKey($user);
140
+            // rename file keys
141
+            $path = '/files_encryption/keys';
142
+            $this->renameFileKeys($user, $path);
143
+            $trashPath = '/files_trashbin/keys';
144
+            if ($this->appManager->isEnabledForUser('files_trashbin') && $this->view->is_dir($user . '/' . $trashPath)) {
145
+                $this->renameFileKeys($user, $trashPath, true);
146
+                $this->view->deleteAll($trashPath);
147
+            }
148
+            // delete old folders
149
+            $this->deleteOldKeys($user);
150
+            $this->view->getMount('/' . $user)->getStorage()->getScanner()->scan('files_encryption');
151
+        }
152
+    }
153
+
154
+    /**
155
+     * update database
156
+     */
157
+    public function updateDB() {
158
+
159
+        // make sure that we don't update the file cache multiple times
160
+        // only update during the first run
161
+        if ($this->installedVersion === '-1') {
162
+            return;
163
+        }
164
+
165
+        // delete left-over from old encryption which is no longer needed
166
+        $this->config->deleteAppValue('files_encryption', 'ocsid');
167
+        $this->config->deleteAppValue('files_encryption', 'types');
168
+        $this->config->deleteAppValue('files_encryption', 'enabled');
169
+
170
+        $oldAppValues = $this->connection->getQueryBuilder();
171
+        $oldAppValues->select('*')
172
+            ->from('appconfig')
173
+            ->where($oldAppValues->expr()->eq('appid', $oldAppValues->createParameter('appid')))
174
+            ->setParameter('appid', 'files_encryption');
175
+        $appSettings = $oldAppValues->execute();
176
+
177
+        while ($row = $appSettings->fetch()) {
178
+            // 'installed_version' gets deleted at the end of the migration process
179
+            if ($row['configkey'] !== 'installed_version' ) {
180
+                $this->config->setAppValue('encryption', $row['configkey'], $row['configvalue']);
181
+                $this->config->deleteAppValue('files_encryption', $row['configkey']);
182
+            }
183
+        }
184
+
185
+        $oldPreferences = $this->connection->getQueryBuilder();
186
+        $oldPreferences->select('*')
187
+            ->from('preferences')
188
+            ->where($oldPreferences->expr()->eq('appid', $oldPreferences->createParameter('appid')))
189
+            ->setParameter('appid', 'files_encryption');
190
+        $preferenceSettings = $oldPreferences->execute();
191
+
192
+        while ($row = $preferenceSettings->fetch()) {
193
+            $this->config->setUserValue($row['userid'], 'encryption', $row['configkey'], $row['configvalue']);
194
+            $this->config->deleteUserValue($row['userid'], 'files_encryption', $row['configkey']);
195
+        }
196
+    }
197
+
198
+    /**
199
+     * create backup of system-wide keys
200
+     */
201
+    private function backupSystemWideKeys() {
202
+        $backupDir = 'encryption_migration_backup_' . date("Y-m-d_H-i-s");
203
+        $this->view->mkdir($backupDir);
204
+        $this->view->copy('files_encryption', $backupDir . '/files_encryption');
205
+    }
206
+
207
+    /**
208
+     * create backup of user specific keys
209
+     *
210
+     * @param string $user
211
+     * @return bool
212
+     */
213
+    private function backupUserKeys($user) {
214
+        $encryptionDir = $user . '/files_encryption';
215
+        if ($this->view->is_dir($encryptionDir)) {
216
+            $backupDir = $user . '/encryption_migration_backup_' . date("Y-m-d_H-i-s");
217
+            $this->view->mkdir($backupDir);
218
+            $this->view->copy($encryptionDir, $backupDir);
219
+            return true;
220
+        }
221
+        return false;
222
+    }
223
+
224
+    /**
225
+     * rename system-wide private keys
226
+     */
227
+    private function renameSystemPrivateKeys() {
228
+        $dh = $this->view->opendir('files_encryption');
229
+        $this->createPathForKeys('/files_encryption/' . $this->moduleId );
230
+        if (is_resource($dh)) {
231
+            while (($privateKey = readdir($dh)) !== false) {
232
+                if (!\OC\Files\Filesystem::isIgnoredDir($privateKey) ) {
233
+                    if (!$this->view->is_dir('/files_encryption/' . $privateKey)) {
234
+                        $this->view->rename('files_encryption/' . $privateKey, 'files_encryption/' . $this->moduleId . '/' . $privateKey);
235
+                        $this->renameSystemPublicKey($privateKey);
236
+                    }
237
+                }
238
+            }
239
+            closedir($dh);
240
+        }
241
+    }
242
+
243
+    /**
244
+     * rename system wide public key
245
+     *
246
+     * @param string $privateKey private key for which we want to rename the corresponding public key
247
+     */
248
+    private function renameSystemPublicKey($privateKey) {
249
+        $publicKey = substr($privateKey,0 , strrpos($privateKey, '.privateKey')) . '.publicKey';
250
+        $this->view->rename('files_encryption/public_keys/' . $publicKey, 'files_encryption/' . $this->moduleId . '/' . $publicKey);
251
+    }
252
+
253
+    /**
254
+     * rename user-specific private keys
255
+     *
256
+     * @param string $user
257
+     */
258
+    private function renameUsersPrivateKey($user) {
259
+        $oldPrivateKey = $user . '/files_encryption/' . $user . '.privateKey';
260
+        $newPrivateKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.privateKey';
261
+        if ($this->view->file_exists($oldPrivateKey)) {
262
+            $this->createPathForKeys(dirname($newPrivateKey));
263
+            $this->view->rename($oldPrivateKey, $newPrivateKey);
264
+        }
265
+    }
266
+
267
+    /**
268
+     * rename user-specific public keys
269
+     *
270
+     * @param string $user
271
+     */
272
+    private function renameUsersPublicKey($user) {
273
+        $oldPublicKey = '/files_encryption/public_keys/' . $user . '.publicKey';
274
+        $newPublicKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.publicKey';
275
+        if ($this->view->file_exists($oldPublicKey)) {
276
+            $this->createPathForKeys(dirname($newPublicKey));
277
+            $this->view->rename($oldPublicKey, $newPublicKey);
278
+        }
279
+    }
280
+
281
+    /**
282
+     * rename file keys
283
+     *
284
+     * @param string $user
285
+     * @param string $path
286
+     * @param bool $trash
287
+     */
288
+    private function renameFileKeys($user, $path, $trash = false) {
289
+
290
+        if ($this->view->is_dir($user . '/' . $path) === false) {
291
+            $this->logger->info('Skip dir /' . $user . '/' . $path . ': does not exist');
292
+            return;
293
+        }
294
+
295
+        $dh = $this->view->opendir($user . '/' . $path);
296
+
297
+        if (is_resource($dh)) {
298
+            while (($file = readdir($dh)) !== false) {
299
+                if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
300
+                    if ($this->view->is_dir($user . '/' . $path . '/' . $file)) {
301
+                        $this->renameFileKeys($user, $path . '/' . $file, $trash);
302
+                    } else {
303
+                        $target = $this->getTargetDir($user, $path, $file, $trash);
304
+                        if ($target !== false) {
305
+                            $this->createPathForKeys(dirname($target));
306
+                            $this->view->rename($user . '/' . $path . '/' . $file, $target);
307
+                        } else {
308
+                            $this->logger->warning(
309
+                                'did not move key "' . $file
310
+                                . '" could not find the corresponding file in /data/' . $user . '/files.'
311
+                            . 'Most likely the key was already moved in a previous migration run and is already on the right place.');
312
+                        }
313
+                    }
314
+                }
315
+            }
316
+            closedir($dh);
317
+        }
318
+    }
319
+
320
+    /**
321
+     * get system mount points
322
+     * wrap static method so that it can be mocked for testing
323
+     *
324
+     * @internal
325
+     * @return array
326
+     */
327
+    protected function getSystemMountPoints() {
328
+        return \OC_Mount_Config::getSystemMountPoints();
329
+    }
330
+
331
+    /**
332
+     * generate target directory
333
+     *
334
+     * @param string $user
335
+     * @param string $keyPath
336
+     * @param string $filename
337
+     * @param bool $trash
338
+     * @return string
339
+     */
340
+    private function getTargetDir($user, $keyPath, $filename, $trash) {
341
+        if ($trash) {
342
+            $filePath = substr($keyPath, strlen('/files_trashbin/keys/'));
343
+            $targetDir = $user . '/files_encryption/keys/files_trashbin/' . $filePath . '/' . $this->moduleId . '/' . $filename;
344
+        } else {
345
+            $filePath = substr($keyPath, strlen('/files_encryption/keys/'));
346
+            $targetDir = $user . '/files_encryption/keys/files/' . $filePath . '/' . $this->moduleId . '/' . $filename;
347
+        }
348
+
349
+        if ($user === '') {
350
+            // for system wide mounts we need to check if the mount point really exists
351
+            $normalized = \OC\Files\Filesystem::normalizePath($filePath);
352
+            $systemMountPoints = $this->getSystemMountPoints();
353
+            foreach ($systemMountPoints as $mountPoint) {
354
+                $normalizedMountPoint = \OC\Files\Filesystem::normalizePath($mountPoint['mountpoint']) . '/';
355
+                if (strpos($normalized, $normalizedMountPoint) === 0)
356
+                    return $targetDir;
357
+            }
358
+        } else if ($trash === false && $this->view->file_exists('/' . $user. '/files/' . $filePath)) {
359
+            return $targetDir;
360
+        } else if ($trash === true && $this->view->file_exists('/' . $user. '/files_trashbin/' . $filePath)) {
361
+                return $targetDir;
362
+            }
363
+
364
+        return false;
365
+    }
366
+
367
+    /**
368
+     * delete old keys
369
+     *
370
+     * @param string $user
371
+     */
372
+    private function deleteOldKeys($user) {
373
+        $this->view->deleteAll($user . '/files_encryption/keyfiles');
374
+        $this->view->deleteAll($user . '/files_encryption/share-keys');
375
+    }
376
+
377
+    /**
378
+     * create directories for the keys recursively
379
+     *
380
+     * @param string $path
381
+     */
382
+    private function createPathForKeys($path) {
383
+        if (!$this->view->file_exists($path)) {
384
+            $sub_dirs = explode('/', $path);
385
+            $dir = '';
386
+            foreach ($sub_dirs as $sub_dir) {
387
+                $dir .= '/' . $sub_dir;
388
+                if (!$this->view->is_dir($dir)) {
389
+                    $this->view->mkdir($dir);
390
+                }
391
+            }
392
+        }
393
+    }
394 394
 }
Please login to merge, or discard this patch.
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -141,13 +141,13 @@  discard block
 block discarded – undo
141 141
 			$path = '/files_encryption/keys';
142 142
 			$this->renameFileKeys($user, $path);
143 143
 			$trashPath = '/files_trashbin/keys';
144
-			if ($this->appManager->isEnabledForUser('files_trashbin') && $this->view->is_dir($user . '/' . $trashPath)) {
144
+			if ($this->appManager->isEnabledForUser('files_trashbin') && $this->view->is_dir($user.'/'.$trashPath)) {
145 145
 				$this->renameFileKeys($user, $trashPath, true);
146 146
 				$this->view->deleteAll($trashPath);
147 147
 			}
148 148
 			// delete old folders
149 149
 			$this->deleteOldKeys($user);
150
-			$this->view->getMount('/' . $user)->getStorage()->getScanner()->scan('files_encryption');
150
+			$this->view->getMount('/'.$user)->getStorage()->getScanner()->scan('files_encryption');
151 151
 		}
152 152
 	}
153 153
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 
177 177
 		while ($row = $appSettings->fetch()) {
178 178
 			// 'installed_version' gets deleted at the end of the migration process
179
-			if ($row['configkey'] !== 'installed_version' ) {
179
+			if ($row['configkey'] !== 'installed_version') {
180 180
 				$this->config->setAppValue('encryption', $row['configkey'], $row['configvalue']);
181 181
 				$this->config->deleteAppValue('files_encryption', $row['configkey']);
182 182
 			}
@@ -199,9 +199,9 @@  discard block
 block discarded – undo
199 199
 	 * create backup of system-wide keys
200 200
 	 */
201 201
 	private function backupSystemWideKeys() {
202
-		$backupDir = 'encryption_migration_backup_' . date("Y-m-d_H-i-s");
202
+		$backupDir = 'encryption_migration_backup_'.date("Y-m-d_H-i-s");
203 203
 		$this->view->mkdir($backupDir);
204
-		$this->view->copy('files_encryption', $backupDir . '/files_encryption');
204
+		$this->view->copy('files_encryption', $backupDir.'/files_encryption');
205 205
 	}
206 206
 
207 207
 	/**
@@ -211,9 +211,9 @@  discard block
 block discarded – undo
211 211
 	 * @return bool
212 212
 	 */
213 213
 	private function backupUserKeys($user) {
214
-		$encryptionDir = $user . '/files_encryption';
214
+		$encryptionDir = $user.'/files_encryption';
215 215
 		if ($this->view->is_dir($encryptionDir)) {
216
-			$backupDir = $user . '/encryption_migration_backup_' . date("Y-m-d_H-i-s");
216
+			$backupDir = $user.'/encryption_migration_backup_'.date("Y-m-d_H-i-s");
217 217
 			$this->view->mkdir($backupDir);
218 218
 			$this->view->copy($encryptionDir, $backupDir);
219 219
 			return true;
@@ -226,12 +226,12 @@  discard block
 block discarded – undo
226 226
 	 */
227 227
 	private function renameSystemPrivateKeys() {
228 228
 		$dh = $this->view->opendir('files_encryption');
229
-		$this->createPathForKeys('/files_encryption/' . $this->moduleId );
229
+		$this->createPathForKeys('/files_encryption/'.$this->moduleId);
230 230
 		if (is_resource($dh)) {
231 231
 			while (($privateKey = readdir($dh)) !== false) {
232
-				if (!\OC\Files\Filesystem::isIgnoredDir($privateKey) ) {
233
-					if (!$this->view->is_dir('/files_encryption/' . $privateKey)) {
234
-						$this->view->rename('files_encryption/' . $privateKey, 'files_encryption/' . $this->moduleId . '/' . $privateKey);
232
+				if (!\OC\Files\Filesystem::isIgnoredDir($privateKey)) {
233
+					if (!$this->view->is_dir('/files_encryption/'.$privateKey)) {
234
+						$this->view->rename('files_encryption/'.$privateKey, 'files_encryption/'.$this->moduleId.'/'.$privateKey);
235 235
 						$this->renameSystemPublicKey($privateKey);
236 236
 					}
237 237
 				}
@@ -246,8 +246,8 @@  discard block
 block discarded – undo
246 246
 	 * @param string $privateKey private key for which we want to rename the corresponding public key
247 247
 	 */
248 248
 	private function renameSystemPublicKey($privateKey) {
249
-		$publicKey = substr($privateKey,0 , strrpos($privateKey, '.privateKey')) . '.publicKey';
250
-		$this->view->rename('files_encryption/public_keys/' . $publicKey, 'files_encryption/' . $this->moduleId . '/' . $publicKey);
249
+		$publicKey = substr($privateKey, 0, strrpos($privateKey, '.privateKey')).'.publicKey';
250
+		$this->view->rename('files_encryption/public_keys/'.$publicKey, 'files_encryption/'.$this->moduleId.'/'.$publicKey);
251 251
 	}
252 252
 
253 253
 	/**
@@ -256,8 +256,8 @@  discard block
 block discarded – undo
256 256
 	 * @param string $user
257 257
 	 */
258 258
 	private function renameUsersPrivateKey($user) {
259
-		$oldPrivateKey = $user . '/files_encryption/' . $user . '.privateKey';
260
-		$newPrivateKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.privateKey';
259
+		$oldPrivateKey = $user.'/files_encryption/'.$user.'.privateKey';
260
+		$newPrivateKey = $user.'/files_encryption/'.$this->moduleId.'/'.$user.'.privateKey';
261 261
 		if ($this->view->file_exists($oldPrivateKey)) {
262 262
 			$this->createPathForKeys(dirname($newPrivateKey));
263 263
 			$this->view->rename($oldPrivateKey, $newPrivateKey);
@@ -270,8 +270,8 @@  discard block
 block discarded – undo
270 270
 	 * @param string $user
271 271
 	 */
272 272
 	private function renameUsersPublicKey($user) {
273
-		$oldPublicKey = '/files_encryption/public_keys/' . $user . '.publicKey';
274
-		$newPublicKey = $user . '/files_encryption/' . $this->moduleId . '/' . $user . '.publicKey';
273
+		$oldPublicKey = '/files_encryption/public_keys/'.$user.'.publicKey';
274
+		$newPublicKey = $user.'/files_encryption/'.$this->moduleId.'/'.$user.'.publicKey';
275 275
 		if ($this->view->file_exists($oldPublicKey)) {
276 276
 			$this->createPathForKeys(dirname($newPublicKey));
277 277
 			$this->view->rename($oldPublicKey, $newPublicKey);
@@ -287,27 +287,27 @@  discard block
 block discarded – undo
287 287
 	 */
288 288
 	private function renameFileKeys($user, $path, $trash = false) {
289 289
 
290
-		if ($this->view->is_dir($user . '/' . $path) === false) {
291
-			$this->logger->info('Skip dir /' . $user . '/' . $path . ': does not exist');
290
+		if ($this->view->is_dir($user.'/'.$path) === false) {
291
+			$this->logger->info('Skip dir /'.$user.'/'.$path.': does not exist');
292 292
 			return;
293 293
 		}
294 294
 
295
-		$dh = $this->view->opendir($user . '/' . $path);
295
+		$dh = $this->view->opendir($user.'/'.$path);
296 296
 
297 297
 		if (is_resource($dh)) {
298 298
 			while (($file = readdir($dh)) !== false) {
299 299
 				if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
300
-					if ($this->view->is_dir($user . '/' . $path . '/' . $file)) {
301
-						$this->renameFileKeys($user, $path . '/' . $file, $trash);
300
+					if ($this->view->is_dir($user.'/'.$path.'/'.$file)) {
301
+						$this->renameFileKeys($user, $path.'/'.$file, $trash);
302 302
 					} else {
303 303
 						$target = $this->getTargetDir($user, $path, $file, $trash);
304 304
 						if ($target !== false) {
305 305
 							$this->createPathForKeys(dirname($target));
306
-							$this->view->rename($user . '/' . $path . '/' . $file, $target);
306
+							$this->view->rename($user.'/'.$path.'/'.$file, $target);
307 307
 						} else {
308 308
 							$this->logger->warning(
309
-								'did not move key "' . $file
310
-								. '" could not find the corresponding file in /data/' . $user . '/files.'
309
+								'did not move key "'.$file
310
+								. '" could not find the corresponding file in /data/'.$user.'/files.'
311 311
 							. 'Most likely the key was already moved in a previous migration run and is already on the right place.');
312 312
 						}
313 313
 					}
@@ -340,10 +340,10 @@  discard block
 block discarded – undo
340 340
 	private function getTargetDir($user, $keyPath, $filename, $trash) {
341 341
 		if ($trash) {
342 342
 			$filePath = substr($keyPath, strlen('/files_trashbin/keys/'));
343
-			$targetDir = $user . '/files_encryption/keys/files_trashbin/' . $filePath . '/' . $this->moduleId . '/' . $filename;
343
+			$targetDir = $user.'/files_encryption/keys/files_trashbin/'.$filePath.'/'.$this->moduleId.'/'.$filename;
344 344
 		} else {
345 345
 			$filePath = substr($keyPath, strlen('/files_encryption/keys/'));
346
-			$targetDir = $user . '/files_encryption/keys/files/' . $filePath . '/' . $this->moduleId . '/' . $filename;
346
+			$targetDir = $user.'/files_encryption/keys/files/'.$filePath.'/'.$this->moduleId.'/'.$filename;
347 347
 		}
348 348
 
349 349
 		if ($user === '') {
@@ -351,13 +351,13 @@  discard block
 block discarded – undo
351 351
 			$normalized = \OC\Files\Filesystem::normalizePath($filePath);
352 352
 			$systemMountPoints = $this->getSystemMountPoints();
353 353
 			foreach ($systemMountPoints as $mountPoint) {
354
-				$normalizedMountPoint = \OC\Files\Filesystem::normalizePath($mountPoint['mountpoint']) . '/';
354
+				$normalizedMountPoint = \OC\Files\Filesystem::normalizePath($mountPoint['mountpoint']).'/';
355 355
 				if (strpos($normalized, $normalizedMountPoint) === 0)
356 356
 					return $targetDir;
357 357
 			}
358
-		} else if ($trash === false && $this->view->file_exists('/' . $user. '/files/' . $filePath)) {
358
+		} else if ($trash === false && $this->view->file_exists('/'.$user.'/files/'.$filePath)) {
359 359
 			return $targetDir;
360
-		} else if ($trash === true && $this->view->file_exists('/' . $user. '/files_trashbin/' . $filePath)) {
360
+		} else if ($trash === true && $this->view->file_exists('/'.$user.'/files_trashbin/'.$filePath)) {
361 361
 				return $targetDir;
362 362
 			}
363 363
 
@@ -370,8 +370,8 @@  discard block
 block discarded – undo
370 370
 	 * @param string $user
371 371
 	 */
372 372
 	private function deleteOldKeys($user) {
373
-		$this->view->deleteAll($user . '/files_encryption/keyfiles');
374
-		$this->view->deleteAll($user . '/files_encryption/share-keys');
373
+		$this->view->deleteAll($user.'/files_encryption/keyfiles');
374
+		$this->view->deleteAll($user.'/files_encryption/share-keys');
375 375
 	}
376 376
 
377 377
 	/**
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
 			$sub_dirs = explode('/', $path);
385 385
 			$dir = '';
386 386
 			foreach ($sub_dirs as $sub_dir) {
387
-				$dir .= '/' . $sub_dir;
387
+				$dir .= '/'.$sub_dir;
388 388
 				if (!$this->view->is_dir($dir)) {
389 389
 					$this->view->mkdir($dir);
390 390
 				}
Please login to merge, or discard this patch.
settings/Controller/EncryptionController.php 1 patch
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -40,119 +40,119 @@
 block discarded – undo
40 40
  */
41 41
 class EncryptionController extends Controller {
42 42
 
43
-	/** @var IL10N */
44
-	private $l10n;
45
-
46
-	/** @var IDBConnection */
47
-	private $connection;
48
-
49
-	/** @var IConfig */
50
-	private $config;
51
-
52
-	/** @var IUserManager */
53
-	private $userManager;
54
-
55
-	/** @var View */
56
-	private $view;
57
-
58
-	/** @var ILogger */
59
-	private $logger;
60
-
61
-	/** @var IAppManager */
62
-	private $appManager;
63
-
64
-	/**
65
-	 * @param string $appName
66
-	 * @param IRequest $request
67
-	 * @param IL10N $l10n
68
-	 * @param IConfig $config
69
-	 * @param IDBConnection $connection
70
-	 * @param IUserManager $userManager
71
-	 * @param View $view
72
-	 * @param ILogger $logger
73
-	 * @param IAppManager $appManager
74
-	 */
75
-	public function __construct($appName,
76
-								IRequest $request,
77
-								IL10N $l10n,
78
-								IConfig $config,
79
-								IDBConnection $connection,
80
-								IUserManager $userManager,
81
-								View $view,
82
-								ILogger $logger,
83
-								IAppManager $appManager) {
84
-		parent::__construct($appName, $request);
85
-		$this->l10n = $l10n;
86
-		$this->config = $config;
87
-		$this->connection = $connection;
88
-		$this->view = $view;
89
-		$this->userManager = $userManager;
90
-		$this->logger = $logger;
91
-		$this->appManager = $appManager;
92
-	}
93
-
94
-	/**
95
-	 * @param IConfig $config
96
-	 * @param View $view
97
-	 * @param IDBConnection $connection
98
-	 * @param ILogger $logger
99
-	 * @param IAppManager $appManager
100
-	 * @return Migration
101
-	 */
102
-	protected function getMigration(IConfig $config,
103
-								 View $view,
104
-								 IDBConnection $connection,
105
-								 ILogger $logger,
106
-								 IAppManager $appManager) {
107
-		return new Migration($config, $view, $connection, $logger, $appManager);
108
-	}
109
-
110
-	/**
111
-	 * start migration
112
-	 *
113
-	 * @return array
114
-	 */
115
-	public function startMigration() {
43
+    /** @var IL10N */
44
+    private $l10n;
45
+
46
+    /** @var IDBConnection */
47
+    private $connection;
48
+
49
+    /** @var IConfig */
50
+    private $config;
51
+
52
+    /** @var IUserManager */
53
+    private $userManager;
54
+
55
+    /** @var View */
56
+    private $view;
57
+
58
+    /** @var ILogger */
59
+    private $logger;
60
+
61
+    /** @var IAppManager */
62
+    private $appManager;
63
+
64
+    /**
65
+     * @param string $appName
66
+     * @param IRequest $request
67
+     * @param IL10N $l10n
68
+     * @param IConfig $config
69
+     * @param IDBConnection $connection
70
+     * @param IUserManager $userManager
71
+     * @param View $view
72
+     * @param ILogger $logger
73
+     * @param IAppManager $appManager
74
+     */
75
+    public function __construct($appName,
76
+                                IRequest $request,
77
+                                IL10N $l10n,
78
+                                IConfig $config,
79
+                                IDBConnection $connection,
80
+                                IUserManager $userManager,
81
+                                View $view,
82
+                                ILogger $logger,
83
+                                IAppManager $appManager) {
84
+        parent::__construct($appName, $request);
85
+        $this->l10n = $l10n;
86
+        $this->config = $config;
87
+        $this->connection = $connection;
88
+        $this->view = $view;
89
+        $this->userManager = $userManager;
90
+        $this->logger = $logger;
91
+        $this->appManager = $appManager;
92
+    }
93
+
94
+    /**
95
+     * @param IConfig $config
96
+     * @param View $view
97
+     * @param IDBConnection $connection
98
+     * @param ILogger $logger
99
+     * @param IAppManager $appManager
100
+     * @return Migration
101
+     */
102
+    protected function getMigration(IConfig $config,
103
+                                    View $view,
104
+                                    IDBConnection $connection,
105
+                                    ILogger $logger,
106
+                                    IAppManager $appManager) {
107
+        return new Migration($config, $view, $connection, $logger, $appManager);
108
+    }
109
+
110
+    /**
111
+     * start migration
112
+     *
113
+     * @return array
114
+     */
115
+    public function startMigration() {
116 116
         // allow as long execution on the web server as possible
117
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
118
-			@set_time_limit(0);
119
-		}
120
-
121
-		try {
122
-
123
-			$migration = $this->getMigration($this->config, $this->view, $this->connection, $this->logger, $this->appManager);
124
-			$migration->reorganizeSystemFolderStructure();
125
-			$migration->updateDB();
126
-
127
-			foreach ($this->userManager->getBackends() as $backend) {
128
-				$limit = 500;
129
-				$offset = 0;
130
-				do {
131
-					$users = $backend->getUsers('', $limit, $offset);
132
-					foreach ($users as $user) {
133
-						$migration->reorganizeFolderStructureForUser($user);
134
-					}
135
-					$offset += $limit;
136
-				} while (count($users) >= $limit);
137
-			}
138
-
139
-			$migration->finalCleanUp();
140
-
141
-		} catch (\Exception $e) {
142
-			return [
143
-				'data' => [
144
-					'message' => (string)$this->l10n->t('A problem occurred, please check your log files (Error: %s)', [$e->getMessage()]),
145
-				],
146
-				'status' => 'error',
147
-			];
148
-		}
149
-
150
-		return [
151
-			'data' => [
152
-				'message' => (string) $this->l10n->t('Migration Completed'),
153
-				],
154
-			'status' => 'success',
155
-		];
156
-	}
117
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
118
+            @set_time_limit(0);
119
+        }
120
+
121
+        try {
122
+
123
+            $migration = $this->getMigration($this->config, $this->view, $this->connection, $this->logger, $this->appManager);
124
+            $migration->reorganizeSystemFolderStructure();
125
+            $migration->updateDB();
126
+
127
+            foreach ($this->userManager->getBackends() as $backend) {
128
+                $limit = 500;
129
+                $offset = 0;
130
+                do {
131
+                    $users = $backend->getUsers('', $limit, $offset);
132
+                    foreach ($users as $user) {
133
+                        $migration->reorganizeFolderStructureForUser($user);
134
+                    }
135
+                    $offset += $limit;
136
+                } while (count($users) >= $limit);
137
+            }
138
+
139
+            $migration->finalCleanUp();
140
+
141
+        } catch (\Exception $e) {
142
+            return [
143
+                'data' => [
144
+                    'message' => (string)$this->l10n->t('A problem occurred, please check your log files (Error: %s)', [$e->getMessage()]),
145
+                ],
146
+                'status' => 'error',
147
+            ];
148
+        }
149
+
150
+        return [
151
+            'data' => [
152
+                'message' => (string) $this->l10n->t('Migration Completed'),
153
+                ],
154
+            'status' => 'success',
155
+        ];
156
+    }
157 157
 
158 158
 }
Please login to merge, or discard this patch.