Passed
Push — master ( a88e7d...ccd89f )
by Daniel
17:07
created
apps/files/lib/Command/ScanAppData.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -38,223 +38,223 @@
 block discarded – undo
38 38
 
39 39
 class ScanAppData extends Base {
40 40
 
41
-	/** @var IRootFolder */
42
-	protected $root;
43
-	/** @var IConfig */
44
-	protected $config;
45
-	/** @var float */
46
-	protected $execTime = 0;
47
-	/** @var int */
48
-	protected $foldersCounter = 0;
49
-	/** @var int */
50
-	protected $filesCounter = 0;
51
-
52
-	public function __construct(IRootFolder $rootFolder, IConfig $config) {
53
-		parent::__construct();
54
-
55
-		$this->root = $rootFolder;
56
-		$this->config = $config;
57
-	}
58
-
59
-	protected function configure() {
60
-		parent::configure();
61
-
62
-		$this
63
-			->setName('files:scan-app-data')
64
-			->setDescription('rescan the AppData folder');
65
-	}
66
-
67
-	public function checkScanWarning($fullPath, OutputInterface $output) {
68
-		$normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
69
-		$path = basename($fullPath);
70
-
71
-		if ($normalizedPath !== $path) {
72
-			$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
73
-		}
74
-	}
75
-
76
-	protected function scanFiles(OutputInterface $output) {
77
-		try {
78
-			$appData = $this->getAppDataFolder();
79
-		} catch (NotFoundException $e) {
80
-			$output->writeln('NoAppData folder found');
81
-			return;
82
-		}
83
-
84
-		$connection = $this->reconnectToDatabase($output);
85
-		$scanner = new \OC\Files\Utils\Scanner(null, $connection, \OC::$server->getLogger());
86
-
87
-		# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
88
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
89
-			$output->writeln("\tFile   <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
90
-			++$this->filesCounter;
91
-			$this->abortIfInterrupted();
92
-		});
93
-
94
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
95
-			$output->writeln("\tFolder <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
96
-			++$this->foldersCounter;
97
-			$this->abortIfInterrupted();
98
-		});
99
-
100
-		$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
101
-			$output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
102
-		});
103
-
104
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
105
-			$this->checkScanWarning($path, $output);
106
-		});
107
-
108
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
109
-			$this->checkScanWarning($path, $output);
110
-		});
111
-
112
-		try {
113
-			$scanner->scan($appData->getPath());
114
-		} catch (ForbiddenException $e) {
115
-			$output->writeln('<error>Storage not writable</error>');
116
-			$output->writeln('Make sure you\'re running the scan command only as the user the web server runs as');
117
-		} catch (InterruptedException $e) {
118
-			# exit the function if ctrl-c has been pressed
119
-			$output->writeln('Interrupted by user');
120
-		} catch (NotFoundException $e) {
121
-			$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
122
-		} catch (\Exception $e) {
123
-			$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
124
-			$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
125
-		}
126
-	}
127
-
128
-
129
-	protected function execute(InputInterface $input, OutputInterface $output) {
130
-		# restrict the verbosity level to VERBOSITY_VERBOSE
131
-		if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
132
-			$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
133
-		}
134
-
135
-		$output->writeln("\nScanning AppData for files");
136
-
137
-		$this->initTools();
138
-
139
-		$this->scanFiles($output);
140
-
141
-		$this->presentStats($output);
142
-	}
143
-
144
-	/**
145
-	 * Initialises some useful tools for the Command
146
-	 */
147
-	protected function initTools() {
148
-		// Start the timer
149
-		$this->execTime = -microtime(true);
150
-		// Convert PHP errors to exceptions
151
-		set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
152
-	}
153
-
154
-	/**
155
-	 * Processes PHP errors as exceptions in order to be able to keep track of problems
156
-	 *
157
-	 * @see https://secure.php.net/manual/en/function.set-error-handler.php
158
-	 *
159
-	 * @param int $severity the level of the error raised
160
-	 * @param string $message
161
-	 * @param string $file the filename that the error was raised in
162
-	 * @param int $line the line number the error was raised
163
-	 *
164
-	 * @throws \ErrorException
165
-	 */
166
-	public function exceptionErrorHandler($severity, $message, $file, $line) {
167
-		if (!(error_reporting() & $severity)) {
168
-			// This error code is not included in error_reporting
169
-			return;
170
-		}
171
-		throw new \ErrorException($message, 0, $severity, $file, $line);
172
-	}
173
-
174
-	/**
175
-	 * @param OutputInterface $output
176
-	 */
177
-	protected function presentStats(OutputInterface $output) {
178
-		// Stop the timer
179
-		$this->execTime += microtime(true);
180
-		$output->writeln("");
181
-
182
-		$headers = [
183
-			'Folders', 'Files', 'Elapsed time'
184
-		];
185
-
186
-		$this->showSummary($headers, null, $output);
187
-	}
188
-
189
-	/**
190
-	 * Shows a summary of operations
191
-	 *
192
-	 * @param string[] $headers
193
-	 * @param string[] $rows
194
-	 * @param OutputInterface $output
195
-	 */
196
-	protected function showSummary($headers, $rows, OutputInterface $output) {
197
-		$niceDate = $this->formatExecTime();
198
-		if (!$rows) {
199
-			$rows = [
200
-				$this->foldersCounter,
201
-				$this->filesCounter,
202
-				$niceDate,
203
-			];
204
-		}
205
-		$table = new Table($output);
206
-		$table
207
-			->setHeaders($headers)
208
-			->setRows([$rows]);
209
-		$table->render();
210
-	}
211
-
212
-
213
-	/**
214
-	 * Formats microtime into a human readable format
215
-	 *
216
-	 * @return string
217
-	 */
218
-	protected function formatExecTime() {
219
-		list($secs, ) = explode('.', sprintf("%.1f", $this->execTime));
220
-
221
-		# if you want to have microseconds add this:   . '.' . $tens;
222
-		return date('H:i:s', $secs);
223
-	}
224
-
225
-	/**
226
-	 * @return \OCP\IDBConnection
227
-	 */
228
-	protected function reconnectToDatabase(OutputInterface $output) {
229
-		/** @var Connection | IDBConnection $connection*/
230
-		$connection = \OC::$server->getDatabaseConnection();
231
-		try {
232
-			$connection->close();
233
-		} catch (\Exception $ex) {
234
-			$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
235
-		}
236
-		while (!$connection->isConnected()) {
237
-			try {
238
-				$connection->connect();
239
-			} catch (\Exception $ex) {
240
-				$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
241
-				sleep(60);
242
-			}
243
-		}
244
-		return $connection;
245
-	}
246
-
247
-	/**
248
-	 * @return \OCP\Files\Folder
249
-	 * @throws NotFoundException
250
-	 */
251
-	private function getAppDataFolder() {
252
-		$instanceId = $this->config->getSystemValue('instanceid', null);
253
-
254
-		if ($instanceId === null) {
255
-			throw new NotFoundException();
256
-		}
257
-
258
-		return $this->root->get('appdata_'.$instanceId);
259
-	}
41
+    /** @var IRootFolder */
42
+    protected $root;
43
+    /** @var IConfig */
44
+    protected $config;
45
+    /** @var float */
46
+    protected $execTime = 0;
47
+    /** @var int */
48
+    protected $foldersCounter = 0;
49
+    /** @var int */
50
+    protected $filesCounter = 0;
51
+
52
+    public function __construct(IRootFolder $rootFolder, IConfig $config) {
53
+        parent::__construct();
54
+
55
+        $this->root = $rootFolder;
56
+        $this->config = $config;
57
+    }
58
+
59
+    protected function configure() {
60
+        parent::configure();
61
+
62
+        $this
63
+            ->setName('files:scan-app-data')
64
+            ->setDescription('rescan the AppData folder');
65
+    }
66
+
67
+    public function checkScanWarning($fullPath, OutputInterface $output) {
68
+        $normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
69
+        $path = basename($fullPath);
70
+
71
+        if ($normalizedPath !== $path) {
72
+            $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
73
+        }
74
+    }
75
+
76
+    protected function scanFiles(OutputInterface $output) {
77
+        try {
78
+            $appData = $this->getAppDataFolder();
79
+        } catch (NotFoundException $e) {
80
+            $output->writeln('NoAppData folder found');
81
+            return;
82
+        }
83
+
84
+        $connection = $this->reconnectToDatabase($output);
85
+        $scanner = new \OC\Files\Utils\Scanner(null, $connection, \OC::$server->getLogger());
86
+
87
+        # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
88
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
89
+            $output->writeln("\tFile   <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
90
+            ++$this->filesCounter;
91
+            $this->abortIfInterrupted();
92
+        });
93
+
94
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
95
+            $output->writeln("\tFolder <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
96
+            ++$this->foldersCounter;
97
+            $this->abortIfInterrupted();
98
+        });
99
+
100
+        $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
101
+            $output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
102
+        });
103
+
104
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
105
+            $this->checkScanWarning($path, $output);
106
+        });
107
+
108
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
109
+            $this->checkScanWarning($path, $output);
110
+        });
111
+
112
+        try {
113
+            $scanner->scan($appData->getPath());
114
+        } catch (ForbiddenException $e) {
115
+            $output->writeln('<error>Storage not writable</error>');
116
+            $output->writeln('Make sure you\'re running the scan command only as the user the web server runs as');
117
+        } catch (InterruptedException $e) {
118
+            # exit the function if ctrl-c has been pressed
119
+            $output->writeln('Interrupted by user');
120
+        } catch (NotFoundException $e) {
121
+            $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
122
+        } catch (\Exception $e) {
123
+            $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
124
+            $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
125
+        }
126
+    }
127
+
128
+
129
+    protected function execute(InputInterface $input, OutputInterface $output) {
130
+        # restrict the verbosity level to VERBOSITY_VERBOSE
131
+        if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
132
+            $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
133
+        }
134
+
135
+        $output->writeln("\nScanning AppData for files");
136
+
137
+        $this->initTools();
138
+
139
+        $this->scanFiles($output);
140
+
141
+        $this->presentStats($output);
142
+    }
143
+
144
+    /**
145
+     * Initialises some useful tools for the Command
146
+     */
147
+    protected function initTools() {
148
+        // Start the timer
149
+        $this->execTime = -microtime(true);
150
+        // Convert PHP errors to exceptions
151
+        set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
152
+    }
153
+
154
+    /**
155
+     * Processes PHP errors as exceptions in order to be able to keep track of problems
156
+     *
157
+     * @see https://secure.php.net/manual/en/function.set-error-handler.php
158
+     *
159
+     * @param int $severity the level of the error raised
160
+     * @param string $message
161
+     * @param string $file the filename that the error was raised in
162
+     * @param int $line the line number the error was raised
163
+     *
164
+     * @throws \ErrorException
165
+     */
166
+    public function exceptionErrorHandler($severity, $message, $file, $line) {
167
+        if (!(error_reporting() & $severity)) {
168
+            // This error code is not included in error_reporting
169
+            return;
170
+        }
171
+        throw new \ErrorException($message, 0, $severity, $file, $line);
172
+    }
173
+
174
+    /**
175
+     * @param OutputInterface $output
176
+     */
177
+    protected function presentStats(OutputInterface $output) {
178
+        // Stop the timer
179
+        $this->execTime += microtime(true);
180
+        $output->writeln("");
181
+
182
+        $headers = [
183
+            'Folders', 'Files', 'Elapsed time'
184
+        ];
185
+
186
+        $this->showSummary($headers, null, $output);
187
+    }
188
+
189
+    /**
190
+     * Shows a summary of operations
191
+     *
192
+     * @param string[] $headers
193
+     * @param string[] $rows
194
+     * @param OutputInterface $output
195
+     */
196
+    protected function showSummary($headers, $rows, OutputInterface $output) {
197
+        $niceDate = $this->formatExecTime();
198
+        if (!$rows) {
199
+            $rows = [
200
+                $this->foldersCounter,
201
+                $this->filesCounter,
202
+                $niceDate,
203
+            ];
204
+        }
205
+        $table = new Table($output);
206
+        $table
207
+            ->setHeaders($headers)
208
+            ->setRows([$rows]);
209
+        $table->render();
210
+    }
211
+
212
+
213
+    /**
214
+     * Formats microtime into a human readable format
215
+     *
216
+     * @return string
217
+     */
218
+    protected function formatExecTime() {
219
+        list($secs, ) = explode('.', sprintf("%.1f", $this->execTime));
220
+
221
+        # if you want to have microseconds add this:   . '.' . $tens;
222
+        return date('H:i:s', $secs);
223
+    }
224
+
225
+    /**
226
+     * @return \OCP\IDBConnection
227
+     */
228
+    protected function reconnectToDatabase(OutputInterface $output) {
229
+        /** @var Connection | IDBConnection $connection*/
230
+        $connection = \OC::$server->getDatabaseConnection();
231
+        try {
232
+            $connection->close();
233
+        } catch (\Exception $ex) {
234
+            $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
235
+        }
236
+        while (!$connection->isConnected()) {
237
+            try {
238
+                $connection->connect();
239
+            } catch (\Exception $ex) {
240
+                $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
241
+                sleep(60);
242
+            }
243
+        }
244
+        return $connection;
245
+    }
246
+
247
+    /**
248
+     * @return \OCP\Files\Folder
249
+     * @throws NotFoundException
250
+     */
251
+    private function getAppDataFolder() {
252
+        $instanceId = $this->config->getSystemValue('instanceid', null);
253
+
254
+        if ($instanceId === null) {
255
+            throw new NotFoundException();
256
+        }
257
+
258
+        return $this->root->get('appdata_'.$instanceId);
259
+    }
260 260
 }
Please login to merge, or discard this patch.