Completed
Pull Request — master (#4396)
by Morris
13:57
created
apps/files/lib/Command/Scan.php 2 patches
Indentation   +281 added lines, -281 removed lines patch added patch discarded remove patch
@@ -44,310 +44,310 @@
 block discarded – undo
44 44
 
45 45
 class Scan extends Base {
46 46
 
47
-	/** @var IUserManager $userManager */
48
-	private $userManager;
49
-	/** @var float */
50
-	protected $execTime = 0;
51
-	/** @var int */
52
-	protected $foldersCounter = 0;
53
-	/** @var int */
54
-	protected $filesCounter = 0;
47
+    /** @var IUserManager $userManager */
48
+    private $userManager;
49
+    /** @var float */
50
+    protected $execTime = 0;
51
+    /** @var int */
52
+    protected $foldersCounter = 0;
53
+    /** @var int */
54
+    protected $filesCounter = 0;
55 55
 
56
-	public function __construct(IUserManager $userManager) {
57
-		$this->userManager = $userManager;
58
-		parent::__construct();
59
-	}
56
+    public function __construct(IUserManager $userManager) {
57
+        $this->userManager = $userManager;
58
+        parent::__construct();
59
+    }
60 60
 
61
-	protected function configure() {
62
-		parent::configure();
61
+    protected function configure() {
62
+        parent::configure();
63 63
 
64
-		$this
65
-			->setName('files:scan')
66
-			->setDescription('rescan filesystem')
67
-			->addArgument(
68
-				'user_id',
69
-				InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
70
-				'will rescan all files of the given user(s)'
71
-			)
72
-			->addOption(
73
-				'path',
74
-				'p',
75
-				InputArgument::OPTIONAL,
76
-				'limit rescan to this path, eg. --path="/alice/files/Music", the user_id is determined by the path and the user_id parameter and --all are ignored'
77
-			)
78
-			->addOption(
79
-				'quiet',
80
-				'q',
81
-				InputOption::VALUE_NONE,
82
-				'suppress any output'
83
-			)
84
-			->addOption(
85
-				'verbose',
86
-				'-v|vv|vvv',
87
-				InputOption::VALUE_NONE,
88
-				'verbose the output'
89
-			)
90
-			->addOption(
91
-				'all',
92
-				null,
93
-				InputOption::VALUE_NONE,
94
-				'will rescan all files of all known users'
95
-			)->addOption(
96
-				'unscanned',
97
-				null,
98
-				InputOption::VALUE_NONE,
99
-				'only scan files which are marked as not fully scanned'
100
-			);
101
-	}
64
+        $this
65
+            ->setName('files:scan')
66
+            ->setDescription('rescan filesystem')
67
+            ->addArgument(
68
+                'user_id',
69
+                InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
70
+                'will rescan all files of the given user(s)'
71
+            )
72
+            ->addOption(
73
+                'path',
74
+                'p',
75
+                InputArgument::OPTIONAL,
76
+                'limit rescan to this path, eg. --path="/alice/files/Music", the user_id is determined by the path and the user_id parameter and --all are ignored'
77
+            )
78
+            ->addOption(
79
+                'quiet',
80
+                'q',
81
+                InputOption::VALUE_NONE,
82
+                'suppress any output'
83
+            )
84
+            ->addOption(
85
+                'verbose',
86
+                '-v|vv|vvv',
87
+                InputOption::VALUE_NONE,
88
+                'verbose the output'
89
+            )
90
+            ->addOption(
91
+                'all',
92
+                null,
93
+                InputOption::VALUE_NONE,
94
+                'will rescan all files of all known users'
95
+            )->addOption(
96
+                'unscanned',
97
+                null,
98
+                InputOption::VALUE_NONE,
99
+                'only scan files which are marked as not fully scanned'
100
+            );
101
+    }
102 102
 
103
-	public function checkScanWarning($fullPath, OutputInterface $output) {
104
-		$normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
105
-		$path = basename($fullPath);
103
+    public function checkScanWarning($fullPath, OutputInterface $output) {
104
+        $normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
105
+        $path = basename($fullPath);
106 106
 
107
-		if ($normalizedPath !== $path) {
108
-			$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
109
-		}
110
-	}
107
+        if ($normalizedPath !== $path) {
108
+            $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
109
+        }
110
+    }
111 111
 
112
-	protected function scanFiles($user, $path, $verbose, OutputInterface $output, $backgroundScan = false) {
113
-		$connection = $this->reconnectToDatabase($output);
114
-		$scanner = new \OC\Files\Utils\Scanner($user, $connection, \OC::$server->getLogger());
115
-		# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
116
-		# printout and count
117
-		if ($verbose) {
118
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
119
-				$output->writeln("\tFile   <info>$path</info>");
120
-				$this->filesCounter += 1;
121
-				if ($this->hasBeenInterrupted()) {
122
-					throw new InterruptedException();
123
-				}
124
-			});
125
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
126
-				$output->writeln("\tFolder <info>$path</info>");
127
-				$this->foldersCounter += 1;
128
-				if ($this->hasBeenInterrupted()) {
129
-					throw new InterruptedException();
130
-				}
131
-			});
132
-			$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
133
-				$output->writeln("Error while scanning, storage not available (" . $e->getMessage() . ")");
134
-			});
135
-			# count only
136
-		} else {
137
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function () use ($output) {
138
-				$this->filesCounter += 1;
139
-				if ($this->hasBeenInterrupted()) {
140
-					throw new InterruptedException();
141
-				}
142
-			});
143
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function () use ($output) {
144
-				$this->foldersCounter += 1;
145
-				if ($this->hasBeenInterrupted()) {
146
-					throw new InterruptedException();
147
-				}
148
-			});
149
-		}
150
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
151
-			$this->checkScanWarning($path, $output);
152
-		});
153
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
154
-			$this->checkScanWarning($path, $output);
155
-		});
112
+    protected function scanFiles($user, $path, $verbose, OutputInterface $output, $backgroundScan = false) {
113
+        $connection = $this->reconnectToDatabase($output);
114
+        $scanner = new \OC\Files\Utils\Scanner($user, $connection, \OC::$server->getLogger());
115
+        # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
116
+        # printout and count
117
+        if ($verbose) {
118
+            $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
119
+                $output->writeln("\tFile   <info>$path</info>");
120
+                $this->filesCounter += 1;
121
+                if ($this->hasBeenInterrupted()) {
122
+                    throw new InterruptedException();
123
+                }
124
+            });
125
+            $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
126
+                $output->writeln("\tFolder <info>$path</info>");
127
+                $this->foldersCounter += 1;
128
+                if ($this->hasBeenInterrupted()) {
129
+                    throw new InterruptedException();
130
+                }
131
+            });
132
+            $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
133
+                $output->writeln("Error while scanning, storage not available (" . $e->getMessage() . ")");
134
+            });
135
+            # count only
136
+        } else {
137
+            $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function () use ($output) {
138
+                $this->filesCounter += 1;
139
+                if ($this->hasBeenInterrupted()) {
140
+                    throw new InterruptedException();
141
+                }
142
+            });
143
+            $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function () use ($output) {
144
+                $this->foldersCounter += 1;
145
+                if ($this->hasBeenInterrupted()) {
146
+                    throw new InterruptedException();
147
+                }
148
+            });
149
+        }
150
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
151
+            $this->checkScanWarning($path, $output);
152
+        });
153
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
154
+            $this->checkScanWarning($path, $output);
155
+        });
156 156
 
157
-		try {
158
-			if ($backgroundScan) {
159
-				$scanner->backgroundScan($path);
160
-			} else {
161
-				$scanner->scan($path);
162
-			}
163
-		} catch (ForbiddenException $e) {
164
-			$output->writeln("<error>Home storage for user $user not writable</error>");
165
-			$output->writeln("Make sure you're running the scan command only as the user the web server runs as");
166
-		} catch (InterruptedException $e) {
167
-			# exit the function if ctrl-c has been pressed
168
-			$output->writeln('Interrupted by user');
169
-		} catch (NotFoundException $e) {
170
-			$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
171
-		} catch (\Exception $e) {
172
-			$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
173
-			$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
174
-		}
175
-	}
157
+        try {
158
+            if ($backgroundScan) {
159
+                $scanner->backgroundScan($path);
160
+            } else {
161
+                $scanner->scan($path);
162
+            }
163
+        } catch (ForbiddenException $e) {
164
+            $output->writeln("<error>Home storage for user $user not writable</error>");
165
+            $output->writeln("Make sure you're running the scan command only as the user the web server runs as");
166
+        } catch (InterruptedException $e) {
167
+            # exit the function if ctrl-c has been pressed
168
+            $output->writeln('Interrupted by user');
169
+        } catch (NotFoundException $e) {
170
+            $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
171
+        } catch (\Exception $e) {
172
+            $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
173
+            $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
174
+        }
175
+    }
176 176
 
177 177
 
178
-	protected function execute(InputInterface $input, OutputInterface $output) {
179
-		$inputPath = $input->getOption('path');
180
-		if ($inputPath) {
181
-			$inputPath = '/' . trim($inputPath, '/');
182
-			list (, $user,) = explode('/', $inputPath, 3);
183
-			$users = array($user);
184
-		} else if ($input->getOption('all')) {
185
-			$users = $this->userManager->search('');
186
-		} else {
187
-			$users = $input->getArgument('user_id');
188
-		}
178
+    protected function execute(InputInterface $input, OutputInterface $output) {
179
+        $inputPath = $input->getOption('path');
180
+        if ($inputPath) {
181
+            $inputPath = '/' . trim($inputPath, '/');
182
+            list (, $user,) = explode('/', $inputPath, 3);
183
+            $users = array($user);
184
+        } else if ($input->getOption('all')) {
185
+            $users = $this->userManager->search('');
186
+        } else {
187
+            $users = $input->getArgument('user_id');
188
+        }
189 189
 
190
-		# no messaging level option means: no full printout but statistics
191
-		# $quiet   means no print at all
192
-		# $verbose means full printout including statistics
193
-		# -q	-v	full	stat
194
-		#  0	 0	no	yes
195
-		#  0	 1	yes	yes
196
-		#  1	--	no	no  (quiet overrules verbose)
197
-		$verbose = $input->getOption('verbose');
198
-		$quiet = $input->getOption('quiet');
199
-		# restrict the verbosity level to VERBOSITY_VERBOSE
200
-		if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
201
-			$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
202
-		}
203
-		if ($quiet) {
204
-			$verbose = false;
205
-		}
190
+        # no messaging level option means: no full printout but statistics
191
+        # $quiet   means no print at all
192
+        # $verbose means full printout including statistics
193
+        # -q	-v	full	stat
194
+        #  0	 0	no	yes
195
+        #  0	 1	yes	yes
196
+        #  1	--	no	no  (quiet overrules verbose)
197
+        $verbose = $input->getOption('verbose');
198
+        $quiet = $input->getOption('quiet');
199
+        # restrict the verbosity level to VERBOSITY_VERBOSE
200
+        if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
201
+            $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
202
+        }
203
+        if ($quiet) {
204
+            $verbose = false;
205
+        }
206 206
 
207
-		# check quantity of users to be process and show it on the command line
208
-		$users_total = count($users);
209
-		if ($users_total === 0) {
210
-			$output->writeln("<error>Please specify the user id to scan, \"--all\" to scan for all users or \"--path=...\"</error>");
211
-			return;
212
-		} else {
213
-			if ($users_total > 1) {
214
-				$output->writeln("\nScanning files for $users_total users");
215
-			}
216
-		}
207
+        # check quantity of users to be process and show it on the command line
208
+        $users_total = count($users);
209
+        if ($users_total === 0) {
210
+            $output->writeln("<error>Please specify the user id to scan, \"--all\" to scan for all users or \"--path=...\"</error>");
211
+            return;
212
+        } else {
213
+            if ($users_total > 1) {
214
+                $output->writeln("\nScanning files for $users_total users");
215
+            }
216
+        }
217 217
 
218
-		$this->initTools();
218
+        $this->initTools();
219 219
 
220
-		$user_count = 0;
221
-		foreach ($users as $user) {
222
-			if (is_object($user)) {
223
-				$user = $user->getUID();
224
-			}
225
-			$path = $inputPath ? $inputPath : '/' . $user;
226
-			$user_count += 1;
227
-			if ($this->userManager->userExists($user)) {
228
-				# add an extra line when verbose is set to optical separate users
229
-				if ($verbose) {
230
-					$output->writeln("");
231
-				}
232
-				$output->writeln("Starting scan for user $user_count out of $users_total ($user)");
233
-				# full: printout data if $verbose was set
234
-				$this->scanFiles($user, $path, $verbose, $output, $input->getOption('unscanned'));
235
-			} else {
236
-				$output->writeln("<error>Unknown user $user_count $user</error>");
237
-			}
238
-			# check on each user if there was a user interrupt (ctrl-c) and exit foreach
239
-			if ($this->hasBeenInterrupted()) {
240
-				break;
241
-			}
242
-		}
220
+        $user_count = 0;
221
+        foreach ($users as $user) {
222
+            if (is_object($user)) {
223
+                $user = $user->getUID();
224
+            }
225
+            $path = $inputPath ? $inputPath : '/' . $user;
226
+            $user_count += 1;
227
+            if ($this->userManager->userExists($user)) {
228
+                # add an extra line when verbose is set to optical separate users
229
+                if ($verbose) {
230
+                    $output->writeln("");
231
+                }
232
+                $output->writeln("Starting scan for user $user_count out of $users_total ($user)");
233
+                # full: printout data if $verbose was set
234
+                $this->scanFiles($user, $path, $verbose, $output, $input->getOption('unscanned'));
235
+            } else {
236
+                $output->writeln("<error>Unknown user $user_count $user</error>");
237
+            }
238
+            # check on each user if there was a user interrupt (ctrl-c) and exit foreach
239
+            if ($this->hasBeenInterrupted()) {
240
+                break;
241
+            }
242
+        }
243 243
 
244
-		# stat: printout statistics if $quiet was not set
245
-		if (!$quiet) {
246
-			$this->presentStats($output);
247
-		}
248
-	}
244
+        # stat: printout statistics if $quiet was not set
245
+        if (!$quiet) {
246
+            $this->presentStats($output);
247
+        }
248
+    }
249 249
 
250
-	/**
251
-	 * Initialises some useful tools for the Command
252
-	 */
253
-	protected function initTools() {
254
-		// Start the timer
255
-		$this->execTime = -microtime(true);
256
-		// Convert PHP errors to exceptions
257
-		set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
258
-	}
250
+    /**
251
+     * Initialises some useful tools for the Command
252
+     */
253
+    protected function initTools() {
254
+        // Start the timer
255
+        $this->execTime = -microtime(true);
256
+        // Convert PHP errors to exceptions
257
+        set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
258
+    }
259 259
 
260
-	/**
261
-	 * Processes PHP errors as exceptions in order to be able to keep track of problems
262
-	 *
263
-	 * @see https://secure.php.net/manual/en/function.set-error-handler.php
264
-	 *
265
-	 * @param int $severity the level of the error raised
266
-	 * @param string $message
267
-	 * @param string $file the filename that the error was raised in
268
-	 * @param int $line the line number the error was raised
269
-	 *
270
-	 * @throws \ErrorException
271
-	 */
272
-	public function exceptionErrorHandler($severity, $message, $file, $line) {
273
-		if (!(error_reporting() & $severity)) {
274
-			// This error code is not included in error_reporting
275
-			return;
276
-		}
277
-		throw new \ErrorException($message, 0, $severity, $file, $line);
278
-	}
260
+    /**
261
+     * Processes PHP errors as exceptions in order to be able to keep track of problems
262
+     *
263
+     * @see https://secure.php.net/manual/en/function.set-error-handler.php
264
+     *
265
+     * @param int $severity the level of the error raised
266
+     * @param string $message
267
+     * @param string $file the filename that the error was raised in
268
+     * @param int $line the line number the error was raised
269
+     *
270
+     * @throws \ErrorException
271
+     */
272
+    public function exceptionErrorHandler($severity, $message, $file, $line) {
273
+        if (!(error_reporting() & $severity)) {
274
+            // This error code is not included in error_reporting
275
+            return;
276
+        }
277
+        throw new \ErrorException($message, 0, $severity, $file, $line);
278
+    }
279 279
 
280
-	/**
281
-	 * @param OutputInterface $output
282
-	 */
283
-	protected function presentStats(OutputInterface $output) {
284
-		// Stop the timer
285
-		$this->execTime += microtime(true);
286
-		$output->writeln("");
280
+    /**
281
+     * @param OutputInterface $output
282
+     */
283
+    protected function presentStats(OutputInterface $output) {
284
+        // Stop the timer
285
+        $this->execTime += microtime(true);
286
+        $output->writeln("");
287 287
 
288
-		$headers = [
289
-			'Folders', 'Files', 'Elapsed time'
290
-		];
288
+        $headers = [
289
+            'Folders', 'Files', 'Elapsed time'
290
+        ];
291 291
 
292
-		$this->showSummary($headers, null, $output);
293
-	}
292
+        $this->showSummary($headers, null, $output);
293
+    }
294 294
 
295
-	/**
296
-	 * Shows a summary of operations
297
-	 *
298
-	 * @param string[] $headers
299
-	 * @param string[] $rows
300
-	 * @param OutputInterface $output
301
-	 */
302
-	protected function showSummary($headers, $rows, OutputInterface $output) {
303
-		$niceDate = $this->formatExecTime();
304
-		if (!$rows) {
305
-			$rows = [
306
-				$this->foldersCounter,
307
-				$this->filesCounter,
308
-				$niceDate,
309
-			];
310
-		}
311
-		$table = new Table($output);
312
-		$table
313
-			->setHeaders($headers)
314
-			->setRows([$rows]);
315
-		$table->render();
316
-	}
295
+    /**
296
+     * Shows a summary of operations
297
+     *
298
+     * @param string[] $headers
299
+     * @param string[] $rows
300
+     * @param OutputInterface $output
301
+     */
302
+    protected function showSummary($headers, $rows, OutputInterface $output) {
303
+        $niceDate = $this->formatExecTime();
304
+        if (!$rows) {
305
+            $rows = [
306
+                $this->foldersCounter,
307
+                $this->filesCounter,
308
+                $niceDate,
309
+            ];
310
+        }
311
+        $table = new Table($output);
312
+        $table
313
+            ->setHeaders($headers)
314
+            ->setRows([$rows]);
315
+        $table->render();
316
+    }
317 317
 
318 318
 
319
-	/**
320
-	 * Formats microtime into a human readable format
321
-	 *
322
-	 * @return string
323
-	 */
324
-	protected function formatExecTime() {
325
-		list($secs, $tens) = explode('.', sprintf("%.1f", ($this->execTime)));
319
+    /**
320
+     * Formats microtime into a human readable format
321
+     *
322
+     * @return string
323
+     */
324
+    protected function formatExecTime() {
325
+        list($secs, $tens) = explode('.', sprintf("%.1f", ($this->execTime)));
326 326
 
327
-		# if you want to have microseconds add this:   . '.' . $tens;
328
-		return date('H:i:s', $secs);
329
-	}
327
+        # if you want to have microseconds add this:   . '.' . $tens;
328
+        return date('H:i:s', $secs);
329
+    }
330 330
 
331
-	/**
332
-	 * @return \OCP\IDBConnection
333
-	 */
334
-	protected function reconnectToDatabase(OutputInterface $output) {
335
-		/** @var Connection | IDBConnection $connection */
336
-		$connection = \OC::$server->getDatabaseConnection();
337
-		try {
338
-			$connection->close();
339
-		} catch (\Exception $ex) {
340
-			$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
341
-		}
342
-		while (!$connection->isConnected()) {
343
-			try {
344
-				$connection->connect();
345
-			} catch (\Exception $ex) {
346
-				$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
347
-				sleep(60);
348
-			}
349
-		}
350
-		return $connection;
351
-	}
331
+    /**
332
+     * @return \OCP\IDBConnection
333
+     */
334
+    protected function reconnectToDatabase(OutputInterface $output) {
335
+        /** @var Connection | IDBConnection $connection */
336
+        $connection = \OC::$server->getDatabaseConnection();
337
+        try {
338
+            $connection->close();
339
+        } catch (\Exception $ex) {
340
+            $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
341
+        }
342
+        while (!$connection->isConnected()) {
343
+            try {
344
+                $connection->connect();
345
+            } catch (\Exception $ex) {
346
+                $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
347
+                sleep(60);
348
+            }
349
+        }
350
+        return $connection;
351
+    }
352 352
 
353 353
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 		$path = basename($fullPath);
106 106
 
107 107
 		if ($normalizedPath !== $path) {
108
-			$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
108
+			$output->writeln("\t<error>Entry \"".$fullPath.'" will not be accessible due to incompatible encoding</error>');
109 109
 		}
110 110
 	}
111 111
 
@@ -115,42 +115,42 @@  discard block
 block discarded – undo
115 115
 		# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
116 116
 		# printout and count
117 117
 		if ($verbose) {
118
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
118
+			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function($path) use ($output) {
119 119
 				$output->writeln("\tFile   <info>$path</info>");
120 120
 				$this->filesCounter += 1;
121 121
 				if ($this->hasBeenInterrupted()) {
122 122
 					throw new InterruptedException();
123 123
 				}
124 124
 			});
125
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
125
+			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function($path) use ($output) {
126 126
 				$output->writeln("\tFolder <info>$path</info>");
127 127
 				$this->foldersCounter += 1;
128 128
 				if ($this->hasBeenInterrupted()) {
129 129
 					throw new InterruptedException();
130 130
 				}
131 131
 			});
132
-			$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
133
-				$output->writeln("Error while scanning, storage not available (" . $e->getMessage() . ")");
132
+			$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function(StorageNotAvailableException $e) use ($output) {
133
+				$output->writeln("Error while scanning, storage not available (".$e->getMessage().")");
134 134
 			});
135 135
 			# count only
136 136
 		} else {
137
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function () use ($output) {
137
+			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function() use ($output) {
138 138
 				$this->filesCounter += 1;
139 139
 				if ($this->hasBeenInterrupted()) {
140 140
 					throw new InterruptedException();
141 141
 				}
142 142
 			});
143
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function () use ($output) {
143
+			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function() use ($output) {
144 144
 				$this->foldersCounter += 1;
145 145
 				if ($this->hasBeenInterrupted()) {
146 146
 					throw new InterruptedException();
147 147
 				}
148 148
 			});
149 149
 		}
150
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
150
+		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function($path) use ($output) {
151 151
 			$this->checkScanWarning($path, $output);
152 152
 		});
153
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
153
+		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function($path) use ($output) {
154 154
 			$this->checkScanWarning($path, $output);
155 155
 		});
156 156
 
@@ -167,10 +167,10 @@  discard block
 block discarded – undo
167 167
 			# exit the function if ctrl-c has been pressed
168 168
 			$output->writeln('Interrupted by user');
169 169
 		} catch (NotFoundException $e) {
170
-			$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
170
+			$output->writeln('<error>Path not found: '.$e->getMessage().'</error>');
171 171
 		} catch (\Exception $e) {
172
-			$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
173
-			$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
172
+			$output->writeln('<error>Exception during scan: '.$e->getMessage().'</error>');
173
+			$output->writeln('<error>'.$e->getTraceAsString().'</error>');
174 174
 		}
175 175
 	}
176 176
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 	protected function execute(InputInterface $input, OutputInterface $output) {
179 179
 		$inputPath = $input->getOption('path');
180 180
 		if ($inputPath) {
181
-			$inputPath = '/' . trim($inputPath, '/');
181
+			$inputPath = '/'.trim($inputPath, '/');
182 182
 			list (, $user,) = explode('/', $inputPath, 3);
183 183
 			$users = array($user);
184 184
 		} else if ($input->getOption('all')) {
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 			if (is_object($user)) {
223 223
 				$user = $user->getUID();
224 224
 			}
225
-			$path = $inputPath ? $inputPath : '/' . $user;
225
+			$path = $inputPath ? $inputPath : '/'.$user;
226 226
 			$user_count += 1;
227 227
 			if ($this->userManager->userExists($user)) {
228 228
 				# add an extra line when verbose is set to optical separate users
Please login to merge, or discard this patch.
apps/files/lib/Command/ScanAppData.php 2 patches
Indentation   +262 added lines, -262 removed lines patch added patch discarded remove patch
@@ -21,266 +21,266 @@
 block discarded – undo
21 21
 
22 22
 class ScanAppData extends Base {
23 23
 
24
-	/** @var IRootFolder */
25
-	protected $root;
26
-	/** @var IConfig */
27
-	protected $config;
28
-	/** @var float */
29
-	protected $execTime = 0;
30
-	/** @var int */
31
-	protected $foldersCounter = 0;
32
-	/** @var int */
33
-	protected $filesCounter = 0;
34
-
35
-	public function __construct(IRootFolder $rootFolder, IConfig $config) {
36
-		parent::__construct();
37
-
38
-		$this->root = $rootFolder;
39
-		$this->config = $config;
40
-	}
41
-
42
-	protected function configure() {
43
-		parent::configure();
44
-
45
-		$this
46
-			->setName('files:scan-app-data')
47
-			->setDescription('rescan the AppData folder')
48
-			->addOption(
49
-				'quiet',
50
-				'q',
51
-				InputOption::VALUE_NONE,
52
-				'suppress any output'
53
-			)
54
-			->addOption(
55
-				'verbose',
56
-				'-v|vv|vvv',
57
-				InputOption::VALUE_NONE,
58
-				'verbose the output'
59
-			);
60
-	}
61
-
62
-	public function checkScanWarning($fullPath, OutputInterface $output) {
63
-		$normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
64
-		$path = basename($fullPath);
65
-
66
-		if ($normalizedPath !== $path) {
67
-			$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
68
-		}
69
-	}
70
-
71
-	protected function scanFiles($verbose, OutputInterface $output) {
72
-		try {
73
-			$appData = $this->getAppDataFolder();
74
-		} catch (NotFoundException $e) {
75
-			$output->writeln('NoAppData folder found');
76
-			return;
77
-		}
78
-
79
-		$connection = $this->reconnectToDatabase($output);
80
-		$scanner = new \OC\Files\Utils\Scanner(null, $connection, \OC::$server->getLogger());
81
-		# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
82
-		# printout and count
83
-		if ($verbose) {
84
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
85
-				$output->writeln("\tFile   <info>$path</info>");
86
-				$this->filesCounter += 1;
87
-				if ($this->hasBeenInterrupted()) {
88
-					throw new InterruptedException();
89
-				}
90
-			});
91
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
92
-				$output->writeln("\tFolder <info>$path</info>");
93
-				$this->foldersCounter += 1;
94
-				if ($this->hasBeenInterrupted()) {
95
-					throw new InterruptedException();
96
-				}
97
-			});
98
-			$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
99
-				$output->writeln("Error while scanning, storage not available (" . $e->getMessage() . ")");
100
-			});
101
-			# count only
102
-		} else {
103
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function () use ($output) {
104
-				$this->filesCounter += 1;
105
-				if ($this->hasBeenInterrupted()) {
106
-					throw new InterruptedException();
107
-				}
108
-			});
109
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function () use ($output) {
110
-				$this->foldersCounter += 1;
111
-				if ($this->hasBeenInterrupted()) {
112
-					throw new InterruptedException();
113
-				}
114
-			});
115
-		}
116
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function($path) use ($output) {
117
-			$this->checkScanWarning($path, $output);
118
-		});
119
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function($path) use ($output) {
120
-			$this->checkScanWarning($path, $output);
121
-		});
122
-
123
-		try {
124
-			$scanner->scan($appData->getPath());
125
-		} catch (ForbiddenException $e) {
126
-			$output->writeln("<error>Storage not writable</error>");
127
-			$output->writeln("Make sure you're running the scan command only as the user the web server runs as");
128
-		} catch (InterruptedException $e) {
129
-			# exit the function if ctrl-c has been pressed
130
-			$output->writeln('Interrupted by user');
131
-		} catch (NotFoundException $e) {
132
-			$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
133
-		} catch (\Exception $e) {
134
-			$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
135
-			$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
136
-		}
137
-	}
138
-
139
-
140
-	protected function execute(InputInterface $input, OutputInterface $output) {
141
-		# no messaging level option means: no full printout but statistics
142
-		# $quiet   means no print at all
143
-		# $verbose means full printout including statistics
144
-		# -q	-v	full	stat
145
-		#  0	 0	no	yes
146
-		#  0	 1	yes	yes
147
-		#  1	--	no	no  (quiet overrules verbose)
148
-		$verbose = $input->getOption('verbose');
149
-		$quiet = $input->getOption('quiet');
150
-		# restrict the verbosity level to VERBOSITY_VERBOSE
151
-		if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
152
-			$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
153
-		}
154
-		if ($quiet) {
155
-			$verbose = false;
156
-		}
157
-
158
-		$output->writeln("\nScanning AppData for files");
159
-
160
-		$this->initTools();
161
-
162
-		$this->scanFiles($verbose, $output);
163
-
164
-		# stat: printout statistics if $quiet was not set
165
-		if (!$quiet) {
166
-			$this->presentStats($output);
167
-		}
168
-	}
169
-
170
-	/**
171
-	 * Initialises some useful tools for the Command
172
-	 */
173
-	protected function initTools() {
174
-		// Start the timer
175
-		$this->execTime = -microtime(true);
176
-		// Convert PHP errors to exceptions
177
-		set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
178
-	}
179
-
180
-	/**
181
-	 * Processes PHP errors as exceptions in order to be able to keep track of problems
182
-	 *
183
-	 * @see https://secure.php.net/manual/en/function.set-error-handler.php
184
-	 *
185
-	 * @param int $severity the level of the error raised
186
-	 * @param string $message
187
-	 * @param string $file the filename that the error was raised in
188
-	 * @param int $line the line number the error was raised
189
-	 *
190
-	 * @throws \ErrorException
191
-	 */
192
-	public function exceptionErrorHandler($severity, $message, $file, $line) {
193
-		if (!(error_reporting() & $severity)) {
194
-			// This error code is not included in error_reporting
195
-			return;
196
-		}
197
-		throw new \ErrorException($message, 0, $severity, $file, $line);
198
-	}
199
-
200
-	/**
201
-	 * @param OutputInterface $output
202
-	 */
203
-	protected function presentStats(OutputInterface $output) {
204
-		// Stop the timer
205
-		$this->execTime += microtime(true);
206
-		$output->writeln("");
207
-
208
-		$headers = [
209
-			'Folders', 'Files', 'Elapsed time'
210
-		];
211
-
212
-		$this->showSummary($headers, null, $output);
213
-	}
214
-
215
-	/**
216
-	 * Shows a summary of operations
217
-	 *
218
-	 * @param string[] $headers
219
-	 * @param string[] $rows
220
-	 * @param OutputInterface $output
221
-	 */
222
-	protected function showSummary($headers, $rows, OutputInterface $output) {
223
-		$niceDate = $this->formatExecTime();
224
-		if (!$rows) {
225
-			$rows = [
226
-				$this->foldersCounter,
227
-				$this->filesCounter,
228
-				$niceDate,
229
-			];
230
-		}
231
-		$table = new Table($output);
232
-		$table
233
-			->setHeaders($headers)
234
-			->setRows([$rows]);
235
-		$table->render();
236
-	}
237
-
238
-
239
-	/**
240
-	 * Formats microtime into a human readable format
241
-	 *
242
-	 * @return string
243
-	 */
244
-	protected function formatExecTime() {
245
-		list($secs, $tens) = explode('.', sprintf("%.1f", ($this->execTime)));
246
-
247
-		# if you want to have microseconds add this:   . '.' . $tens;
248
-		return date('H:i:s', $secs);
249
-	}
250
-
251
-	/**
252
-	 * @return \OCP\IDBConnection
253
-	 */
254
-	protected function reconnectToDatabase(OutputInterface $output) {
255
-		/** @var Connection | IDBConnection $connection*/
256
-		$connection = \OC::$server->getDatabaseConnection();
257
-		try {
258
-			$connection->close();
259
-		} catch (\Exception $ex) {
260
-			$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
261
-		}
262
-		while (!$connection->isConnected()) {
263
-			try {
264
-				$connection->connect();
265
-			} catch (\Exception $ex) {
266
-				$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
267
-				sleep(60);
268
-			}
269
-		}
270
-		return $connection;
271
-	}
272
-
273
-	/**
274
-	 * @return \OCP\Files\Folder
275
-	 * @throws NotFoundException
276
-	 */
277
-	private function getAppDataFolder() {
278
-		$instanceId = $this->config->getSystemValue('instanceid', null);
279
-
280
-		if ($instanceId === null) {
281
-			throw new NotFoundException();
282
-		}
283
-
284
-		return $this->root->get('appdata_'.$instanceId);
285
-	}
24
+    /** @var IRootFolder */
25
+    protected $root;
26
+    /** @var IConfig */
27
+    protected $config;
28
+    /** @var float */
29
+    protected $execTime = 0;
30
+    /** @var int */
31
+    protected $foldersCounter = 0;
32
+    /** @var int */
33
+    protected $filesCounter = 0;
34
+
35
+    public function __construct(IRootFolder $rootFolder, IConfig $config) {
36
+        parent::__construct();
37
+
38
+        $this->root = $rootFolder;
39
+        $this->config = $config;
40
+    }
41
+
42
+    protected function configure() {
43
+        parent::configure();
44
+
45
+        $this
46
+            ->setName('files:scan-app-data')
47
+            ->setDescription('rescan the AppData folder')
48
+            ->addOption(
49
+                'quiet',
50
+                'q',
51
+                InputOption::VALUE_NONE,
52
+                'suppress any output'
53
+            )
54
+            ->addOption(
55
+                'verbose',
56
+                '-v|vv|vvv',
57
+                InputOption::VALUE_NONE,
58
+                'verbose the output'
59
+            );
60
+    }
61
+
62
+    public function checkScanWarning($fullPath, OutputInterface $output) {
63
+        $normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
64
+        $path = basename($fullPath);
65
+
66
+        if ($normalizedPath !== $path) {
67
+            $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
68
+        }
69
+    }
70
+
71
+    protected function scanFiles($verbose, OutputInterface $output) {
72
+        try {
73
+            $appData = $this->getAppDataFolder();
74
+        } catch (NotFoundException $e) {
75
+            $output->writeln('NoAppData folder found');
76
+            return;
77
+        }
78
+
79
+        $connection = $this->reconnectToDatabase($output);
80
+        $scanner = new \OC\Files\Utils\Scanner(null, $connection, \OC::$server->getLogger());
81
+        # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
82
+        # printout and count
83
+        if ($verbose) {
84
+            $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
85
+                $output->writeln("\tFile   <info>$path</info>");
86
+                $this->filesCounter += 1;
87
+                if ($this->hasBeenInterrupted()) {
88
+                    throw new InterruptedException();
89
+                }
90
+            });
91
+            $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
92
+                $output->writeln("\tFolder <info>$path</info>");
93
+                $this->foldersCounter += 1;
94
+                if ($this->hasBeenInterrupted()) {
95
+                    throw new InterruptedException();
96
+                }
97
+            });
98
+            $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
99
+                $output->writeln("Error while scanning, storage not available (" . $e->getMessage() . ")");
100
+            });
101
+            # count only
102
+        } else {
103
+            $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function () use ($output) {
104
+                $this->filesCounter += 1;
105
+                if ($this->hasBeenInterrupted()) {
106
+                    throw new InterruptedException();
107
+                }
108
+            });
109
+            $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function () use ($output) {
110
+                $this->foldersCounter += 1;
111
+                if ($this->hasBeenInterrupted()) {
112
+                    throw new InterruptedException();
113
+                }
114
+            });
115
+        }
116
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function($path) use ($output) {
117
+            $this->checkScanWarning($path, $output);
118
+        });
119
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function($path) use ($output) {
120
+            $this->checkScanWarning($path, $output);
121
+        });
122
+
123
+        try {
124
+            $scanner->scan($appData->getPath());
125
+        } catch (ForbiddenException $e) {
126
+            $output->writeln("<error>Storage not writable</error>");
127
+            $output->writeln("Make sure you're running the scan command only as the user the web server runs as");
128
+        } catch (InterruptedException $e) {
129
+            # exit the function if ctrl-c has been pressed
130
+            $output->writeln('Interrupted by user');
131
+        } catch (NotFoundException $e) {
132
+            $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
133
+        } catch (\Exception $e) {
134
+            $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
135
+            $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
136
+        }
137
+    }
138
+
139
+
140
+    protected function execute(InputInterface $input, OutputInterface $output) {
141
+        # no messaging level option means: no full printout but statistics
142
+        # $quiet   means no print at all
143
+        # $verbose means full printout including statistics
144
+        # -q	-v	full	stat
145
+        #  0	 0	no	yes
146
+        #  0	 1	yes	yes
147
+        #  1	--	no	no  (quiet overrules verbose)
148
+        $verbose = $input->getOption('verbose');
149
+        $quiet = $input->getOption('quiet');
150
+        # restrict the verbosity level to VERBOSITY_VERBOSE
151
+        if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
152
+            $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
153
+        }
154
+        if ($quiet) {
155
+            $verbose = false;
156
+        }
157
+
158
+        $output->writeln("\nScanning AppData for files");
159
+
160
+        $this->initTools();
161
+
162
+        $this->scanFiles($verbose, $output);
163
+
164
+        # stat: printout statistics if $quiet was not set
165
+        if (!$quiet) {
166
+            $this->presentStats($output);
167
+        }
168
+    }
169
+
170
+    /**
171
+     * Initialises some useful tools for the Command
172
+     */
173
+    protected function initTools() {
174
+        // Start the timer
175
+        $this->execTime = -microtime(true);
176
+        // Convert PHP errors to exceptions
177
+        set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
178
+    }
179
+
180
+    /**
181
+     * Processes PHP errors as exceptions in order to be able to keep track of problems
182
+     *
183
+     * @see https://secure.php.net/manual/en/function.set-error-handler.php
184
+     *
185
+     * @param int $severity the level of the error raised
186
+     * @param string $message
187
+     * @param string $file the filename that the error was raised in
188
+     * @param int $line the line number the error was raised
189
+     *
190
+     * @throws \ErrorException
191
+     */
192
+    public function exceptionErrorHandler($severity, $message, $file, $line) {
193
+        if (!(error_reporting() & $severity)) {
194
+            // This error code is not included in error_reporting
195
+            return;
196
+        }
197
+        throw new \ErrorException($message, 0, $severity, $file, $line);
198
+    }
199
+
200
+    /**
201
+     * @param OutputInterface $output
202
+     */
203
+    protected function presentStats(OutputInterface $output) {
204
+        // Stop the timer
205
+        $this->execTime += microtime(true);
206
+        $output->writeln("");
207
+
208
+        $headers = [
209
+            'Folders', 'Files', 'Elapsed time'
210
+        ];
211
+
212
+        $this->showSummary($headers, null, $output);
213
+    }
214
+
215
+    /**
216
+     * Shows a summary of operations
217
+     *
218
+     * @param string[] $headers
219
+     * @param string[] $rows
220
+     * @param OutputInterface $output
221
+     */
222
+    protected function showSummary($headers, $rows, OutputInterface $output) {
223
+        $niceDate = $this->formatExecTime();
224
+        if (!$rows) {
225
+            $rows = [
226
+                $this->foldersCounter,
227
+                $this->filesCounter,
228
+                $niceDate,
229
+            ];
230
+        }
231
+        $table = new Table($output);
232
+        $table
233
+            ->setHeaders($headers)
234
+            ->setRows([$rows]);
235
+        $table->render();
236
+    }
237
+
238
+
239
+    /**
240
+     * Formats microtime into a human readable format
241
+     *
242
+     * @return string
243
+     */
244
+    protected function formatExecTime() {
245
+        list($secs, $tens) = explode('.', sprintf("%.1f", ($this->execTime)));
246
+
247
+        # if you want to have microseconds add this:   . '.' . $tens;
248
+        return date('H:i:s', $secs);
249
+    }
250
+
251
+    /**
252
+     * @return \OCP\IDBConnection
253
+     */
254
+    protected function reconnectToDatabase(OutputInterface $output) {
255
+        /** @var Connection | IDBConnection $connection*/
256
+        $connection = \OC::$server->getDatabaseConnection();
257
+        try {
258
+            $connection->close();
259
+        } catch (\Exception $ex) {
260
+            $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
261
+        }
262
+        while (!$connection->isConnected()) {
263
+            try {
264
+                $connection->connect();
265
+            } catch (\Exception $ex) {
266
+                $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
267
+                sleep(60);
268
+            }
269
+        }
270
+        return $connection;
271
+    }
272
+
273
+    /**
274
+     * @return \OCP\Files\Folder
275
+     * @throws NotFoundException
276
+     */
277
+    private function getAppDataFolder() {
278
+        $instanceId = $this->config->getSystemValue('instanceid', null);
279
+
280
+        if ($instanceId === null) {
281
+            throw new NotFoundException();
282
+        }
283
+
284
+        return $this->root->get('appdata_'.$instanceId);
285
+    }
286 286
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
 		$path = basename($fullPath);
65 65
 
66 66
 		if ($normalizedPath !== $path) {
67
-			$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
67
+			$output->writeln("\t<error>Entry \"".$fullPath.'" will not be accessible due to incompatible encoding</error>');
68 68
 		}
69 69
 	}
70 70
 
@@ -81,32 +81,32 @@  discard block
 block discarded – undo
81 81
 		# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
82 82
 		# printout and count
83 83
 		if ($verbose) {
84
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
84
+			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function($path) use ($output) {
85 85
 				$output->writeln("\tFile   <info>$path</info>");
86 86
 				$this->filesCounter += 1;
87 87
 				if ($this->hasBeenInterrupted()) {
88 88
 					throw new InterruptedException();
89 89
 				}
90 90
 			});
91
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
91
+			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function($path) use ($output) {
92 92
 				$output->writeln("\tFolder <info>$path</info>");
93 93
 				$this->foldersCounter += 1;
94 94
 				if ($this->hasBeenInterrupted()) {
95 95
 					throw new InterruptedException();
96 96
 				}
97 97
 			});
98
-			$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
99
-				$output->writeln("Error while scanning, storage not available (" . $e->getMessage() . ")");
98
+			$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function(StorageNotAvailableException $e) use ($output) {
99
+				$output->writeln("Error while scanning, storage not available (".$e->getMessage().")");
100 100
 			});
101 101
 			# count only
102 102
 		} else {
103
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function () use ($output) {
103
+			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function() use ($output) {
104 104
 				$this->filesCounter += 1;
105 105
 				if ($this->hasBeenInterrupted()) {
106 106
 					throw new InterruptedException();
107 107
 				}
108 108
 			});
109
-			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function () use ($output) {
109
+			$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function() use ($output) {
110 110
 				$this->foldersCounter += 1;
111 111
 				if ($this->hasBeenInterrupted()) {
112 112
 					throw new InterruptedException();
@@ -129,10 +129,10 @@  discard block
 block discarded – undo
129 129
 			# exit the function if ctrl-c has been pressed
130 130
 			$output->writeln('Interrupted by user');
131 131
 		} catch (NotFoundException $e) {
132
-			$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
132
+			$output->writeln('<error>Path not found: '.$e->getMessage().'</error>');
133 133
 		} catch (\Exception $e) {
134
-			$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
135
-			$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
134
+			$output->writeln('<error>Exception during scan: '.$e->getMessage().'</error>');
135
+			$output->writeln('<error>'.$e->getTraceAsString().'</error>');
136 136
 		}
137 137
 	}
138 138
 
Please login to merge, or discard this patch.
lib/private/Files/Utils/Scanner.php 1 patch
Indentation   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -47,200 +47,200 @@
 block discarded – undo
47 47
  * @package OC\Files\Utils
48 48
  */
49 49
 class Scanner extends PublicEmitter {
50
-	/**
51
-	 * @var string $user
52
-	 */
53
-	private $user;
54
-
55
-	/**
56
-	 * @var \OCP\IDBConnection
57
-	 */
58
-	protected $db;
59
-
60
-	/**
61
-	 * @var ILogger
62
-	 */
63
-	protected $logger;
64
-
65
-	/**
66
-	 * @param string $user
67
-	 * @param \OCP\IDBConnection $db
68
-	 * @param ILogger $logger
69
-	 */
70
-	public function __construct($user, $db, ILogger $logger) {
71
-		$this->logger = $logger;
72
-		$this->user = $user;
73
-		$this->db = $db;
74
-	}
75
-
76
-	/**
77
-	 * get all storages for $dir
78
-	 *
79
-	 * @param string $dir
80
-	 * @return \OC\Files\Mount\MountPoint[]
81
-	 */
82
-	protected function getMounts($dir) {
83
-		//TODO: move to the node based fileapi once that's done
84
-		\OC_Util::tearDownFS();
85
-		\OC_Util::setupFS($this->user);
86
-
87
-		$mountManager = Filesystem::getMountManager();
88
-		$mounts = $mountManager->findIn($dir);
89
-		$mounts[] = $mountManager->find($dir);
90
-		$mounts = array_reverse($mounts); //start with the mount of $dir
91
-
92
-		return $mounts;
93
-	}
94
-
95
-	/**
96
-	 * attach listeners to the scanner
97
-	 *
98
-	 * @param \OC\Files\Mount\MountPoint $mount
99
-	 */
100
-	protected function attachListener($mount) {
101
-		$scanner = $mount->getStorage()->getScanner();
102
-		$emitter = $this;
103
-		$scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount, $emitter) {
104
-			$emitter->emit('\OC\Files\Utils\Scanner', 'scanFile', array($mount->getMountPoint() . $path));
105
-		});
106
-		$scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount, $emitter) {
107
-			$emitter->emit('\OC\Files\Utils\Scanner', 'scanFolder', array($mount->getMountPoint() . $path));
108
-		});
109
-		$scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount, $emitter) {
110
-			$emitter->emit('\OC\Files\Utils\Scanner', 'postScanFile', array($mount->getMountPoint() . $path));
111
-		});
112
-		$scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount, $emitter) {
113
-			$emitter->emit('\OC\Files\Utils\Scanner', 'postScanFolder', array($mount->getMountPoint() . $path));
114
-		});
115
-	}
116
-
117
-	/**
118
-	 * @param string $dir
119
-	 */
120
-	public function backgroundScan($dir) {
121
-		$mounts = $this->getMounts($dir);
122
-		foreach ($mounts as $mount) {
123
-			$storage = $mount->getStorage();
124
-			if (is_null($storage)) {
125
-				continue;
126
-			}
127
-
128
-			// don't bother scanning failed storages (shortcut for same result)
129
-			if ($storage->instanceOfStorage('OC\Files\Storage\FailedStorage')) {
130
-				continue;
131
-			}
132
-
133
-			// don't scan the root storage
134
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Local') && $mount->getMountPoint() === '/') {
135
-				continue;
136
-			}
137
-
138
-			// don't scan received local shares, these can be scanned when scanning the owner's storage
139
-			if ($storage->instanceOfStorage(SharedStorage::class)) {
140
-				continue;
141
-			}
142
-			$scanner = $storage->getScanner();
143
-			$this->attachListener($mount);
144
-
145
-			$scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
146
-				$this->triggerPropagator($storage, $path);
147
-			});
148
-			$scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
149
-				$this->triggerPropagator($storage, $path);
150
-			});
151
-			$scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
152
-				$this->triggerPropagator($storage, $path);
153
-			});
154
-
155
-			$propagator = $storage->getPropagator();
156
-			$propagator->beginBatch();
157
-			$scanner->backgroundScan();
158
-			$propagator->commitBatch();
159
-		}
160
-	}
161
-
162
-	/**
163
-	 * @param string $dir
164
-	 * @throws \OC\ForbiddenException
165
-	 * @throws \OCP\Files\NotFoundException
166
-	 */
167
-	public function scan($dir = '') {
168
-		if (!Filesystem::isValidPath($dir)) {
169
-			throw new \InvalidArgumentException('Invalid path to scan');
170
-		}
171
-		$mounts = $this->getMounts($dir);
172
-		foreach ($mounts as $mount) {
173
-			$storage = $mount->getStorage();
174
-			if (is_null($storage)) {
175
-				continue;
176
-			}
177
-
178
-			// don't bother scanning failed storages (shortcut for same result)
179
-			if ($storage->instanceOfStorage('OC\Files\Storage\FailedStorage')) {
180
-				continue;
181
-			}
182
-
183
-			// if the home storage isn't writable then the scanner is run as the wrong user
184
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home') and
185
-				(!$storage->isCreatable('') or !$storage->isCreatable('files'))
186
-			) {
187
-				if ($storage->file_exists('') or $storage->getCache()->inCache('')) {
188
-					throw new ForbiddenException();
189
-				} else {// if the root exists in neither the cache nor the storage the user isn't setup yet
190
-					break;
191
-				}
192
-
193
-			}
194
-
195
-			// don't scan received local shares, these can be scanned when scanning the owner's storage
196
-			if ($storage->instanceOfStorage(SharedStorage::class)) {
197
-				continue;
198
-			}
199
-			$relativePath = $mount->getInternalPath($dir);
200
-			$scanner = $storage->getScanner();
201
-			$scanner->setUseTransactions(false);
202
-			$this->attachListener($mount);
203
-			$isDbLocking = \OC::$server->getLockingProvider() instanceof DBLockingProvider;
204
-
205
-			$scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
206
-				$this->triggerPropagator($storage, $path);
207
-			});
208
-			$scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
209
-				$this->triggerPropagator($storage, $path);
210
-			});
211
-			$scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
212
-				$this->triggerPropagator($storage, $path);
213
-			});
214
-
215
-			if (!$isDbLocking) {
216
-				$this->db->beginTransaction();
217
-			}
218
-			try {
219
-				$propagator = $storage->getPropagator();
220
-				$propagator->beginBatch();
221
-				if (!$storage->file_exists($relativePath)) {
222
-					throw new NotFoundException($dir);
223
-				}
224
-				$scanner->scan($relativePath, \OC\Files\Cache\Scanner::SCAN_RECURSIVE, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
225
-				$cache = $storage->getCache();
226
-				if ($cache instanceof Cache) {
227
-					// only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
228
-					$cache->correctFolderSize($relativePath);
229
-				}
230
-				$propagator->commitBatch();
231
-			} catch (StorageNotAvailableException $e) {
232
-				$this->logger->error('Storage ' . $storage->getId() . ' not available');
233
-				$this->logger->logException($e);
234
-				$this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]);
235
-			}
236
-			if (!$isDbLocking) {
237
-				$this->db->commit();
238
-			}
239
-		}
240
-	}
241
-
242
-	private function triggerPropagator(IStorage $storage, $internalPath) {
243
-		$storage->getPropagator()->propagateChange($internalPath, time());
244
-	}
50
+    /**
51
+     * @var string $user
52
+     */
53
+    private $user;
54
+
55
+    /**
56
+     * @var \OCP\IDBConnection
57
+     */
58
+    protected $db;
59
+
60
+    /**
61
+     * @var ILogger
62
+     */
63
+    protected $logger;
64
+
65
+    /**
66
+     * @param string $user
67
+     * @param \OCP\IDBConnection $db
68
+     * @param ILogger $logger
69
+     */
70
+    public function __construct($user, $db, ILogger $logger) {
71
+        $this->logger = $logger;
72
+        $this->user = $user;
73
+        $this->db = $db;
74
+    }
75
+
76
+    /**
77
+     * get all storages for $dir
78
+     *
79
+     * @param string $dir
80
+     * @return \OC\Files\Mount\MountPoint[]
81
+     */
82
+    protected function getMounts($dir) {
83
+        //TODO: move to the node based fileapi once that's done
84
+        \OC_Util::tearDownFS();
85
+        \OC_Util::setupFS($this->user);
86
+
87
+        $mountManager = Filesystem::getMountManager();
88
+        $mounts = $mountManager->findIn($dir);
89
+        $mounts[] = $mountManager->find($dir);
90
+        $mounts = array_reverse($mounts); //start with the mount of $dir
91
+
92
+        return $mounts;
93
+    }
94
+
95
+    /**
96
+     * attach listeners to the scanner
97
+     *
98
+     * @param \OC\Files\Mount\MountPoint $mount
99
+     */
100
+    protected function attachListener($mount) {
101
+        $scanner = $mount->getStorage()->getScanner();
102
+        $emitter = $this;
103
+        $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount, $emitter) {
104
+            $emitter->emit('\OC\Files\Utils\Scanner', 'scanFile', array($mount->getMountPoint() . $path));
105
+        });
106
+        $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount, $emitter) {
107
+            $emitter->emit('\OC\Files\Utils\Scanner', 'scanFolder', array($mount->getMountPoint() . $path));
108
+        });
109
+        $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount, $emitter) {
110
+            $emitter->emit('\OC\Files\Utils\Scanner', 'postScanFile', array($mount->getMountPoint() . $path));
111
+        });
112
+        $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount, $emitter) {
113
+            $emitter->emit('\OC\Files\Utils\Scanner', 'postScanFolder', array($mount->getMountPoint() . $path));
114
+        });
115
+    }
116
+
117
+    /**
118
+     * @param string $dir
119
+     */
120
+    public function backgroundScan($dir) {
121
+        $mounts = $this->getMounts($dir);
122
+        foreach ($mounts as $mount) {
123
+            $storage = $mount->getStorage();
124
+            if (is_null($storage)) {
125
+                continue;
126
+            }
127
+
128
+            // don't bother scanning failed storages (shortcut for same result)
129
+            if ($storage->instanceOfStorage('OC\Files\Storage\FailedStorage')) {
130
+                continue;
131
+            }
132
+
133
+            // don't scan the root storage
134
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Local') && $mount->getMountPoint() === '/') {
135
+                continue;
136
+            }
137
+
138
+            // don't scan received local shares, these can be scanned when scanning the owner's storage
139
+            if ($storage->instanceOfStorage(SharedStorage::class)) {
140
+                continue;
141
+            }
142
+            $scanner = $storage->getScanner();
143
+            $this->attachListener($mount);
144
+
145
+            $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
146
+                $this->triggerPropagator($storage, $path);
147
+            });
148
+            $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
149
+                $this->triggerPropagator($storage, $path);
150
+            });
151
+            $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
152
+                $this->triggerPropagator($storage, $path);
153
+            });
154
+
155
+            $propagator = $storage->getPropagator();
156
+            $propagator->beginBatch();
157
+            $scanner->backgroundScan();
158
+            $propagator->commitBatch();
159
+        }
160
+    }
161
+
162
+    /**
163
+     * @param string $dir
164
+     * @throws \OC\ForbiddenException
165
+     * @throws \OCP\Files\NotFoundException
166
+     */
167
+    public function scan($dir = '') {
168
+        if (!Filesystem::isValidPath($dir)) {
169
+            throw new \InvalidArgumentException('Invalid path to scan');
170
+        }
171
+        $mounts = $this->getMounts($dir);
172
+        foreach ($mounts as $mount) {
173
+            $storage = $mount->getStorage();
174
+            if (is_null($storage)) {
175
+                continue;
176
+            }
177
+
178
+            // don't bother scanning failed storages (shortcut for same result)
179
+            if ($storage->instanceOfStorage('OC\Files\Storage\FailedStorage')) {
180
+                continue;
181
+            }
182
+
183
+            // if the home storage isn't writable then the scanner is run as the wrong user
184
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home') and
185
+                (!$storage->isCreatable('') or !$storage->isCreatable('files'))
186
+            ) {
187
+                if ($storage->file_exists('') or $storage->getCache()->inCache('')) {
188
+                    throw new ForbiddenException();
189
+                } else {// if the root exists in neither the cache nor the storage the user isn't setup yet
190
+                    break;
191
+                }
192
+
193
+            }
194
+
195
+            // don't scan received local shares, these can be scanned when scanning the owner's storage
196
+            if ($storage->instanceOfStorage(SharedStorage::class)) {
197
+                continue;
198
+            }
199
+            $relativePath = $mount->getInternalPath($dir);
200
+            $scanner = $storage->getScanner();
201
+            $scanner->setUseTransactions(false);
202
+            $this->attachListener($mount);
203
+            $isDbLocking = \OC::$server->getLockingProvider() instanceof DBLockingProvider;
204
+
205
+            $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
206
+                $this->triggerPropagator($storage, $path);
207
+            });
208
+            $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
209
+                $this->triggerPropagator($storage, $path);
210
+            });
211
+            $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
212
+                $this->triggerPropagator($storage, $path);
213
+            });
214
+
215
+            if (!$isDbLocking) {
216
+                $this->db->beginTransaction();
217
+            }
218
+            try {
219
+                $propagator = $storage->getPropagator();
220
+                $propagator->beginBatch();
221
+                if (!$storage->file_exists($relativePath)) {
222
+                    throw new NotFoundException($dir);
223
+                }
224
+                $scanner->scan($relativePath, \OC\Files\Cache\Scanner::SCAN_RECURSIVE, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
225
+                $cache = $storage->getCache();
226
+                if ($cache instanceof Cache) {
227
+                    // only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
228
+                    $cache->correctFolderSize($relativePath);
229
+                }
230
+                $propagator->commitBatch();
231
+            } catch (StorageNotAvailableException $e) {
232
+                $this->logger->error('Storage ' . $storage->getId() . ' not available');
233
+                $this->logger->logException($e);
234
+                $this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]);
235
+            }
236
+            if (!$isDbLocking) {
237
+                $this->db->commit();
238
+            }
239
+        }
240
+    }
241
+
242
+    private function triggerPropagator(IStorage $storage, $internalPath) {
243
+        $storage->getPropagator()->propagateChange($internalPath, time());
244
+    }
245 245
 }
246 246
 
Please login to merge, or discard this patch.