Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
lib/private/Files/Type/Detection.php 1 patch
Indentation   +334 added lines, -334 removed lines patch added patch discarded remove patch
@@ -51,338 +51,338 @@
 block discarded – undo
51 51
  */
52 52
 class Detection implements IMimeTypeDetector {
53 53
 
54
-	private const CUSTOM_MIMETYPEMAPPING = 'mimetypemapping.json';
55
-	private const CUSTOM_MIMETYPEALIASES = 'mimetypealiases.json';
56
-
57
-	protected $mimetypes = [];
58
-	protected $secureMimeTypes = [];
59
-
60
-	protected $mimetypeIcons = [];
61
-	/** @var string[] */
62
-	protected $mimeTypeAlias = [];
63
-
64
-	/** @var IURLGenerator */
65
-	private $urlGenerator;
66
-
67
-	/** @var ILogger */
68
-	private $logger;
69
-
70
-	/** @var string */
71
-	private $customConfigDir;
72
-
73
-	/** @var string */
74
-	private $defaultConfigDir;
75
-
76
-	/**
77
-	 * @param IURLGenerator $urlGenerator
78
-	 * @param ILogger $logger
79
-	 * @param string $customConfigDir
80
-	 * @param string $defaultConfigDir
81
-	 */
82
-	public function __construct(IURLGenerator $urlGenerator,
83
-								ILogger $logger,
84
-								string $customConfigDir,
85
-								string $defaultConfigDir) {
86
-		$this->urlGenerator = $urlGenerator;
87
-		$this->logger = $logger;
88
-		$this->customConfigDir = $customConfigDir;
89
-		$this->defaultConfigDir = $defaultConfigDir;
90
-	}
91
-
92
-	/**
93
-	 * Add an extension -> mimetype mapping
94
-	 *
95
-	 * $mimetype is the assumed correct mime type
96
-	 * The optional $secureMimeType is an alternative to send to send
97
-	 * to avoid potential XSS.
98
-	 *
99
-	 * @param string $extension
100
-	 * @param string $mimetype
101
-	 * @param string|null $secureMimeType
102
-	 */
103
-	public function registerType(string $extension,
104
-								 string $mimetype,
105
-								 ?string $secureMimeType = null): void {
106
-		$this->mimetypes[$extension] = [$mimetype, $secureMimeType];
107
-		$this->secureMimeTypes[$mimetype] = $secureMimeType ?: $mimetype;
108
-	}
109
-
110
-	/**
111
-	 * Add an array of extension -> mimetype mappings
112
-	 *
113
-	 * The mimetype value is in itself an array where the first index is
114
-	 * the assumed correct mimetype and the second is either a secure alternative
115
-	 * or null if the correct is considered secure.
116
-	 *
117
-	 * @param array $types
118
-	 */
119
-	public function registerTypeArray(array $types): void {
120
-		$this->mimetypes = array_merge($this->mimetypes, $types);
121
-
122
-		// Update the alternative mimetypes to avoid having to look them up each time.
123
-		foreach ($this->mimetypes as $mimeType) {
124
-			$this->secureMimeTypes[$mimeType[0]] = $mimeType[1] ?? $mimeType[0];
125
-		}
126
-	}
127
-
128
-	private function loadCustomDefinitions(string $fileName, array $definitions): array {
129
-		if (file_exists($this->customConfigDir . '/' . $fileName)) {
130
-			$custom = json_decode(file_get_contents($this->customConfigDir . '/' . $fileName), true);
131
-			if (json_last_error() === JSON_ERROR_NONE) {
132
-				$definitions = array_merge($definitions, $custom);
133
-			} else {
134
-				$this->logger->warning('Failed to parse ' . $fileName . ': ' . json_last_error_msg());
135
-			}
136
-		}
137
-		return $definitions;
138
-	}
139
-
140
-	/**
141
-	 * Add the mimetype aliases if they are not yet present
142
-	 */
143
-	private function loadAliases(): void {
144
-		if (!empty($this->mimeTypeAlias)) {
145
-			return;
146
-		}
147
-
148
-		$this->mimeTypeAlias = json_decode(file_get_contents($this->defaultConfigDir . '/mimetypealiases.dist.json'), true);
149
-		$this->mimeTypeAlias = $this->loadCustomDefinitions(self::CUSTOM_MIMETYPEALIASES, $this->mimeTypeAlias);
150
-	}
151
-
152
-	/**
153
-	 * @return string[]
154
-	 */
155
-	public function getAllAliases(): array {
156
-		$this->loadAliases();
157
-		return $this->mimeTypeAlias;
158
-	}
159
-
160
-	public function getOnlyDefaultAliases(): array {
161
-		$this->loadMappings();
162
-		$this->mimeTypeAlias = json_decode(file_get_contents($this->defaultConfigDir . '/mimetypealiases.dist.json'), true);
163
-		return $this->mimeTypeAlias;
164
-	}
165
-
166
-	/**
167
-	 * Add mimetype mappings if they are not yet present
168
-	 */
169
-	private function loadMappings(): void {
170
-		if (!empty($this->mimetypes)) {
171
-			return;
172
-		}
173
-
174
-		$mimetypeMapping = json_decode(file_get_contents($this->defaultConfigDir . '/mimetypemapping.dist.json'), true);
175
-		$mimetypeMapping = $this->loadCustomDefinitions(self::CUSTOM_MIMETYPEMAPPING, $mimetypeMapping);
176
-
177
-		$this->registerTypeArray($mimetypeMapping);
178
-	}
179
-
180
-	/**
181
-	 * @return array
182
-	 */
183
-	public function getAllMappings(): array {
184
-		$this->loadMappings();
185
-		return $this->mimetypes;
186
-	}
187
-
188
-	/**
189
-	 * detect mimetype only based on filename, content of file is not used
190
-	 *
191
-	 * @param string $path
192
-	 * @return string
193
-	 */
194
-	public function detectPath($path): string {
195
-		$this->loadMappings();
196
-
197
-		$fileName = basename($path);
198
-
199
-		// remove leading dot on hidden files with a file extension
200
-		$fileName = ltrim($fileName, '.');
201
-
202
-		// note: leading dot doesn't qualify as extension
203
-		if (strpos($fileName, '.') > 0) {
204
-
205
-			// remove versioning extension: name.v1508946057 and transfer extension: name.ocTransferId2057600214.part
206
-			$fileName = preg_replace('!((\.v\d+)|((\.ocTransferId\d+)?\.part))$!', '', $fileName);
207
-
208
-			//try to guess the type by the file extension
209
-			$extension = strrchr($fileName, '.');
210
-			if ($extension !== false) {
211
-				$extension = strtolower($extension);
212
-				$extension = substr($extension, 1); //remove leading .
213
-				return $this->mimetypes[$extension][0] ?? 'application/octet-stream';
214
-			}
215
-		}
216
-
217
-		return 'application/octet-stream';
218
-	}
219
-
220
-	/**
221
-	 * detect mimetype only based on the content of file
222
-	 * @param string $path
223
-	 * @return string
224
-	 * @since 18.0.0
225
-	 */
226
-	public function detectContent(string $path): string {
227
-		$this->loadMappings();
228
-
229
-		if (@is_dir($path)) {
230
-			// directories are easy
231
-			return 'httpd/unix-directory';
232
-		}
233
-
234
-		if (function_exists('finfo_open')
235
-			&& function_exists('finfo_file')
236
-			&& $finfo = finfo_open(FILEINFO_MIME)) {
237
-			$info = @finfo_file($finfo, $path);
238
-			finfo_close($finfo);
239
-			if ($info) {
240
-				$info = strtolower($info);
241
-				$mimeType = strpos($info, ';') !== false ? substr($info, 0, strpos($info, ';')) : $info;
242
-				$mimeType = $this->getSecureMimeType($mimeType);
243
-				if ($mimeType !== 'application/octet-stream') {
244
-					return $mimeType;
245
-				}
246
-			}
247
-		}
248
-
249
-		if (strpos($path, '://') !== false && strpos($path, 'file://') === 0) {
250
-			// Is the file wrapped in a stream?
251
-			return 'application/octet-stream';
252
-		}
253
-
254
-		if (function_exists('mime_content_type')) {
255
-			// use mime magic extension if available
256
-			$mimeType = mime_content_type($path);
257
-			if ($mimeType !== false) {
258
-				$mimeType = $this->getSecureMimeType($mimeType);
259
-				if ($mimeType !== 'application/octet-stream') {
260
-					return $mimeType;
261
-				}
262
-			}
263
-		}
264
-
265
-		if (\OC_Helper::canExecute('file')) {
266
-			// it looks like we have a 'file' command,
267
-			// lets see if it does have mime support
268
-			$path = escapeshellarg($path);
269
-			$fp = popen("test -f $path && file -b --mime-type $path", 'r');
270
-			$mimeType = fgets($fp);
271
-			pclose($fp);
272
-
273
-			if ($mimeType !== false) {
274
-				//trim the newline
275
-				$mimeType = trim($mimeType);
276
-				$mimeType = $this->getSecureMimeType($mimeType);
277
-				if ($mimeType !== 'application/octet-stream') {
278
-					return $mimeType;
279
-				}
280
-			}
281
-
282
-		}
283
-		return 'application/octet-stream';
284
-	}
285
-
286
-	/**
287
-	 * detect mimetype based on both filename and content
288
-	 *
289
-	 * @param string $path
290
-	 * @return string
291
-	 */
292
-	public function detect($path): string {
293
-		$mimeType = $this->detectPath($path);
294
-
295
-		if ($mimeType !== 'application/octet-stream') {
296
-			return $mimeType;
297
-		}
298
-
299
-		return $this->detectContent($path);
300
-	}
301
-
302
-	/**
303
-	 * detect mimetype based on the content of a string
304
-	 *
305
-	 * @param string $data
306
-	 * @return string
307
-	 */
308
-	public function detectString($data): string {
309
-		if (function_exists('finfo_open') && function_exists('finfo_file')) {
310
-			$finfo = finfo_open(FILEINFO_MIME);
311
-			$info = finfo_buffer($finfo, $data);
312
-			return strpos($info, ';') !== false ? substr($info, 0, strpos($info, ';')) : $info;
313
-		}
314
-
315
-		$tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
316
-		$fh = fopen($tmpFile, 'wb');
317
-		fwrite($fh, $data, 8024);
318
-		fclose($fh);
319
-		$mime = $this->detect($tmpFile);
320
-		unset($tmpFile);
321
-		return $mime;
322
-	}
323
-
324
-	/**
325
-	 * Get a secure mimetype that won't expose potential XSS.
326
-	 *
327
-	 * @param string $mimeType
328
-	 * @return string
329
-	 */
330
-	public function getSecureMimeType($mimeType): string {
331
-		$this->loadMappings();
332
-
333
-		return $this->secureMimeTypes[$mimeType] ?? 'application/octet-stream';
334
-	}
335
-
336
-	/**
337
-	 * Get path to the icon of a file type
338
-	 * @param string $mimetype the MIME type
339
-	 * @return string the url
340
-	 */
341
-	public function mimeTypeIcon($mimetype): string {
342
-		$this->loadAliases();
343
-
344
-		while (isset($this->mimeTypeAlias[$mimetype])) {
345
-			$mimetype = $this->mimeTypeAlias[$mimetype];
346
-		}
347
-		if (isset($this->mimetypeIcons[$mimetype])) {
348
-			return $this->mimetypeIcons[$mimetype];
349
-		}
350
-
351
-		// Replace slash and backslash with a minus
352
-		$icon = str_replace(['/', '\\'], '-', $mimetype);
353
-
354
-		// Is it a dir?
355
-		if ($mimetype === 'dir') {
356
-			$this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/folder.svg');
357
-			return $this->mimetypeIcons[$mimetype];
358
-		}
359
-		if ($mimetype === 'dir-shared') {
360
-			$this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/folder-shared.svg');
361
-			return $this->mimetypeIcons[$mimetype];
362
-		}
363
-		if ($mimetype === 'dir-external') {
364
-			$this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/folder-external.svg');
365
-			return $this->mimetypeIcons[$mimetype];
366
-		}
367
-
368
-		// Icon exists?
369
-		try {
370
-			$this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/' . $icon . '.svg');
371
-			return $this->mimetypeIcons[$mimetype];
372
-		} catch (\RuntimeException $e) {
373
-			// Specified image not found
374
-		}
375
-
376
-		// Try only the first part of the filetype
377
-		$mimePart = substr($icon, 0, strpos($icon, '-'));
378
-		try {
379
-			$this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/' . $mimePart . '.svg');
380
-			return $this->mimetypeIcons[$mimetype];
381
-		} catch (\RuntimeException $e) {
382
-			// Image for the first part of the mimetype not found
383
-		}
384
-
385
-		$this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/file.svg');
386
-		return $this->mimetypeIcons[$mimetype];
387
-	}
54
+    private const CUSTOM_MIMETYPEMAPPING = 'mimetypemapping.json';
55
+    private const CUSTOM_MIMETYPEALIASES = 'mimetypealiases.json';
56
+
57
+    protected $mimetypes = [];
58
+    protected $secureMimeTypes = [];
59
+
60
+    protected $mimetypeIcons = [];
61
+    /** @var string[] */
62
+    protected $mimeTypeAlias = [];
63
+
64
+    /** @var IURLGenerator */
65
+    private $urlGenerator;
66
+
67
+    /** @var ILogger */
68
+    private $logger;
69
+
70
+    /** @var string */
71
+    private $customConfigDir;
72
+
73
+    /** @var string */
74
+    private $defaultConfigDir;
75
+
76
+    /**
77
+     * @param IURLGenerator $urlGenerator
78
+     * @param ILogger $logger
79
+     * @param string $customConfigDir
80
+     * @param string $defaultConfigDir
81
+     */
82
+    public function __construct(IURLGenerator $urlGenerator,
83
+                                ILogger $logger,
84
+                                string $customConfigDir,
85
+                                string $defaultConfigDir) {
86
+        $this->urlGenerator = $urlGenerator;
87
+        $this->logger = $logger;
88
+        $this->customConfigDir = $customConfigDir;
89
+        $this->defaultConfigDir = $defaultConfigDir;
90
+    }
91
+
92
+    /**
93
+     * Add an extension -> mimetype mapping
94
+     *
95
+     * $mimetype is the assumed correct mime type
96
+     * The optional $secureMimeType is an alternative to send to send
97
+     * to avoid potential XSS.
98
+     *
99
+     * @param string $extension
100
+     * @param string $mimetype
101
+     * @param string|null $secureMimeType
102
+     */
103
+    public function registerType(string $extension,
104
+                                    string $mimetype,
105
+                                 ?string $secureMimeType = null): void {
106
+        $this->mimetypes[$extension] = [$mimetype, $secureMimeType];
107
+        $this->secureMimeTypes[$mimetype] = $secureMimeType ?: $mimetype;
108
+    }
109
+
110
+    /**
111
+     * Add an array of extension -> mimetype mappings
112
+     *
113
+     * The mimetype value is in itself an array where the first index is
114
+     * the assumed correct mimetype and the second is either a secure alternative
115
+     * or null if the correct is considered secure.
116
+     *
117
+     * @param array $types
118
+     */
119
+    public function registerTypeArray(array $types): void {
120
+        $this->mimetypes = array_merge($this->mimetypes, $types);
121
+
122
+        // Update the alternative mimetypes to avoid having to look them up each time.
123
+        foreach ($this->mimetypes as $mimeType) {
124
+            $this->secureMimeTypes[$mimeType[0]] = $mimeType[1] ?? $mimeType[0];
125
+        }
126
+    }
127
+
128
+    private function loadCustomDefinitions(string $fileName, array $definitions): array {
129
+        if (file_exists($this->customConfigDir . '/' . $fileName)) {
130
+            $custom = json_decode(file_get_contents($this->customConfigDir . '/' . $fileName), true);
131
+            if (json_last_error() === JSON_ERROR_NONE) {
132
+                $definitions = array_merge($definitions, $custom);
133
+            } else {
134
+                $this->logger->warning('Failed to parse ' . $fileName . ': ' . json_last_error_msg());
135
+            }
136
+        }
137
+        return $definitions;
138
+    }
139
+
140
+    /**
141
+     * Add the mimetype aliases if they are not yet present
142
+     */
143
+    private function loadAliases(): void {
144
+        if (!empty($this->mimeTypeAlias)) {
145
+            return;
146
+        }
147
+
148
+        $this->mimeTypeAlias = json_decode(file_get_contents($this->defaultConfigDir . '/mimetypealiases.dist.json'), true);
149
+        $this->mimeTypeAlias = $this->loadCustomDefinitions(self::CUSTOM_MIMETYPEALIASES, $this->mimeTypeAlias);
150
+    }
151
+
152
+    /**
153
+     * @return string[]
154
+     */
155
+    public function getAllAliases(): array {
156
+        $this->loadAliases();
157
+        return $this->mimeTypeAlias;
158
+    }
159
+
160
+    public function getOnlyDefaultAliases(): array {
161
+        $this->loadMappings();
162
+        $this->mimeTypeAlias = json_decode(file_get_contents($this->defaultConfigDir . '/mimetypealiases.dist.json'), true);
163
+        return $this->mimeTypeAlias;
164
+    }
165
+
166
+    /**
167
+     * Add mimetype mappings if they are not yet present
168
+     */
169
+    private function loadMappings(): void {
170
+        if (!empty($this->mimetypes)) {
171
+            return;
172
+        }
173
+
174
+        $mimetypeMapping = json_decode(file_get_contents($this->defaultConfigDir . '/mimetypemapping.dist.json'), true);
175
+        $mimetypeMapping = $this->loadCustomDefinitions(self::CUSTOM_MIMETYPEMAPPING, $mimetypeMapping);
176
+
177
+        $this->registerTypeArray($mimetypeMapping);
178
+    }
179
+
180
+    /**
181
+     * @return array
182
+     */
183
+    public function getAllMappings(): array {
184
+        $this->loadMappings();
185
+        return $this->mimetypes;
186
+    }
187
+
188
+    /**
189
+     * detect mimetype only based on filename, content of file is not used
190
+     *
191
+     * @param string $path
192
+     * @return string
193
+     */
194
+    public function detectPath($path): string {
195
+        $this->loadMappings();
196
+
197
+        $fileName = basename($path);
198
+
199
+        // remove leading dot on hidden files with a file extension
200
+        $fileName = ltrim($fileName, '.');
201
+
202
+        // note: leading dot doesn't qualify as extension
203
+        if (strpos($fileName, '.') > 0) {
204
+
205
+            // remove versioning extension: name.v1508946057 and transfer extension: name.ocTransferId2057600214.part
206
+            $fileName = preg_replace('!((\.v\d+)|((\.ocTransferId\d+)?\.part))$!', '', $fileName);
207
+
208
+            //try to guess the type by the file extension
209
+            $extension = strrchr($fileName, '.');
210
+            if ($extension !== false) {
211
+                $extension = strtolower($extension);
212
+                $extension = substr($extension, 1); //remove leading .
213
+                return $this->mimetypes[$extension][0] ?? 'application/octet-stream';
214
+            }
215
+        }
216
+
217
+        return 'application/octet-stream';
218
+    }
219
+
220
+    /**
221
+     * detect mimetype only based on the content of file
222
+     * @param string $path
223
+     * @return string
224
+     * @since 18.0.0
225
+     */
226
+    public function detectContent(string $path): string {
227
+        $this->loadMappings();
228
+
229
+        if (@is_dir($path)) {
230
+            // directories are easy
231
+            return 'httpd/unix-directory';
232
+        }
233
+
234
+        if (function_exists('finfo_open')
235
+            && function_exists('finfo_file')
236
+            && $finfo = finfo_open(FILEINFO_MIME)) {
237
+            $info = @finfo_file($finfo, $path);
238
+            finfo_close($finfo);
239
+            if ($info) {
240
+                $info = strtolower($info);
241
+                $mimeType = strpos($info, ';') !== false ? substr($info, 0, strpos($info, ';')) : $info;
242
+                $mimeType = $this->getSecureMimeType($mimeType);
243
+                if ($mimeType !== 'application/octet-stream') {
244
+                    return $mimeType;
245
+                }
246
+            }
247
+        }
248
+
249
+        if (strpos($path, '://') !== false && strpos($path, 'file://') === 0) {
250
+            // Is the file wrapped in a stream?
251
+            return 'application/octet-stream';
252
+        }
253
+
254
+        if (function_exists('mime_content_type')) {
255
+            // use mime magic extension if available
256
+            $mimeType = mime_content_type($path);
257
+            if ($mimeType !== false) {
258
+                $mimeType = $this->getSecureMimeType($mimeType);
259
+                if ($mimeType !== 'application/octet-stream') {
260
+                    return $mimeType;
261
+                }
262
+            }
263
+        }
264
+
265
+        if (\OC_Helper::canExecute('file')) {
266
+            // it looks like we have a 'file' command,
267
+            // lets see if it does have mime support
268
+            $path = escapeshellarg($path);
269
+            $fp = popen("test -f $path && file -b --mime-type $path", 'r');
270
+            $mimeType = fgets($fp);
271
+            pclose($fp);
272
+
273
+            if ($mimeType !== false) {
274
+                //trim the newline
275
+                $mimeType = trim($mimeType);
276
+                $mimeType = $this->getSecureMimeType($mimeType);
277
+                if ($mimeType !== 'application/octet-stream') {
278
+                    return $mimeType;
279
+                }
280
+            }
281
+
282
+        }
283
+        return 'application/octet-stream';
284
+    }
285
+
286
+    /**
287
+     * detect mimetype based on both filename and content
288
+     *
289
+     * @param string $path
290
+     * @return string
291
+     */
292
+    public function detect($path): string {
293
+        $mimeType = $this->detectPath($path);
294
+
295
+        if ($mimeType !== 'application/octet-stream') {
296
+            return $mimeType;
297
+        }
298
+
299
+        return $this->detectContent($path);
300
+    }
301
+
302
+    /**
303
+     * detect mimetype based on the content of a string
304
+     *
305
+     * @param string $data
306
+     * @return string
307
+     */
308
+    public function detectString($data): string {
309
+        if (function_exists('finfo_open') && function_exists('finfo_file')) {
310
+            $finfo = finfo_open(FILEINFO_MIME);
311
+            $info = finfo_buffer($finfo, $data);
312
+            return strpos($info, ';') !== false ? substr($info, 0, strpos($info, ';')) : $info;
313
+        }
314
+
315
+        $tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
316
+        $fh = fopen($tmpFile, 'wb');
317
+        fwrite($fh, $data, 8024);
318
+        fclose($fh);
319
+        $mime = $this->detect($tmpFile);
320
+        unset($tmpFile);
321
+        return $mime;
322
+    }
323
+
324
+    /**
325
+     * Get a secure mimetype that won't expose potential XSS.
326
+     *
327
+     * @param string $mimeType
328
+     * @return string
329
+     */
330
+    public function getSecureMimeType($mimeType): string {
331
+        $this->loadMappings();
332
+
333
+        return $this->secureMimeTypes[$mimeType] ?? 'application/octet-stream';
334
+    }
335
+
336
+    /**
337
+     * Get path to the icon of a file type
338
+     * @param string $mimetype the MIME type
339
+     * @return string the url
340
+     */
341
+    public function mimeTypeIcon($mimetype): string {
342
+        $this->loadAliases();
343
+
344
+        while (isset($this->mimeTypeAlias[$mimetype])) {
345
+            $mimetype = $this->mimeTypeAlias[$mimetype];
346
+        }
347
+        if (isset($this->mimetypeIcons[$mimetype])) {
348
+            return $this->mimetypeIcons[$mimetype];
349
+        }
350
+
351
+        // Replace slash and backslash with a minus
352
+        $icon = str_replace(['/', '\\'], '-', $mimetype);
353
+
354
+        // Is it a dir?
355
+        if ($mimetype === 'dir') {
356
+            $this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/folder.svg');
357
+            return $this->mimetypeIcons[$mimetype];
358
+        }
359
+        if ($mimetype === 'dir-shared') {
360
+            $this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/folder-shared.svg');
361
+            return $this->mimetypeIcons[$mimetype];
362
+        }
363
+        if ($mimetype === 'dir-external') {
364
+            $this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/folder-external.svg');
365
+            return $this->mimetypeIcons[$mimetype];
366
+        }
367
+
368
+        // Icon exists?
369
+        try {
370
+            $this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/' . $icon . '.svg');
371
+            return $this->mimetypeIcons[$mimetype];
372
+        } catch (\RuntimeException $e) {
373
+            // Specified image not found
374
+        }
375
+
376
+        // Try only the first part of the filetype
377
+        $mimePart = substr($icon, 0, strpos($icon, '-'));
378
+        try {
379
+            $this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/' . $mimePart . '.svg');
380
+            return $this->mimetypeIcons[$mimetype];
381
+        } catch (\RuntimeException $e) {
382
+            // Image for the first part of the mimetype not found
383
+        }
384
+
385
+        $this->mimetypeIcons[$mimetype] = $this->urlGenerator->imagePath('core', 'filetypes/file.svg');
386
+        return $this->mimetypeIcons[$mimetype];
387
+    }
388 388
 }
Please login to merge, or discard this patch.
lib/private/Files/Stream/Quota.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -33,71 +33,71 @@
 block discarded – undo
33 33
  * usage: resource \OC\Files\Stream\Quota::wrap($stream, $limit)
34 34
  */
35 35
 class Quota extends Wrapper {
36
-	/**
37
-	 * @var int $limit
38
-	 */
39
-	private $limit;
36
+    /**
37
+     * @var int $limit
38
+     */
39
+    private $limit;
40 40
 
41
-	/**
42
-	 * @param resource $stream
43
-	 * @param int $limit
44
-	 * @return resource
45
-	 */
46
-	static public function wrap($stream, $limit) {
47
-		$context = stream_context_create([
48
-			'quota' => [
49
-				'source' => $stream,
50
-				'limit' => $limit
51
-			]
52
-		]);
53
-		return Wrapper::wrapSource($stream, $context, 'quota', self::class);
54
-	}
41
+    /**
42
+     * @param resource $stream
43
+     * @param int $limit
44
+     * @return resource
45
+     */
46
+    static public function wrap($stream, $limit) {
47
+        $context = stream_context_create([
48
+            'quota' => [
49
+                'source' => $stream,
50
+                'limit' => $limit
51
+            ]
52
+        ]);
53
+        return Wrapper::wrapSource($stream, $context, 'quota', self::class);
54
+    }
55 55
 
56
-	public function stream_open($path, $mode, $options, &$opened_path) {
57
-		$context = $this->loadContext('quota');
58
-		$this->source = $context['source'];
59
-		$this->limit = $context['limit'];
56
+    public function stream_open($path, $mode, $options, &$opened_path) {
57
+        $context = $this->loadContext('quota');
58
+        $this->source = $context['source'];
59
+        $this->limit = $context['limit'];
60 60
 
61
-		return true;
62
-	}
61
+        return true;
62
+    }
63 63
 
64
-	public function dir_opendir($path, $options) {
65
-		return false;
66
-	}
64
+    public function dir_opendir($path, $options) {
65
+        return false;
66
+    }
67 67
 
68
-	public function stream_seek($offset, $whence = SEEK_SET) {
69
-		if ($whence === SEEK_END){
70
-			// go to the end to find out last position's offset
71
-			$oldOffset = $this->stream_tell();
72
-			if (fseek($this->source, 0, $whence) !== 0){
73
-				return false;
74
-			}
75
-			$whence = SEEK_SET;
76
-			$offset = $this->stream_tell() + $offset;
77
-			$this->limit += $oldOffset - $offset;
78
-		}
79
-		else if ($whence === SEEK_SET) {
80
-			$this->limit += $this->stream_tell() - $offset;
81
-		} else {
82
-			$this->limit -= $offset;
83
-		}
84
-		// this wrapper needs to return "true" for success.
85
-		// the fseek call itself returns 0 on succeess
86
-		return fseek($this->source, $offset, $whence) === 0;
87
-	}
68
+    public function stream_seek($offset, $whence = SEEK_SET) {
69
+        if ($whence === SEEK_END){
70
+            // go to the end to find out last position's offset
71
+            $oldOffset = $this->stream_tell();
72
+            if (fseek($this->source, 0, $whence) !== 0){
73
+                return false;
74
+            }
75
+            $whence = SEEK_SET;
76
+            $offset = $this->stream_tell() + $offset;
77
+            $this->limit += $oldOffset - $offset;
78
+        }
79
+        else if ($whence === SEEK_SET) {
80
+            $this->limit += $this->stream_tell() - $offset;
81
+        } else {
82
+            $this->limit -= $offset;
83
+        }
84
+        // this wrapper needs to return "true" for success.
85
+        // the fseek call itself returns 0 on succeess
86
+        return fseek($this->source, $offset, $whence) === 0;
87
+    }
88 88
 
89
-	public function stream_read($count) {
90
-		$this->limit -= $count;
91
-		return fread($this->source, $count);
92
-	}
89
+    public function stream_read($count) {
90
+        $this->limit -= $count;
91
+        return fread($this->source, $count);
92
+    }
93 93
 
94
-	public function stream_write($data) {
95
-		$size = strlen($data);
96
-		if ($size > $this->limit) {
97
-			$data = substr($data, 0, $this->limit);
98
-			$size = $this->limit;
99
-		}
100
-		$this->limit -= $size;
101
-		return fwrite($this->source, $data);
102
-	}
94
+    public function stream_write($data) {
95
+        $size = strlen($data);
96
+        if ($size > $this->limit) {
97
+            $data = substr($data, 0, $this->limit);
98
+            $size = $this->limit;
99
+        }
100
+        $this->limit -= $size;
101
+        return fwrite($this->source, $data);
102
+    }
103 103
 }
Please login to merge, or discard this patch.
lib/private/Files/Stream/Encryption.php 1 patch
Indentation   +507 added lines, -507 removed lines patch added patch discarded remove patch
@@ -36,513 +36,513 @@
 block discarded – undo
36 36
 
37 37
 class Encryption extends Wrapper {
38 38
 
39
-	/** @var \OC\Encryption\Util */
40
-	protected $util;
41
-
42
-	/** @var \OC\Encryption\File */
43
-	protected $file;
44
-
45
-	/** @var \OCP\Encryption\IEncryptionModule */
46
-	protected $encryptionModule;
47
-
48
-	/** @var \OC\Files\Storage\Storage */
49
-	protected $storage;
50
-
51
-	/** @var \OC\Files\Storage\Wrapper\Encryption */
52
-	protected $encryptionStorage;
53
-
54
-	/** @var string */
55
-	protected $internalPath;
56
-
57
-	/** @var string */
58
-	protected $cache;
59
-
60
-	/** @var integer */
61
-	protected $size;
62
-
63
-	/** @var integer */
64
-	protected $position;
65
-
66
-	/** @var integer */
67
-	protected $unencryptedSize;
68
-
69
-	/** @var integer */
70
-	protected $headerSize;
71
-
72
-	/** @var integer */
73
-	protected $unencryptedBlockSize;
74
-
75
-	/** @var array */
76
-	protected $header;
77
-
78
-	/** @var string */
79
-	protected $fullPath;
80
-
81
-	/** @var  bool */
82
-	protected $signed;
83
-
84
-	/**
85
-	 * header data returned by the encryption module, will be written to the file
86
-	 * in case of a write operation
87
-	 *
88
-	 * @var array
89
-	 */
90
-	protected $newHeader;
91
-
92
-	/**
93
-	 * user who perform the read/write operation null for public access
94
-	 *
95
-	 * @var string
96
-	 */
97
-	protected $uid;
98
-
99
-	/** @var bool */
100
-	protected $readOnly;
101
-
102
-	/** @var bool */
103
-	protected $writeFlag;
104
-
105
-	/** @var array */
106
-	protected $expectedContextProperties;
107
-
108
-	/** @var bool */
109
-	protected $fileUpdated;
110
-
111
-	public function __construct() {
112
-		$this->expectedContextProperties = [
113
-			'source',
114
-			'storage',
115
-			'internalPath',
116
-			'fullPath',
117
-			'encryptionModule',
118
-			'header',
119
-			'uid',
120
-			'file',
121
-			'util',
122
-			'size',
123
-			'unencryptedSize',
124
-			'encryptionStorage',
125
-			'headerSize',
126
-			'signed'
127
-		];
128
-	}
129
-
130
-
131
-	/**
132
-	 * Wraps a stream with the provided callbacks
133
-	 *
134
-	 * @param resource $source
135
-	 * @param string $internalPath relative to mount point
136
-	 * @param string $fullPath relative to data/
137
-	 * @param array $header
138
-	 * @param string $uid
139
-	 * @param \OCP\Encryption\IEncryptionModule $encryptionModule
140
-	 * @param \OC\Files\Storage\Storage $storage
141
-	 * @param \OC\Files\Storage\Wrapper\Encryption $encStorage
142
-	 * @param \OC\Encryption\Util $util
143
-	 * @param \OC\Encryption\File $file
144
-	 * @param string $mode
145
-	 * @param int $size
146
-	 * @param int $unencryptedSize
147
-	 * @param int $headerSize
148
-	 * @param bool $signed
149
-	 * @param string $wrapper stream wrapper class
150
-	 * @return resource
151
-	 *
152
-	 * @throws \BadMethodCallException
153
-	 */
154
-	public static function wrap($source, $internalPath, $fullPath, array $header,
155
-								$uid,
156
-								\OCP\Encryption\IEncryptionModule $encryptionModule,
157
-								\OC\Files\Storage\Storage $storage,
158
-								\OC\Files\Storage\Wrapper\Encryption $encStorage,
159
-								\OC\Encryption\Util $util,
160
-								 \OC\Encryption\File $file,
161
-								$mode,
162
-								$size,
163
-								$unencryptedSize,
164
-								$headerSize,
165
-								$signed,
166
-								$wrapper = Encryption::class) {
167
-
168
-		$context = stream_context_create([
169
-			'ocencryption' => [
170
-				'source' => $source,
171
-				'storage' => $storage,
172
-				'internalPath' => $internalPath,
173
-				'fullPath' => $fullPath,
174
-				'encryptionModule' => $encryptionModule,
175
-				'header' => $header,
176
-				'uid' => $uid,
177
-				'util' => $util,
178
-				'file' => $file,
179
-				'size' => $size,
180
-				'unencryptedSize' => $unencryptedSize,
181
-				'encryptionStorage' => $encStorage,
182
-				'headerSize' => $headerSize,
183
-				'signed' => $signed
184
-			]
185
-		]);
186
-
187
-		return self::wrapSource($source, $context, 'ocencryption', $wrapper, $mode);
188
-	}
189
-
190
-	/**
191
-	 * add stream wrapper
192
-	 *
193
-	 * @param resource $source
194
-	 * @param string $mode
195
-	 * @param resource $context
196
-	 * @param string $protocol
197
-	 * @param string $class
198
-	 * @return resource
199
-	 * @throws \BadMethodCallException
200
-	 */
201
-	protected static function wrapSource($source, $context, $protocol, $class, $mode = 'r+') {
202
-		try {
203
-			stream_wrapper_register($protocol, $class);
204
-			if (self::isDirectoryHandle($source)) {
205
-				$wrapped = opendir($protocol . '://', $context);
206
-			} else {
207
-				$wrapped = fopen($protocol . '://', $mode, false, $context);
208
-			}
209
-		} catch (\BadMethodCallException $e) {
210
-			stream_wrapper_unregister($protocol);
211
-			throw $e;
212
-		}
213
-		stream_wrapper_unregister($protocol);
214
-		return $wrapped;
215
-	}
216
-
217
-	/**
218
-	 * Load the source from the stream context and return the context options
219
-	 *
220
-	 * @param string $name
221
-	 * @return array
222
-	 * @throws \BadMethodCallException
223
-	 */
224
-	protected function loadContext($name) {
225
-		$context = parent::loadContext($name);
226
-
227
-		foreach ($this->expectedContextProperties as $property) {
228
-			if (array_key_exists($property, $context)) {
229
-				$this->{$property} = $context[$property];
230
-			} else {
231
-				throw new \BadMethodCallException('Invalid context, "' . $property . '" options not set');
232
-			}
233
-		}
234
-		return $context;
235
-
236
-	}
237
-
238
-	public function stream_open($path, $mode, $options, &$opened_path) {
239
-		$this->loadContext('ocencryption');
240
-
241
-		$this->position = 0;
242
-		$this->cache = '';
243
-		$this->writeFlag = false;
244
-		$this->fileUpdated = false;
245
-		$this->unencryptedBlockSize = $this->encryptionModule->getUnencryptedBlockSize($this->signed);
246
-
247
-		if (
248
-			$mode === 'w'
249
-			|| $mode === 'w+'
250
-			|| $mode === 'wb'
251
-			|| $mode === 'wb+'
252
-			|| $mode === 'r+'
253
-			|| $mode === 'rb+'
254
-		) {
255
-			$this->readOnly = false;
256
-		} else {
257
-			$this->readOnly = true;
258
-		}
259
-
260
-		$sharePath = $this->fullPath;
261
-		if (!$this->storage->file_exists($this->internalPath)) {
262
-			$sharePath = dirname($sharePath);
263
-		}
264
-
265
-		$accessList = [];
266
-		if ($this->encryptionModule->needDetailedAccessList()) {
267
-			$accessList = $this->file->getAccessList($sharePath);
268
-		}
269
-		$this->newHeader = $this->encryptionModule->begin($this->fullPath, $this->uid, $mode, $this->header, $accessList);
270
-
271
-		if (
272
-			$mode === 'w'
273
-			|| $mode === 'w+'
274
-			|| $mode === 'wb'
275
-			|| $mode === 'wb+'
276
-		) {
277
-			// We're writing a new file so start write counter with 0 bytes
278
-			$this->unencryptedSize = 0;
279
-			$this->writeHeader();
280
-			$this->headerSize = $this->util->getHeaderSize();
281
-			$this->size = $this->headerSize;
282
-		} else {
283
-			$this->skipHeader();
284
-		}
285
-
286
-		return true;
287
-
288
-	}
289
-
290
-	public function stream_eof() {
291
-		return $this->position >= $this->unencryptedSize;
292
-	}
293
-
294
-	public function stream_read($count) {
295
-
296
-		$result = '';
297
-
298
-		$count = min($count, $this->unencryptedSize - $this->position);
299
-		while ($count > 0) {
300
-			$remainingLength = $count;
301
-			// update the cache of the current block
302
-			$this->readCache();
303
-			// determine the relative position in the current block
304
-			$blockPosition = ($this->position % $this->unencryptedBlockSize);
305
-			// if entire read inside current block then only position needs to be updated
306
-			if ($remainingLength < ($this->unencryptedBlockSize - $blockPosition)) {
307
-				$result .= substr($this->cache, $blockPosition, $remainingLength);
308
-				$this->position += $remainingLength;
309
-				$count = 0;
310
-				// otherwise remainder of current block is fetched, the block is flushed and the position updated
311
-			} else {
312
-				$result .= substr($this->cache, $blockPosition);
313
-				$this->flush();
314
-				$this->position += ($this->unencryptedBlockSize - $blockPosition);
315
-				$count -= ($this->unencryptedBlockSize - $blockPosition);
316
-			}
317
-		}
318
-		return $result;
319
-
320
-	}
39
+    /** @var \OC\Encryption\Util */
40
+    protected $util;
41
+
42
+    /** @var \OC\Encryption\File */
43
+    protected $file;
44
+
45
+    /** @var \OCP\Encryption\IEncryptionModule */
46
+    protected $encryptionModule;
47
+
48
+    /** @var \OC\Files\Storage\Storage */
49
+    protected $storage;
50
+
51
+    /** @var \OC\Files\Storage\Wrapper\Encryption */
52
+    protected $encryptionStorage;
53
+
54
+    /** @var string */
55
+    protected $internalPath;
56
+
57
+    /** @var string */
58
+    protected $cache;
59
+
60
+    /** @var integer */
61
+    protected $size;
62
+
63
+    /** @var integer */
64
+    protected $position;
65
+
66
+    /** @var integer */
67
+    protected $unencryptedSize;
68
+
69
+    /** @var integer */
70
+    protected $headerSize;
71
+
72
+    /** @var integer */
73
+    protected $unencryptedBlockSize;
74
+
75
+    /** @var array */
76
+    protected $header;
77
+
78
+    /** @var string */
79
+    protected $fullPath;
80
+
81
+    /** @var  bool */
82
+    protected $signed;
83
+
84
+    /**
85
+     * header data returned by the encryption module, will be written to the file
86
+     * in case of a write operation
87
+     *
88
+     * @var array
89
+     */
90
+    protected $newHeader;
91
+
92
+    /**
93
+     * user who perform the read/write operation null for public access
94
+     *
95
+     * @var string
96
+     */
97
+    protected $uid;
98
+
99
+    /** @var bool */
100
+    protected $readOnly;
101
+
102
+    /** @var bool */
103
+    protected $writeFlag;
104
+
105
+    /** @var array */
106
+    protected $expectedContextProperties;
107
+
108
+    /** @var bool */
109
+    protected $fileUpdated;
110
+
111
+    public function __construct() {
112
+        $this->expectedContextProperties = [
113
+            'source',
114
+            'storage',
115
+            'internalPath',
116
+            'fullPath',
117
+            'encryptionModule',
118
+            'header',
119
+            'uid',
120
+            'file',
121
+            'util',
122
+            'size',
123
+            'unencryptedSize',
124
+            'encryptionStorage',
125
+            'headerSize',
126
+            'signed'
127
+        ];
128
+    }
129
+
130
+
131
+    /**
132
+     * Wraps a stream with the provided callbacks
133
+     *
134
+     * @param resource $source
135
+     * @param string $internalPath relative to mount point
136
+     * @param string $fullPath relative to data/
137
+     * @param array $header
138
+     * @param string $uid
139
+     * @param \OCP\Encryption\IEncryptionModule $encryptionModule
140
+     * @param \OC\Files\Storage\Storage $storage
141
+     * @param \OC\Files\Storage\Wrapper\Encryption $encStorage
142
+     * @param \OC\Encryption\Util $util
143
+     * @param \OC\Encryption\File $file
144
+     * @param string $mode
145
+     * @param int $size
146
+     * @param int $unencryptedSize
147
+     * @param int $headerSize
148
+     * @param bool $signed
149
+     * @param string $wrapper stream wrapper class
150
+     * @return resource
151
+     *
152
+     * @throws \BadMethodCallException
153
+     */
154
+    public static function wrap($source, $internalPath, $fullPath, array $header,
155
+                                $uid,
156
+                                \OCP\Encryption\IEncryptionModule $encryptionModule,
157
+                                \OC\Files\Storage\Storage $storage,
158
+                                \OC\Files\Storage\Wrapper\Encryption $encStorage,
159
+                                \OC\Encryption\Util $util,
160
+                                    \OC\Encryption\File $file,
161
+                                $mode,
162
+                                $size,
163
+                                $unencryptedSize,
164
+                                $headerSize,
165
+                                $signed,
166
+                                $wrapper = Encryption::class) {
167
+
168
+        $context = stream_context_create([
169
+            'ocencryption' => [
170
+                'source' => $source,
171
+                'storage' => $storage,
172
+                'internalPath' => $internalPath,
173
+                'fullPath' => $fullPath,
174
+                'encryptionModule' => $encryptionModule,
175
+                'header' => $header,
176
+                'uid' => $uid,
177
+                'util' => $util,
178
+                'file' => $file,
179
+                'size' => $size,
180
+                'unencryptedSize' => $unencryptedSize,
181
+                'encryptionStorage' => $encStorage,
182
+                'headerSize' => $headerSize,
183
+                'signed' => $signed
184
+            ]
185
+        ]);
186
+
187
+        return self::wrapSource($source, $context, 'ocencryption', $wrapper, $mode);
188
+    }
189
+
190
+    /**
191
+     * add stream wrapper
192
+     *
193
+     * @param resource $source
194
+     * @param string $mode
195
+     * @param resource $context
196
+     * @param string $protocol
197
+     * @param string $class
198
+     * @return resource
199
+     * @throws \BadMethodCallException
200
+     */
201
+    protected static function wrapSource($source, $context, $protocol, $class, $mode = 'r+') {
202
+        try {
203
+            stream_wrapper_register($protocol, $class);
204
+            if (self::isDirectoryHandle($source)) {
205
+                $wrapped = opendir($protocol . '://', $context);
206
+            } else {
207
+                $wrapped = fopen($protocol . '://', $mode, false, $context);
208
+            }
209
+        } catch (\BadMethodCallException $e) {
210
+            stream_wrapper_unregister($protocol);
211
+            throw $e;
212
+        }
213
+        stream_wrapper_unregister($protocol);
214
+        return $wrapped;
215
+    }
216
+
217
+    /**
218
+     * Load the source from the stream context and return the context options
219
+     *
220
+     * @param string $name
221
+     * @return array
222
+     * @throws \BadMethodCallException
223
+     */
224
+    protected function loadContext($name) {
225
+        $context = parent::loadContext($name);
226
+
227
+        foreach ($this->expectedContextProperties as $property) {
228
+            if (array_key_exists($property, $context)) {
229
+                $this->{$property} = $context[$property];
230
+            } else {
231
+                throw new \BadMethodCallException('Invalid context, "' . $property . '" options not set');
232
+            }
233
+        }
234
+        return $context;
235
+
236
+    }
237
+
238
+    public function stream_open($path, $mode, $options, &$opened_path) {
239
+        $this->loadContext('ocencryption');
240
+
241
+        $this->position = 0;
242
+        $this->cache = '';
243
+        $this->writeFlag = false;
244
+        $this->fileUpdated = false;
245
+        $this->unencryptedBlockSize = $this->encryptionModule->getUnencryptedBlockSize($this->signed);
246
+
247
+        if (
248
+            $mode === 'w'
249
+            || $mode === 'w+'
250
+            || $mode === 'wb'
251
+            || $mode === 'wb+'
252
+            || $mode === 'r+'
253
+            || $mode === 'rb+'
254
+        ) {
255
+            $this->readOnly = false;
256
+        } else {
257
+            $this->readOnly = true;
258
+        }
259
+
260
+        $sharePath = $this->fullPath;
261
+        if (!$this->storage->file_exists($this->internalPath)) {
262
+            $sharePath = dirname($sharePath);
263
+        }
264
+
265
+        $accessList = [];
266
+        if ($this->encryptionModule->needDetailedAccessList()) {
267
+            $accessList = $this->file->getAccessList($sharePath);
268
+        }
269
+        $this->newHeader = $this->encryptionModule->begin($this->fullPath, $this->uid, $mode, $this->header, $accessList);
270
+
271
+        if (
272
+            $mode === 'w'
273
+            || $mode === 'w+'
274
+            || $mode === 'wb'
275
+            || $mode === 'wb+'
276
+        ) {
277
+            // We're writing a new file so start write counter with 0 bytes
278
+            $this->unencryptedSize = 0;
279
+            $this->writeHeader();
280
+            $this->headerSize = $this->util->getHeaderSize();
281
+            $this->size = $this->headerSize;
282
+        } else {
283
+            $this->skipHeader();
284
+        }
285
+
286
+        return true;
287
+
288
+    }
289
+
290
+    public function stream_eof() {
291
+        return $this->position >= $this->unencryptedSize;
292
+    }
293
+
294
+    public function stream_read($count) {
295
+
296
+        $result = '';
297
+
298
+        $count = min($count, $this->unencryptedSize - $this->position);
299
+        while ($count > 0) {
300
+            $remainingLength = $count;
301
+            // update the cache of the current block
302
+            $this->readCache();
303
+            // determine the relative position in the current block
304
+            $blockPosition = ($this->position % $this->unencryptedBlockSize);
305
+            // if entire read inside current block then only position needs to be updated
306
+            if ($remainingLength < ($this->unencryptedBlockSize - $blockPosition)) {
307
+                $result .= substr($this->cache, $blockPosition, $remainingLength);
308
+                $this->position += $remainingLength;
309
+                $count = 0;
310
+                // otherwise remainder of current block is fetched, the block is flushed and the position updated
311
+            } else {
312
+                $result .= substr($this->cache, $blockPosition);
313
+                $this->flush();
314
+                $this->position += ($this->unencryptedBlockSize - $blockPosition);
315
+                $count -= ($this->unencryptedBlockSize - $blockPosition);
316
+            }
317
+        }
318
+        return $result;
319
+
320
+    }
321 321
 	
322
-	/**
323
-	 * stream_read_block
324
-	 *
325
-	 * This function is a wrapper for function stream_read.
326
-	 * It calls stream read until the requested $blockSize was received or no remaining data is present.
327
-	 * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
328
-	 * remote storage over the internet and it does not care about the given $blockSize.
329
-	 *
330
-	 * @param int $blockSize Length of requested data block in bytes
331
-	 * @return string Data fetched from stream.
332
-	 */
333
-	private function stream_read_block(int $blockSize): string {
334
-		$remaining = $blockSize;
335
-		$data = '';
336
-
337
-		do {
338
-			$chunk = parent::stream_read($remaining);
339
-			$chunk_len = strlen($chunk);
340
-			$data .= $chunk;
341
-			$remaining -= $chunk_len;
342
-		} while (($remaining > 0) && ($chunk_len > 0));
343
-
344
-		return $data;
345
-	}
346
-
347
-	public function stream_write($data) {
348
-		$length = 0;
349
-		// loop over $data to fit it in 6126 sized unencrypted blocks
350
-		while (isset($data[0])) {
351
-			$remainingLength = strlen($data);
352
-
353
-			// set the cache to the current 6126 block
354
-			$this->readCache();
355
-
356
-			// for seekable streams the pointer is moved back to the beginning of the encrypted block
357
-			// flush will start writing there when the position moves to another block
358
-			$positionInFile = (int)floor($this->position / $this->unencryptedBlockSize) *
359
-				$this->util->getBlockSize() + $this->headerSize;
360
-			$resultFseek = $this->parentStreamSeek($positionInFile);
361
-
362
-			// only allow writes on seekable streams, or at the end of the encrypted stream
363
-			if (!$this->readOnly && ($resultFseek || $positionInFile === $this->size)) {
364
-
365
-				// switch the writeFlag so flush() will write the block
366
-				$this->writeFlag = true;
367
-				$this->fileUpdated = true;
368
-
369
-				// determine the relative position in the current block
370
-				$blockPosition = ($this->position % $this->unencryptedBlockSize);
371
-				// check if $data fits in current block
372
-				// if so, overwrite existing data (if any)
373
-				// update position and liberate $data
374
-				if ($remainingLength < ($this->unencryptedBlockSize - $blockPosition)) {
375
-					$this->cache = substr($this->cache, 0, $blockPosition)
376
-						. $data . substr($this->cache, $blockPosition + $remainingLength);
377
-					$this->position += $remainingLength;
378
-					$length += $remainingLength;
379
-					$data = '';
380
-					// if $data doesn't fit the current block, the fill the current block and reiterate
381
-					// after the block is filled, it is flushed and $data is updatedxxx
382
-				} else {
383
-					$this->cache = substr($this->cache, 0, $blockPosition) .
384
-						substr($data, 0, $this->unencryptedBlockSize - $blockPosition);
385
-					$this->flush();
386
-					$this->position += ($this->unencryptedBlockSize - $blockPosition);
387
-					$length += ($this->unencryptedBlockSize - $blockPosition);
388
-					$data = substr($data, $this->unencryptedBlockSize - $blockPosition);
389
-				}
390
-			} else {
391
-				$data = '';
392
-			}
393
-			$this->unencryptedSize = max($this->unencryptedSize, $this->position);
394
-		}
395
-		return $length;
396
-	}
397
-
398
-	public function stream_tell() {
399
-		return $this->position;
400
-	}
401
-
402
-	public function stream_seek($offset, $whence = SEEK_SET) {
403
-
404
-		$return = false;
405
-
406
-		switch ($whence) {
407
-			case SEEK_SET:
408
-				$newPosition = $offset;
409
-				break;
410
-			case SEEK_CUR:
411
-				$newPosition = $this->position + $offset;
412
-				break;
413
-			case SEEK_END:
414
-				$newPosition = $this->unencryptedSize + $offset;
415
-				break;
416
-			default:
417
-				return $return;
418
-		}
419
-
420
-		if ($newPosition > $this->unencryptedSize || $newPosition < 0) {
421
-			return $return;
422
-		}
423
-
424
-		$newFilePosition = floor($newPosition / $this->unencryptedBlockSize)
425
-			* $this->util->getBlockSize() + $this->headerSize;
426
-
427
-		$oldFilePosition = parent::stream_tell();
428
-		if ($this->parentStreamSeek($newFilePosition)) {
429
-			$this->parentStreamSeek($oldFilePosition);
430
-			$this->flush();
431
-			$this->parentStreamSeek($newFilePosition);
432
-			$this->position = $newPosition;
433
-			$return = true;
434
-		}
435
-		return $return;
436
-
437
-	}
438
-
439
-	public function stream_close() {
440
-		$this->flush('end');
441
-		$position = (int)floor($this->position/$this->unencryptedBlockSize);
442
-		$remainingData = $this->encryptionModule->end($this->fullPath, $position . 'end');
443
-		if ($this->readOnly === false) {
444
-			if(!empty($remainingData)) {
445
-				parent::stream_write($remainingData);
446
-			}
447
-			$this->encryptionStorage->updateUnencryptedSize($this->fullPath, $this->unencryptedSize);
448
-		}
449
-		$result = parent::stream_close();
450
-
451
-		if ($this->fileUpdated) {
452
-			$cache = $this->storage->getCache();
453
-			$cacheEntry = $cache->get($this->internalPath);
454
-			if ($cacheEntry) {
455
-				$version = $cacheEntry['encryptedVersion'] + 1;
456
-				$cache->update($cacheEntry->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
457
-			}
458
-		}
459
-
460
-		return $result;
461
-	}
462
-
463
-	/**
464
-	 * write block to file
465
-	 * @param string $positionPrefix
466
-	 */
467
-	protected function flush($positionPrefix = '') {
468
-		// write to disk only when writeFlag was set to 1
469
-		if ($this->writeFlag) {
470
-			// Disable the file proxies so that encryption is not
471
-			// automatically attempted when the file is written to disk -
472
-			// we are handling that separately here and we don't want to
473
-			// get into an infinite loop
474
-			$position = (int)floor($this->position/$this->unencryptedBlockSize);
475
-			$encrypted = $this->encryptionModule->encrypt($this->cache, $position . $positionPrefix);
476
-			$bytesWritten = parent::stream_write($encrypted);
477
-			$this->writeFlag = false;
478
-			// Check whether the write concerns the last block
479
-			// If so then update the encrypted filesize
480
-			// Note that the unencrypted pointer and filesize are NOT yet updated when flush() is called
481
-			// We recalculate the encrypted filesize as we do not know the context of calling flush()
482
-			$completeBlocksInFile=(int)floor($this->unencryptedSize/$this->unencryptedBlockSize);
483
-			if ($completeBlocksInFile === (int)floor($this->position/$this->unencryptedBlockSize)) {
484
-				$this->size = $this->util->getBlockSize() * $completeBlocksInFile;
485
-				$this->size += $bytesWritten;
486
-				$this->size += $this->headerSize;
487
-			}
488
-		}
489
-		// always empty the cache (otherwise readCache() will not fill it with the new block)
490
-		$this->cache = '';
491
-	}
492
-
493
-	/**
494
-	 * read block to file
495
-	 */
496
-	protected function readCache() {
497
-		// cache should always be empty string when this function is called
498
-		// don't try to fill the cache when trying to write at the end of the unencrypted file when it coincides with new block
499
-		if ($this->cache === '' && !($this->position === $this->unencryptedSize && ($this->position % $this->unencryptedBlockSize) === 0)) {
500
-			// Get the data from the file handle
501
-			$data = $this->stream_read_block($this->util->getBlockSize());
502
-			$position = (int)floor($this->position/$this->unencryptedBlockSize);
503
-			$numberOfChunks = (int)($this->unencryptedSize / $this->unencryptedBlockSize);
504
-			if($numberOfChunks === $position) {
505
-				$position .= 'end';
506
-			}
507
-			$this->cache = $this->encryptionModule->decrypt($data, $position);
508
-		}
509
-	}
510
-
511
-	/**
512
-	 * write header at beginning of encrypted file
513
-	 *
514
-	 * @return integer
515
-	 * @throws EncryptionHeaderKeyExistsException if header key is already in use
516
-	 */
517
-	protected function writeHeader() {
518
-		$header = $this->util->createHeader($this->newHeader, $this->encryptionModule);
519
-		return parent::stream_write($header);
520
-	}
521
-
522
-	/**
523
-	 * read first block to skip the header
524
-	 */
525
-	protected function skipHeader() {
526
-		$this->stream_read_block($this->headerSize);
527
-	}
528
-
529
-	/**
530
-	 * call stream_seek() from parent class
531
-	 *
532
-	 * @param integer $position
533
-	 * @return bool
534
-	 */
535
-	protected function parentStreamSeek($position) {
536
-		return parent::stream_seek($position);
537
-	}
538
-
539
-	/**
540
-	 * @param string $path
541
-	 * @param array $options
542
-	 * @return bool
543
-	 */
544
-	public function dir_opendir($path, $options) {
545
-		return false;
546
-	}
322
+    /**
323
+     * stream_read_block
324
+     *
325
+     * This function is a wrapper for function stream_read.
326
+     * It calls stream read until the requested $blockSize was received or no remaining data is present.
327
+     * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
328
+     * remote storage over the internet and it does not care about the given $blockSize.
329
+     *
330
+     * @param int $blockSize Length of requested data block in bytes
331
+     * @return string Data fetched from stream.
332
+     */
333
+    private function stream_read_block(int $blockSize): string {
334
+        $remaining = $blockSize;
335
+        $data = '';
336
+
337
+        do {
338
+            $chunk = parent::stream_read($remaining);
339
+            $chunk_len = strlen($chunk);
340
+            $data .= $chunk;
341
+            $remaining -= $chunk_len;
342
+        } while (($remaining > 0) && ($chunk_len > 0));
343
+
344
+        return $data;
345
+    }
346
+
347
+    public function stream_write($data) {
348
+        $length = 0;
349
+        // loop over $data to fit it in 6126 sized unencrypted blocks
350
+        while (isset($data[0])) {
351
+            $remainingLength = strlen($data);
352
+
353
+            // set the cache to the current 6126 block
354
+            $this->readCache();
355
+
356
+            // for seekable streams the pointer is moved back to the beginning of the encrypted block
357
+            // flush will start writing there when the position moves to another block
358
+            $positionInFile = (int)floor($this->position / $this->unencryptedBlockSize) *
359
+                $this->util->getBlockSize() + $this->headerSize;
360
+            $resultFseek = $this->parentStreamSeek($positionInFile);
361
+
362
+            // only allow writes on seekable streams, or at the end of the encrypted stream
363
+            if (!$this->readOnly && ($resultFseek || $positionInFile === $this->size)) {
364
+
365
+                // switch the writeFlag so flush() will write the block
366
+                $this->writeFlag = true;
367
+                $this->fileUpdated = true;
368
+
369
+                // determine the relative position in the current block
370
+                $blockPosition = ($this->position % $this->unencryptedBlockSize);
371
+                // check if $data fits in current block
372
+                // if so, overwrite existing data (if any)
373
+                // update position and liberate $data
374
+                if ($remainingLength < ($this->unencryptedBlockSize - $blockPosition)) {
375
+                    $this->cache = substr($this->cache, 0, $blockPosition)
376
+                        . $data . substr($this->cache, $blockPosition + $remainingLength);
377
+                    $this->position += $remainingLength;
378
+                    $length += $remainingLength;
379
+                    $data = '';
380
+                    // if $data doesn't fit the current block, the fill the current block and reiterate
381
+                    // after the block is filled, it is flushed and $data is updatedxxx
382
+                } else {
383
+                    $this->cache = substr($this->cache, 0, $blockPosition) .
384
+                        substr($data, 0, $this->unencryptedBlockSize - $blockPosition);
385
+                    $this->flush();
386
+                    $this->position += ($this->unencryptedBlockSize - $blockPosition);
387
+                    $length += ($this->unencryptedBlockSize - $blockPosition);
388
+                    $data = substr($data, $this->unencryptedBlockSize - $blockPosition);
389
+                }
390
+            } else {
391
+                $data = '';
392
+            }
393
+            $this->unencryptedSize = max($this->unencryptedSize, $this->position);
394
+        }
395
+        return $length;
396
+    }
397
+
398
+    public function stream_tell() {
399
+        return $this->position;
400
+    }
401
+
402
+    public function stream_seek($offset, $whence = SEEK_SET) {
403
+
404
+        $return = false;
405
+
406
+        switch ($whence) {
407
+            case SEEK_SET:
408
+                $newPosition = $offset;
409
+                break;
410
+            case SEEK_CUR:
411
+                $newPosition = $this->position + $offset;
412
+                break;
413
+            case SEEK_END:
414
+                $newPosition = $this->unencryptedSize + $offset;
415
+                break;
416
+            default:
417
+                return $return;
418
+        }
419
+
420
+        if ($newPosition > $this->unencryptedSize || $newPosition < 0) {
421
+            return $return;
422
+        }
423
+
424
+        $newFilePosition = floor($newPosition / $this->unencryptedBlockSize)
425
+            * $this->util->getBlockSize() + $this->headerSize;
426
+
427
+        $oldFilePosition = parent::stream_tell();
428
+        if ($this->parentStreamSeek($newFilePosition)) {
429
+            $this->parentStreamSeek($oldFilePosition);
430
+            $this->flush();
431
+            $this->parentStreamSeek($newFilePosition);
432
+            $this->position = $newPosition;
433
+            $return = true;
434
+        }
435
+        return $return;
436
+
437
+    }
438
+
439
+    public function stream_close() {
440
+        $this->flush('end');
441
+        $position = (int)floor($this->position/$this->unencryptedBlockSize);
442
+        $remainingData = $this->encryptionModule->end($this->fullPath, $position . 'end');
443
+        if ($this->readOnly === false) {
444
+            if(!empty($remainingData)) {
445
+                parent::stream_write($remainingData);
446
+            }
447
+            $this->encryptionStorage->updateUnencryptedSize($this->fullPath, $this->unencryptedSize);
448
+        }
449
+        $result = parent::stream_close();
450
+
451
+        if ($this->fileUpdated) {
452
+            $cache = $this->storage->getCache();
453
+            $cacheEntry = $cache->get($this->internalPath);
454
+            if ($cacheEntry) {
455
+                $version = $cacheEntry['encryptedVersion'] + 1;
456
+                $cache->update($cacheEntry->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
457
+            }
458
+        }
459
+
460
+        return $result;
461
+    }
462
+
463
+    /**
464
+     * write block to file
465
+     * @param string $positionPrefix
466
+     */
467
+    protected function flush($positionPrefix = '') {
468
+        // write to disk only when writeFlag was set to 1
469
+        if ($this->writeFlag) {
470
+            // Disable the file proxies so that encryption is not
471
+            // automatically attempted when the file is written to disk -
472
+            // we are handling that separately here and we don't want to
473
+            // get into an infinite loop
474
+            $position = (int)floor($this->position/$this->unencryptedBlockSize);
475
+            $encrypted = $this->encryptionModule->encrypt($this->cache, $position . $positionPrefix);
476
+            $bytesWritten = parent::stream_write($encrypted);
477
+            $this->writeFlag = false;
478
+            // Check whether the write concerns the last block
479
+            // If so then update the encrypted filesize
480
+            // Note that the unencrypted pointer and filesize are NOT yet updated when flush() is called
481
+            // We recalculate the encrypted filesize as we do not know the context of calling flush()
482
+            $completeBlocksInFile=(int)floor($this->unencryptedSize/$this->unencryptedBlockSize);
483
+            if ($completeBlocksInFile === (int)floor($this->position/$this->unencryptedBlockSize)) {
484
+                $this->size = $this->util->getBlockSize() * $completeBlocksInFile;
485
+                $this->size += $bytesWritten;
486
+                $this->size += $this->headerSize;
487
+            }
488
+        }
489
+        // always empty the cache (otherwise readCache() will not fill it with the new block)
490
+        $this->cache = '';
491
+    }
492
+
493
+    /**
494
+     * read block to file
495
+     */
496
+    protected function readCache() {
497
+        // cache should always be empty string when this function is called
498
+        // don't try to fill the cache when trying to write at the end of the unencrypted file when it coincides with new block
499
+        if ($this->cache === '' && !($this->position === $this->unencryptedSize && ($this->position % $this->unencryptedBlockSize) === 0)) {
500
+            // Get the data from the file handle
501
+            $data = $this->stream_read_block($this->util->getBlockSize());
502
+            $position = (int)floor($this->position/$this->unencryptedBlockSize);
503
+            $numberOfChunks = (int)($this->unencryptedSize / $this->unencryptedBlockSize);
504
+            if($numberOfChunks === $position) {
505
+                $position .= 'end';
506
+            }
507
+            $this->cache = $this->encryptionModule->decrypt($data, $position);
508
+        }
509
+    }
510
+
511
+    /**
512
+     * write header at beginning of encrypted file
513
+     *
514
+     * @return integer
515
+     * @throws EncryptionHeaderKeyExistsException if header key is already in use
516
+     */
517
+    protected function writeHeader() {
518
+        $header = $this->util->createHeader($this->newHeader, $this->encryptionModule);
519
+        return parent::stream_write($header);
520
+    }
521
+
522
+    /**
523
+     * read first block to skip the header
524
+     */
525
+    protected function skipHeader() {
526
+        $this->stream_read_block($this->headerSize);
527
+    }
528
+
529
+    /**
530
+     * call stream_seek() from parent class
531
+     *
532
+     * @param integer $position
533
+     * @return bool
534
+     */
535
+    protected function parentStreamSeek($position) {
536
+        return parent::stream_seek($position);
537
+    }
538
+
539
+    /**
540
+     * @param string $path
541
+     * @param array $options
542
+     * @return bool
543
+     */
544
+    public function dir_opendir($path, $options) {
545
+        return false;
546
+    }
547 547
 
548 548
 }
Please login to merge, or discard this patch.
lib/private/Files/Utils/Scanner.php 1 patch
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -61,237 +61,237 @@
 block discarded – undo
61 61
  * @package OC\Files\Utils
62 62
  */
63 63
 class Scanner extends PublicEmitter {
64
-	const MAX_ENTRIES_TO_COMMIT = 10000;
64
+    const MAX_ENTRIES_TO_COMMIT = 10000;
65 65
 
66
-	/** @var string $user */
67
-	private $user;
66
+    /** @var string $user */
67
+    private $user;
68 68
 
69
-	/** @var IDBConnection */
70
-	protected $db;
69
+    /** @var IDBConnection */
70
+    protected $db;
71 71
 
72
-	/** @var IEventDispatcher */
73
-	private $dispatcher;
72
+    /** @var IEventDispatcher */
73
+    private $dispatcher;
74 74
 
75
-	/** @var ILogger */
76
-	protected $logger;
75
+    /** @var ILogger */
76
+    protected $logger;
77 77
 
78
-	/**
79
-	 * Whether to use a DB transaction
80
-	 *
81
-	 * @var bool
82
-	 */
83
-	protected $useTransaction;
78
+    /**
79
+     * Whether to use a DB transaction
80
+     *
81
+     * @var bool
82
+     */
83
+    protected $useTransaction;
84 84
 
85
-	/**
86
-	 * Number of entries scanned to commit
87
-	 *
88
-	 * @var int
89
-	 */
90
-	protected $entriesToCommit;
85
+    /**
86
+     * Number of entries scanned to commit
87
+     *
88
+     * @var int
89
+     */
90
+    protected $entriesToCommit;
91 91
 
92
-	/**
93
-	 * @param string $user
94
-	 * @param IDBConnection|null $db
95
-	 * @param IEventDispatcher $dispatcher
96
-	 * @param ILogger $logger
97
-	 */
98
-	public function __construct($user, $db, IEventDispatcher $dispatcher, ILogger $logger) {
99
-		$this->user = $user;
100
-		$this->db = $db;
101
-		$this->dispatcher = $dispatcher;
102
-		$this->logger = $logger;
103
-		// when DB locking is used, no DB transactions will be used
104
-		$this->useTransaction = !(\OC::$server->getLockingProvider() instanceof DBLockingProvider);
105
-	}
92
+    /**
93
+     * @param string $user
94
+     * @param IDBConnection|null $db
95
+     * @param IEventDispatcher $dispatcher
96
+     * @param ILogger $logger
97
+     */
98
+    public function __construct($user, $db, IEventDispatcher $dispatcher, ILogger $logger) {
99
+        $this->user = $user;
100
+        $this->db = $db;
101
+        $this->dispatcher = $dispatcher;
102
+        $this->logger = $logger;
103
+        // when DB locking is used, no DB transactions will be used
104
+        $this->useTransaction = !(\OC::$server->getLockingProvider() instanceof DBLockingProvider);
105
+    }
106 106
 
107
-	/**
108
-	 * get all storages for $dir
109
-	 *
110
-	 * @param string $dir
111
-	 * @return \OC\Files\Mount\MountPoint[]
112
-	 */
113
-	protected function getMounts($dir) {
114
-		//TODO: move to the node based fileapi once that's done
115
-		\OC_Util::tearDownFS();
116
-		\OC_Util::setupFS($this->user);
107
+    /**
108
+     * get all storages for $dir
109
+     *
110
+     * @param string $dir
111
+     * @return \OC\Files\Mount\MountPoint[]
112
+     */
113
+    protected function getMounts($dir) {
114
+        //TODO: move to the node based fileapi once that's done
115
+        \OC_Util::tearDownFS();
116
+        \OC_Util::setupFS($this->user);
117 117
 
118
-		$mountManager = Filesystem::getMountManager();
119
-		$mounts = $mountManager->findIn($dir);
120
-		$mounts[] = $mountManager->find($dir);
121
-		$mounts = array_reverse($mounts); //start with the mount of $dir
118
+        $mountManager = Filesystem::getMountManager();
119
+        $mounts = $mountManager->findIn($dir);
120
+        $mounts[] = $mountManager->find($dir);
121
+        $mounts = array_reverse($mounts); //start with the mount of $dir
122 122
 
123
-		return $mounts;
124
-	}
123
+        return $mounts;
124
+    }
125 125
 
126
-	/**
127
-	 * attach listeners to the scanner
128
-	 *
129
-	 * @param \OC\Files\Mount\MountPoint $mount
130
-	 */
131
-	protected function attachListener($mount) {
132
-		$scanner = $mount->getStorage()->getScanner();
133
-		$scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount) {
134
-			$this->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]);
135
-			$this->dispatcher->dispatchTyped(new BeforeFileScannedEvent($mount->getMountPoint() . $path));
136
-		});
137
-		$scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount) {
138
-			$this->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]);
139
-			$this->dispatcher->dispatchTyped(new BeforeFolderScannedEvent($mount->getMountPoint() . $path));
140
-		});
141
-		$scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount) {
142
-			$this->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]);
143
-			$this->dispatcher->dispatchTyped(new FileScannedEvent($mount->getMountPoint() . $path));
144
-		});
145
-		$scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount) {
146
-			$this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]);
147
-			$this->dispatcher->dispatchTyped(new FolderScannedEvent($mount->getMountPoint() . $path));
148
-		});
149
-	}
126
+    /**
127
+     * attach listeners to the scanner
128
+     *
129
+     * @param \OC\Files\Mount\MountPoint $mount
130
+     */
131
+    protected function attachListener($mount) {
132
+        $scanner = $mount->getStorage()->getScanner();
133
+        $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount) {
134
+            $this->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]);
135
+            $this->dispatcher->dispatchTyped(new BeforeFileScannedEvent($mount->getMountPoint() . $path));
136
+        });
137
+        $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount) {
138
+            $this->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]);
139
+            $this->dispatcher->dispatchTyped(new BeforeFolderScannedEvent($mount->getMountPoint() . $path));
140
+        });
141
+        $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount) {
142
+            $this->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]);
143
+            $this->dispatcher->dispatchTyped(new FileScannedEvent($mount->getMountPoint() . $path));
144
+        });
145
+        $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount) {
146
+            $this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]);
147
+            $this->dispatcher->dispatchTyped(new FolderScannedEvent($mount->getMountPoint() . $path));
148
+        });
149
+    }
150 150
 
151
-	/**
152
-	 * @param string $dir
153
-	 */
154
-	public function backgroundScan($dir) {
155
-		$mounts = $this->getMounts($dir);
156
-		foreach ($mounts as $mount) {
157
-			$storage = $mount->getStorage();
158
-			if (is_null($storage)) {
159
-				continue;
160
-			}
151
+    /**
152
+     * @param string $dir
153
+     */
154
+    public function backgroundScan($dir) {
155
+        $mounts = $this->getMounts($dir);
156
+        foreach ($mounts as $mount) {
157
+            $storage = $mount->getStorage();
158
+            if (is_null($storage)) {
159
+                continue;
160
+            }
161 161
 
162
-			// don't bother scanning failed storages (shortcut for same result)
163
-			if ($storage->instanceOfStorage(FailedStorage::class)) {
164
-				continue;
165
-			}
162
+            // don't bother scanning failed storages (shortcut for same result)
163
+            if ($storage->instanceOfStorage(FailedStorage::class)) {
164
+                continue;
165
+            }
166 166
 
167
-			// don't scan received local shares, these can be scanned when scanning the owner's storage
168
-			if ($storage->instanceOfStorage(SharedStorage::class)) {
169
-				continue;
170
-			}
171
-			$scanner = $storage->getScanner();
172
-			$this->attachListener($mount);
167
+            // don't scan received local shares, these can be scanned when scanning the owner's storage
168
+            if ($storage->instanceOfStorage(SharedStorage::class)) {
169
+                continue;
170
+            }
171
+            $scanner = $storage->getScanner();
172
+            $this->attachListener($mount);
173 173
 
174
-			$scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
175
-				$this->triggerPropagator($storage, $path);
176
-			});
177
-			$scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
178
-				$this->triggerPropagator($storage, $path);
179
-			});
180
-			$scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
181
-				$this->triggerPropagator($storage, $path);
182
-			});
174
+            $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
175
+                $this->triggerPropagator($storage, $path);
176
+            });
177
+            $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
178
+                $this->triggerPropagator($storage, $path);
179
+            });
180
+            $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
181
+                $this->triggerPropagator($storage, $path);
182
+            });
183 183
 
184
-			$propagator = $storage->getPropagator();
185
-			$propagator->beginBatch();
186
-			$scanner->backgroundScan();
187
-			$propagator->commitBatch();
188
-		}
189
-	}
184
+            $propagator = $storage->getPropagator();
185
+            $propagator->beginBatch();
186
+            $scanner->backgroundScan();
187
+            $propagator->commitBatch();
188
+        }
189
+    }
190 190
 
191
-	/**
192
-	 * @param string $dir
193
-	 * @param $recursive
194
-	 * @param callable|null $mountFilter
195
-	 * @throws ForbiddenException
196
-	 * @throws NotFoundException
197
-	 */
198
-	public function scan($dir = '', $recursive = \OC\Files\Cache\Scanner::SCAN_RECURSIVE, callable $mountFilter = null) {
199
-		if (!Filesystem::isValidPath($dir)) {
200
-			throw new \InvalidArgumentException('Invalid path to scan');
201
-		}
202
-		$mounts = $this->getMounts($dir);
203
-		foreach ($mounts as $mount) {
204
-			if ($mountFilter && !$mountFilter($mount)) {
205
-				continue;
206
-			}
207
-			$storage = $mount->getStorage();
208
-			if (is_null($storage)) {
209
-				continue;
210
-			}
191
+    /**
192
+     * @param string $dir
193
+     * @param $recursive
194
+     * @param callable|null $mountFilter
195
+     * @throws ForbiddenException
196
+     * @throws NotFoundException
197
+     */
198
+    public function scan($dir = '', $recursive = \OC\Files\Cache\Scanner::SCAN_RECURSIVE, callable $mountFilter = null) {
199
+        if (!Filesystem::isValidPath($dir)) {
200
+            throw new \InvalidArgumentException('Invalid path to scan');
201
+        }
202
+        $mounts = $this->getMounts($dir);
203
+        foreach ($mounts as $mount) {
204
+            if ($mountFilter && !$mountFilter($mount)) {
205
+                continue;
206
+            }
207
+            $storage = $mount->getStorage();
208
+            if (is_null($storage)) {
209
+                continue;
210
+            }
211 211
 
212
-			// don't bother scanning failed storages (shortcut for same result)
213
-			if ($storage->instanceOfStorage(FailedStorage::class)) {
214
-				continue;
215
-			}
212
+            // don't bother scanning failed storages (shortcut for same result)
213
+            if ($storage->instanceOfStorage(FailedStorage::class)) {
214
+                continue;
215
+            }
216 216
 
217
-			// if the home storage isn't writable then the scanner is run as the wrong user
218
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home') and
219
-				(!$storage->isCreatable('') or !$storage->isCreatable('files'))
220
-			) {
221
-				if ($storage->file_exists('') or $storage->getCache()->inCache('')) {
222
-					throw new ForbiddenException();
223
-				} else {// if the root exists in neither the cache nor the storage the user isn't setup yet
224
-					break;
225
-				}
217
+            // if the home storage isn't writable then the scanner is run as the wrong user
218
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home') and
219
+                (!$storage->isCreatable('') or !$storage->isCreatable('files'))
220
+            ) {
221
+                if ($storage->file_exists('') or $storage->getCache()->inCache('')) {
222
+                    throw new ForbiddenException();
223
+                } else {// if the root exists in neither the cache nor the storage the user isn't setup yet
224
+                    break;
225
+                }
226 226
 
227
-			}
227
+            }
228 228
 
229
-			// don't scan received local shares, these can be scanned when scanning the owner's storage
230
-			if ($storage->instanceOfStorage(SharedStorage::class)) {
231
-				continue;
232
-			}
233
-			$relativePath = $mount->getInternalPath($dir);
234
-			$scanner = $storage->getScanner();
235
-			$scanner->setUseTransactions(false);
236
-			$this->attachListener($mount);
229
+            // don't scan received local shares, these can be scanned when scanning the owner's storage
230
+            if ($storage->instanceOfStorage(SharedStorage::class)) {
231
+                continue;
232
+            }
233
+            $relativePath = $mount->getInternalPath($dir);
234
+            $scanner = $storage->getScanner();
235
+            $scanner->setUseTransactions(false);
236
+            $this->attachListener($mount);
237 237
 
238
-			$scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
239
-				$this->postProcessEntry($storage, $path);
240
-				$this->dispatcher->dispatchTyped(new NodeRemovedFromCache($storage, $path));
241
-			});
242
-			$scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
243
-				$this->postProcessEntry($storage, $path);
244
-				$this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
245
-			});
246
-			$scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
247
-				$this->postProcessEntry($storage, $path);
248
-				$this->dispatcher->dispatchTyped(new NodeAddedToCache($storage, $path));
249
-			});
238
+            $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
239
+                $this->postProcessEntry($storage, $path);
240
+                $this->dispatcher->dispatchTyped(new NodeRemovedFromCache($storage, $path));
241
+            });
242
+            $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
243
+                $this->postProcessEntry($storage, $path);
244
+                $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
245
+            });
246
+            $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
247
+                $this->postProcessEntry($storage, $path);
248
+                $this->dispatcher->dispatchTyped(new NodeAddedToCache($storage, $path));
249
+            });
250 250
 
251
-			if (!$storage->file_exists($relativePath)) {
252
-				throw new NotFoundException($dir);
253
-			}
251
+            if (!$storage->file_exists($relativePath)) {
252
+                throw new NotFoundException($dir);
253
+            }
254 254
 
255
-			if ($this->useTransaction) {
256
-				$this->db->beginTransaction();
257
-			}
258
-			try {
259
-				$propagator = $storage->getPropagator();
260
-				$propagator->beginBatch();
261
-				$scanner->scan($relativePath, $recursive, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
262
-				$cache = $storage->getCache();
263
-				if ($cache instanceof Cache) {
264
-					// only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
265
-					$cache->correctFolderSize($relativePath);
266
-				}
267
-				$propagator->commitBatch();
268
-			} catch (StorageNotAvailableException $e) {
269
-				$this->logger->error('Storage ' . $storage->getId() . ' not available');
270
-				$this->logger->logException($e);
271
-				$this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]);
272
-			}
273
-			if ($this->useTransaction) {
274
-				$this->db->commit();
275
-			}
276
-		}
277
-	}
255
+            if ($this->useTransaction) {
256
+                $this->db->beginTransaction();
257
+            }
258
+            try {
259
+                $propagator = $storage->getPropagator();
260
+                $propagator->beginBatch();
261
+                $scanner->scan($relativePath, $recursive, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
262
+                $cache = $storage->getCache();
263
+                if ($cache instanceof Cache) {
264
+                    // only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
265
+                    $cache->correctFolderSize($relativePath);
266
+                }
267
+                $propagator->commitBatch();
268
+            } catch (StorageNotAvailableException $e) {
269
+                $this->logger->error('Storage ' . $storage->getId() . ' not available');
270
+                $this->logger->logException($e);
271
+                $this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]);
272
+            }
273
+            if ($this->useTransaction) {
274
+                $this->db->commit();
275
+            }
276
+        }
277
+    }
278 278
 
279
-	private function triggerPropagator(IStorage $storage, $internalPath) {
280
-		$storage->getPropagator()->propagateChange($internalPath, time());
281
-	}
279
+    private function triggerPropagator(IStorage $storage, $internalPath) {
280
+        $storage->getPropagator()->propagateChange($internalPath, time());
281
+    }
282 282
 
283
-	private function postProcessEntry(IStorage $storage, $internalPath) {
284
-		$this->triggerPropagator($storage, $internalPath);
285
-		if ($this->useTransaction) {
286
-			$this->entriesToCommit++;
287
-			if ($this->entriesToCommit >= self::MAX_ENTRIES_TO_COMMIT) {
288
-				$propagator = $storage->getPropagator();
289
-				$this->entriesToCommit = 0;
290
-				$this->db->commit();
291
-				$propagator->commitBatch();
292
-				$this->db->beginTransaction();
293
-				$propagator->beginBatch();
294
-			}
295
-		}
296
-	}
283
+    private function postProcessEntry(IStorage $storage, $internalPath) {
284
+        $this->triggerPropagator($storage, $internalPath);
285
+        if ($this->useTransaction) {
286
+            $this->entriesToCommit++;
287
+            if ($this->entriesToCommit >= self::MAX_ENTRIES_TO_COMMIT) {
288
+                $propagator = $storage->getPropagator();
289
+                $this->entriesToCommit = 0;
290
+                $this->db->commit();
291
+                $propagator->commitBatch();
292
+                $this->db->beginTransaction();
293
+                $propagator->beginBatch();
294
+            }
295
+        }
296
+    }
297 297
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 1 patch
Indentation   +2109 added lines, -2109 removed lines patch added patch discarded remove patch
@@ -82,2113 +82,2113 @@
 block discarded – undo
82 82
  * \OC\Files\Storage\Storage object
83 83
  */
84 84
 class View {
85
-	/** @var string */
86
-	private $fakeRoot = '';
87
-
88
-	/**
89
-	 * @var \OCP\Lock\ILockingProvider
90
-	 */
91
-	protected $lockingProvider;
92
-
93
-	private $lockingEnabled;
94
-
95
-	private $updaterEnabled = true;
96
-
97
-	/** @var \OC\User\Manager */
98
-	private $userManager;
99
-
100
-	/** @var \OCP\ILogger */
101
-	private $logger;
102
-
103
-	/**
104
-	 * @param string $root
105
-	 * @throws \Exception If $root contains an invalid path
106
-	 */
107
-	public function __construct($root = '') {
108
-		if (is_null($root)) {
109
-			throw new \InvalidArgumentException('Root can\'t be null');
110
-		}
111
-		if (!Filesystem::isValidPath($root)) {
112
-			throw new \Exception();
113
-		}
114
-
115
-		$this->fakeRoot = $root;
116
-		$this->lockingProvider = \OC::$server->getLockingProvider();
117
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
-		$this->userManager = \OC::$server->getUserManager();
119
-		$this->logger = \OC::$server->getLogger();
120
-	}
121
-
122
-	public function getAbsolutePath($path = '/') {
123
-		if ($path === null) {
124
-			return null;
125
-		}
126
-		$this->assertPathLength($path);
127
-		if ($path === '') {
128
-			$path = '/';
129
-		}
130
-		if ($path[0] !== '/') {
131
-			$path = '/' . $path;
132
-		}
133
-		return $this->fakeRoot . $path;
134
-	}
135
-
136
-	/**
137
-	 * change the root to a fake root
138
-	 *
139
-	 * @param string $fakeRoot
140
-	 * @return boolean|null
141
-	 */
142
-	public function chroot($fakeRoot) {
143
-		if (!$fakeRoot == '') {
144
-			if ($fakeRoot[0] !== '/') {
145
-				$fakeRoot = '/' . $fakeRoot;
146
-			}
147
-		}
148
-		$this->fakeRoot = $fakeRoot;
149
-	}
150
-
151
-	/**
152
-	 * get the fake root
153
-	 *
154
-	 * @return string
155
-	 */
156
-	public function getRoot() {
157
-		return $this->fakeRoot;
158
-	}
159
-
160
-	/**
161
-	 * get path relative to the root of the view
162
-	 *
163
-	 * @param string $path
164
-	 * @return string
165
-	 */
166
-	public function getRelativePath($path) {
167
-		$this->assertPathLength($path);
168
-		if ($this->fakeRoot == '') {
169
-			return $path;
170
-		}
171
-
172
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
-			return '/';
174
-		}
175
-
176
-		// missing slashes can cause wrong matches!
177
-		$root = rtrim($this->fakeRoot, '/') . '/';
178
-
179
-		if (strpos($path, $root) !== 0) {
180
-			return null;
181
-		} else {
182
-			$path = substr($path, strlen($this->fakeRoot));
183
-			if (strlen($path) === 0) {
184
-				return '/';
185
-			} else {
186
-				return $path;
187
-			}
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * get the mountpoint of the storage object for a path
193
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
194
-	 * returned mountpoint is relative to the absolute root of the filesystem
195
-	 * and does not take the chroot into account )
196
-	 *
197
-	 * @param string $path
198
-	 * @return string
199
-	 */
200
-	public function getMountPoint($path) {
201
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
-	}
203
-
204
-	/**
205
-	 * get the mountpoint of the storage object for a path
206
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
207
-	 * returned mountpoint is relative to the absolute root of the filesystem
208
-	 * and does not take the chroot into account )
209
-	 *
210
-	 * @param string $path
211
-	 * @return \OCP\Files\Mount\IMountPoint
212
-	 */
213
-	public function getMount($path) {
214
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
-	}
216
-
217
-	/**
218
-	 * resolve a path to a storage and internal path
219
-	 *
220
-	 * @param string $path
221
-	 * @return array an array consisting of the storage and the internal path
222
-	 */
223
-	public function resolvePath($path) {
224
-		$a = $this->getAbsolutePath($path);
225
-		$p = Filesystem::normalizePath($a);
226
-		return Filesystem::resolvePath($p);
227
-	}
228
-
229
-	/**
230
-	 * return the path to a local version of the file
231
-	 * we need this because we can't know if a file is stored local or not from
232
-	 * outside the filestorage and for some purposes a local file is needed
233
-	 *
234
-	 * @param string $path
235
-	 * @return string
236
-	 */
237
-	public function getLocalFile($path) {
238
-		$parent = substr($path, 0, strrpos($path, '/'));
239
-		$path = $this->getAbsolutePath($path);
240
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
241
-		if (Filesystem::isValidPath($parent) and $storage) {
242
-			return $storage->getLocalFile($internalPath);
243
-		} else {
244
-			return null;
245
-		}
246
-	}
247
-
248
-	/**
249
-	 * @param string $path
250
-	 * @return string
251
-	 */
252
-	public function getLocalFolder($path) {
253
-		$parent = substr($path, 0, strrpos($path, '/'));
254
-		$path = $this->getAbsolutePath($path);
255
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
256
-		if (Filesystem::isValidPath($parent) and $storage) {
257
-			return $storage->getLocalFolder($internalPath);
258
-		} else {
259
-			return null;
260
-		}
261
-	}
262
-
263
-	/**
264
-	 * the following functions operate with arguments and return values identical
265
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
-	 * for \OC\Files\Storage\Storage via basicOperation().
267
-	 */
268
-	public function mkdir($path) {
269
-		return $this->basicOperation('mkdir', $path, ['create', 'write']);
270
-	}
271
-
272
-	/**
273
-	 * remove mount point
274
-	 *
275
-	 * @param \OC\Files\Mount\MoveableMount $mount
276
-	 * @param string $path relative to data/
277
-	 * @return boolean
278
-	 */
279
-	protected function removeMount($mount, $path) {
280
-		if ($mount instanceof MoveableMount) {
281
-			// cut of /user/files to get the relative path to data/user/files
282
-			$pathParts = explode('/', $path, 4);
283
-			$relPath = '/' . $pathParts[3];
284
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
-			\OC_Hook::emit(
286
-				Filesystem::CLASSNAME, "umount",
287
-				[Filesystem::signal_param_path => $relPath]
288
-			);
289
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
-			$result = $mount->removeMount();
291
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
-			if ($result) {
293
-				\OC_Hook::emit(
294
-					Filesystem::CLASSNAME, "post_umount",
295
-					[Filesystem::signal_param_path => $relPath]
296
-				);
297
-			}
298
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
-			return $result;
300
-		} else {
301
-			// do not allow deleting the storage's root / the mount point
302
-			// because for some storages it might delete the whole contents
303
-			// but isn't supposed to work that way
304
-			return false;
305
-		}
306
-	}
307
-
308
-	public function disableCacheUpdate() {
309
-		$this->updaterEnabled = false;
310
-	}
311
-
312
-	public function enableCacheUpdate() {
313
-		$this->updaterEnabled = true;
314
-	}
315
-
316
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
-		if ($this->updaterEnabled) {
318
-			if (is_null($time)) {
319
-				$time = time();
320
-			}
321
-			$storage->getUpdater()->update($internalPath, $time);
322
-		}
323
-	}
324
-
325
-	protected function removeUpdate(Storage $storage, $internalPath) {
326
-		if ($this->updaterEnabled) {
327
-			$storage->getUpdater()->remove($internalPath);
328
-		}
329
-	}
330
-
331
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
-		if ($this->updaterEnabled) {
333
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
-		}
335
-	}
336
-
337
-	/**
338
-	 * @param string $path
339
-	 * @return bool|mixed
340
-	 */
341
-	public function rmdir($path) {
342
-		$absolutePath = $this->getAbsolutePath($path);
343
-		$mount = Filesystem::getMountManager()->find($absolutePath);
344
-		if ($mount->getInternalPath($absolutePath) === '') {
345
-			return $this->removeMount($mount, $absolutePath);
346
-		}
347
-		if ($this->is_dir($path)) {
348
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
349
-		} else {
350
-			$result = false;
351
-		}
352
-
353
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
-			$storage = $mount->getStorage();
355
-			$internalPath = $mount->getInternalPath($absolutePath);
356
-			$storage->getUpdater()->remove($internalPath);
357
-		}
358
-		return $result;
359
-	}
360
-
361
-	/**
362
-	 * @param string $path
363
-	 * @return resource
364
-	 */
365
-	public function opendir($path) {
366
-		return $this->basicOperation('opendir', $path, ['read']);
367
-	}
368
-
369
-	/**
370
-	 * @param string $path
371
-	 * @return bool|mixed
372
-	 */
373
-	public function is_dir($path) {
374
-		if ($path == '/') {
375
-			return true;
376
-		}
377
-		return $this->basicOperation('is_dir', $path);
378
-	}
379
-
380
-	/**
381
-	 * @param string $path
382
-	 * @return bool|mixed
383
-	 */
384
-	public function is_file($path) {
385
-		if ($path == '/') {
386
-			return false;
387
-		}
388
-		return $this->basicOperation('is_file', $path);
389
-	}
390
-
391
-	/**
392
-	 * @param string $path
393
-	 * @return mixed
394
-	 */
395
-	public function stat($path) {
396
-		return $this->basicOperation('stat', $path);
397
-	}
398
-
399
-	/**
400
-	 * @param string $path
401
-	 * @return mixed
402
-	 */
403
-	public function filetype($path) {
404
-		return $this->basicOperation('filetype', $path);
405
-	}
406
-
407
-	/**
408
-	 * @param string $path
409
-	 * @return mixed
410
-	 */
411
-	public function filesize($path) {
412
-		return $this->basicOperation('filesize', $path);
413
-	}
414
-
415
-	/**
416
-	 * @param string $path
417
-	 * @return bool|mixed
418
-	 * @throws \OCP\Files\InvalidPathException
419
-	 */
420
-	public function readfile($path) {
421
-		$this->assertPathLength($path);
422
-		@ob_end_clean();
423
-		$handle = $this->fopen($path, 'rb');
424
-		if ($handle) {
425
-			$chunkSize = 8192; // 8 kB chunks
426
-			while (!feof($handle)) {
427
-				echo fread($handle, $chunkSize);
428
-				flush();
429
-			}
430
-			fclose($handle);
431
-			return $this->filesize($path);
432
-		}
433
-		return false;
434
-	}
435
-
436
-	/**
437
-	 * @param string $path
438
-	 * @param int $from
439
-	 * @param int $to
440
-	 * @return bool|mixed
441
-	 * @throws \OCP\Files\InvalidPathException
442
-	 * @throws \OCP\Files\UnseekableException
443
-	 */
444
-	public function readfilePart($path, $from, $to) {
445
-		$this->assertPathLength($path);
446
-		@ob_end_clean();
447
-		$handle = $this->fopen($path, 'rb');
448
-		if ($handle) {
449
-			$chunkSize = 8192; // 8 kB chunks
450
-			$startReading = true;
451
-
452
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
453
-				// forward file handle via chunked fread because fseek seem to have failed
454
-
455
-				$end = $from + 1;
456
-				while (!feof($handle) && ftell($handle) < $end) {
457
-					$len = $from - ftell($handle);
458
-					if ($len > $chunkSize) {
459
-						$len = $chunkSize;
460
-					}
461
-					$result = fread($handle, $len);
462
-
463
-					if ($result === false) {
464
-						$startReading = false;
465
-						break;
466
-					}
467
-				}
468
-			}
469
-
470
-			if ($startReading) {
471
-				$end = $to + 1;
472
-				while (!feof($handle) && ftell($handle) < $end) {
473
-					$len = $end - ftell($handle);
474
-					if ($len > $chunkSize) {
475
-						$len = $chunkSize;
476
-					}
477
-					echo fread($handle, $len);
478
-					flush();
479
-				}
480
-				return ftell($handle) - $from;
481
-			}
482
-
483
-			throw new \OCP\Files\UnseekableException('fseek error');
484
-		}
485
-		return false;
486
-	}
487
-
488
-	/**
489
-	 * @param string $path
490
-	 * @return mixed
491
-	 */
492
-	public function isCreatable($path) {
493
-		return $this->basicOperation('isCreatable', $path);
494
-	}
495
-
496
-	/**
497
-	 * @param string $path
498
-	 * @return mixed
499
-	 */
500
-	public function isReadable($path) {
501
-		return $this->basicOperation('isReadable', $path);
502
-	}
503
-
504
-	/**
505
-	 * @param string $path
506
-	 * @return mixed
507
-	 */
508
-	public function isUpdatable($path) {
509
-		return $this->basicOperation('isUpdatable', $path);
510
-	}
511
-
512
-	/**
513
-	 * @param string $path
514
-	 * @return bool|mixed
515
-	 */
516
-	public function isDeletable($path) {
517
-		$absolutePath = $this->getAbsolutePath($path);
518
-		$mount = Filesystem::getMountManager()->find($absolutePath);
519
-		if ($mount->getInternalPath($absolutePath) === '') {
520
-			return $mount instanceof MoveableMount;
521
-		}
522
-		return $this->basicOperation('isDeletable', $path);
523
-	}
524
-
525
-	/**
526
-	 * @param string $path
527
-	 * @return mixed
528
-	 */
529
-	public function isSharable($path) {
530
-		return $this->basicOperation('isSharable', $path);
531
-	}
532
-
533
-	/**
534
-	 * @param string $path
535
-	 * @return bool|mixed
536
-	 */
537
-	public function file_exists($path) {
538
-		if ($path == '/') {
539
-			return true;
540
-		}
541
-		return $this->basicOperation('file_exists', $path);
542
-	}
543
-
544
-	/**
545
-	 * @param string $path
546
-	 * @return mixed
547
-	 */
548
-	public function filemtime($path) {
549
-		return $this->basicOperation('filemtime', $path);
550
-	}
551
-
552
-	/**
553
-	 * @param string $path
554
-	 * @param int|string $mtime
555
-	 * @return bool
556
-	 */
557
-	public function touch($path, $mtime = null) {
558
-		if (!is_null($mtime) and !is_numeric($mtime)) {
559
-			$mtime = strtotime($mtime);
560
-		}
561
-
562
-		$hooks = ['touch'];
563
-
564
-		if (!$this->file_exists($path)) {
565
-			$hooks[] = 'create';
566
-			$hooks[] = 'write';
567
-		}
568
-		try {
569
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
570
-		} catch (\Exception $e) {
571
-			$this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
572
-			$result = false;
573
-		}
574
-		if (!$result) {
575
-			// If create file fails because of permissions on external storage like SMB folders,
576
-			// check file exists and return false if not.
577
-			if (!$this->file_exists($path)) {
578
-				return false;
579
-			}
580
-			if (is_null($mtime)) {
581
-				$mtime = time();
582
-			}
583
-			//if native touch fails, we emulate it by changing the mtime in the cache
584
-			$this->putFileInfo($path, ['mtime' => floor($mtime)]);
585
-		}
586
-		return true;
587
-	}
588
-
589
-	/**
590
-	 * @param string $path
591
-	 * @return mixed
592
-	 * @throws LockedException
593
-	 */
594
-	public function file_get_contents($path) {
595
-		return $this->basicOperation('file_get_contents', $path, ['read']);
596
-	}
597
-
598
-	/**
599
-	 * @param bool $exists
600
-	 * @param string $path
601
-	 * @param bool $run
602
-	 */
603
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
604
-		if (!$exists) {
605
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
606
-				Filesystem::signal_param_path => $this->getHookPath($path),
607
-				Filesystem::signal_param_run => &$run,
608
-			]);
609
-		} else {
610
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
611
-				Filesystem::signal_param_path => $this->getHookPath($path),
612
-				Filesystem::signal_param_run => &$run,
613
-			]);
614
-		}
615
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
616
-			Filesystem::signal_param_path => $this->getHookPath($path),
617
-			Filesystem::signal_param_run => &$run,
618
-		]);
619
-	}
620
-
621
-	/**
622
-	 * @param bool $exists
623
-	 * @param string $path
624
-	 */
625
-	protected function emit_file_hooks_post($exists, $path) {
626
-		if (!$exists) {
627
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
628
-				Filesystem::signal_param_path => $this->getHookPath($path),
629
-			]);
630
-		} else {
631
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
632
-				Filesystem::signal_param_path => $this->getHookPath($path),
633
-			]);
634
-		}
635
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
636
-			Filesystem::signal_param_path => $this->getHookPath($path),
637
-		]);
638
-	}
639
-
640
-	/**
641
-	 * @param string $path
642
-	 * @param string|resource $data
643
-	 * @return bool|mixed
644
-	 * @throws LockedException
645
-	 */
646
-	public function file_put_contents($path, $data) {
647
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
648
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
649
-			if (Filesystem::isValidPath($path)
650
-				and !Filesystem::isFileBlacklisted($path)
651
-			) {
652
-				$path = $this->getRelativePath($absolutePath);
653
-
654
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
655
-
656
-				$exists = $this->file_exists($path);
657
-				$run = true;
658
-				if ($this->shouldEmitHooks($path)) {
659
-					$this->emit_file_hooks_pre($exists, $path, $run);
660
-				}
661
-				if (!$run) {
662
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
663
-					return false;
664
-				}
665
-
666
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
667
-
668
-				/** @var \OC\Files\Storage\Storage $storage */
669
-				list($storage, $internalPath) = $this->resolvePath($path);
670
-				$target = $storage->fopen($internalPath, 'w');
671
-				if ($target) {
672
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
673
-					fclose($target);
674
-					fclose($data);
675
-
676
-					$this->writeUpdate($storage, $internalPath);
677
-
678
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
679
-
680
-					if ($this->shouldEmitHooks($path) && $result !== false) {
681
-						$this->emit_file_hooks_post($exists, $path);
682
-					}
683
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
684
-					return $result;
685
-				} else {
686
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
687
-					return false;
688
-				}
689
-			} else {
690
-				return false;
691
-			}
692
-		} else {
693
-			$hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
694
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
695
-		}
696
-	}
697
-
698
-	/**
699
-	 * @param string $path
700
-	 * @return bool|mixed
701
-	 */
702
-	public function unlink($path) {
703
-		if ($path === '' || $path === '/') {
704
-			// do not allow deleting the root
705
-			return false;
706
-		}
707
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
708
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
709
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
710
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
711
-			return $this->removeMount($mount, $absolutePath);
712
-		}
713
-		if ($this->is_dir($path)) {
714
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
715
-		} else {
716
-			$result = $this->basicOperation('unlink', $path, ['delete']);
717
-		}
718
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
719
-			$storage = $mount->getStorage();
720
-			$internalPath = $mount->getInternalPath($absolutePath);
721
-			$storage->getUpdater()->remove($internalPath);
722
-			return true;
723
-		} else {
724
-			return $result;
725
-		}
726
-	}
727
-
728
-	/**
729
-	 * @param string $directory
730
-	 * @return bool|mixed
731
-	 */
732
-	public function deleteAll($directory) {
733
-		return $this->rmdir($directory);
734
-	}
735
-
736
-	/**
737
-	 * Rename/move a file or folder from the source path to target path.
738
-	 *
739
-	 * @param string $path1 source path
740
-	 * @param string $path2 target path
741
-	 *
742
-	 * @return bool|mixed
743
-	 * @throws LockedException
744
-	 */
745
-	public function rename($path1, $path2) {
746
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
747
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
748
-		$result = false;
749
-		if (
750
-			Filesystem::isValidPath($path2)
751
-			and Filesystem::isValidPath($path1)
752
-			and !Filesystem::isFileBlacklisted($path2)
753
-		) {
754
-			$path1 = $this->getRelativePath($absolutePath1);
755
-			$path2 = $this->getRelativePath($absolutePath2);
756
-			$exists = $this->file_exists($path2);
757
-
758
-			if ($path1 == null or $path2 == null) {
759
-				return false;
760
-			}
761
-
762
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
763
-			try {
764
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
765
-
766
-				$run = true;
767
-				if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
768
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
769
-					$this->emit_file_hooks_pre($exists, $path2, $run);
770
-				} elseif ($this->shouldEmitHooks($path1)) {
771
-					\OC_Hook::emit(
772
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
773
-						[
774
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
775
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
776
-							Filesystem::signal_param_run => &$run
777
-						]
778
-					);
779
-				}
780
-				if ($run) {
781
-					$this->verifyPath(dirname($path2), basename($path2));
782
-
783
-					$manager = Filesystem::getMountManager();
784
-					$mount1 = $this->getMount($path1);
785
-					$mount2 = $this->getMount($path2);
786
-					$storage1 = $mount1->getStorage();
787
-					$storage2 = $mount2->getStorage();
788
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
789
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
790
-
791
-					$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
792
-					try {
793
-						$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
794
-
795
-						if ($internalPath1 === '') {
796
-							if ($mount1 instanceof MoveableMount) {
797
-								$sourceParentMount = $this->getMount(dirname($path1));
798
-								if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
799
-									/**
800
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
801
-									 */
802
-									$sourceMountPoint = $mount1->getMountPoint();
803
-									$result = $mount1->moveMount($absolutePath2);
804
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
805
-								} else {
806
-									$result = false;
807
-								}
808
-							} else {
809
-								$result = false;
810
-							}
811
-							// moving a file/folder within the same mount point
812
-						} elseif ($storage1 === $storage2) {
813
-							if ($storage1) {
814
-								$result = $storage1->rename($internalPath1, $internalPath2);
815
-							} else {
816
-								$result = false;
817
-							}
818
-							// moving a file/folder between storages (from $storage1 to $storage2)
819
-						} else {
820
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
821
-						}
822
-
823
-						if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
824
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
825
-							$this->writeUpdate($storage2, $internalPath2);
826
-						} else if ($result) {
827
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
828
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
829
-							}
830
-						}
831
-					} catch(\Exception $e) {
832
-						throw $e;
833
-					} finally {
834
-						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
835
-						$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
836
-					}
837
-
838
-					if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
839
-						if ($this->shouldEmitHooks()) {
840
-							$this->emit_file_hooks_post($exists, $path2);
841
-						}
842
-					} elseif ($result) {
843
-						if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
844
-							\OC_Hook::emit(
845
-								Filesystem::CLASSNAME,
846
-								Filesystem::signal_post_rename,
847
-								[
848
-									Filesystem::signal_param_oldpath => $this->getHookPath($path1),
849
-									Filesystem::signal_param_newpath => $this->getHookPath($path2)
850
-								]
851
-							);
852
-						}
853
-					}
854
-				}
855
-			} catch(\Exception $e) {
856
-				throw $e;
857
-			} finally {
858
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
859
-				$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
860
-			}
861
-		}
862
-		return $result;
863
-	}
864
-
865
-	/**
866
-	 * Copy a file/folder from the source path to target path
867
-	 *
868
-	 * @param string $path1 source path
869
-	 * @param string $path2 target path
870
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
871
-	 *
872
-	 * @return bool|mixed
873
-	 */
874
-	public function copy($path1, $path2, $preserveMtime = false) {
875
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
876
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
877
-		$result = false;
878
-		if (
879
-			Filesystem::isValidPath($path2)
880
-			and Filesystem::isValidPath($path1)
881
-			and !Filesystem::isFileBlacklisted($path2)
882
-		) {
883
-			$path1 = $this->getRelativePath($absolutePath1);
884
-			$path2 = $this->getRelativePath($absolutePath2);
885
-
886
-			if ($path1 == null or $path2 == null) {
887
-				return false;
888
-			}
889
-			$run = true;
890
-
891
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
892
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
893
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
894
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
895
-
896
-			try {
897
-
898
-				$exists = $this->file_exists($path2);
899
-				if ($this->shouldEmitHooks()) {
900
-					\OC_Hook::emit(
901
-						Filesystem::CLASSNAME,
902
-						Filesystem::signal_copy,
903
-						[
904
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
905
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
906
-							Filesystem::signal_param_run => &$run
907
-						]
908
-					);
909
-					$this->emit_file_hooks_pre($exists, $path2, $run);
910
-				}
911
-				if ($run) {
912
-					$mount1 = $this->getMount($path1);
913
-					$mount2 = $this->getMount($path2);
914
-					$storage1 = $mount1->getStorage();
915
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
916
-					$storage2 = $mount2->getStorage();
917
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
918
-
919
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
920
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
921
-
922
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
923
-						if ($storage1) {
924
-							$result = $storage1->copy($internalPath1, $internalPath2);
925
-						} else {
926
-							$result = false;
927
-						}
928
-					} else {
929
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
930
-					}
931
-
932
-					$this->writeUpdate($storage2, $internalPath2);
933
-
934
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
935
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
936
-
937
-					if ($this->shouldEmitHooks() && $result !== false) {
938
-						\OC_Hook::emit(
939
-							Filesystem::CLASSNAME,
940
-							Filesystem::signal_post_copy,
941
-							[
942
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
943
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
944
-							]
945
-						);
946
-						$this->emit_file_hooks_post($exists, $path2);
947
-					}
948
-
949
-				}
950
-			} catch (\Exception $e) {
951
-				$this->unlockFile($path2, $lockTypePath2);
952
-				$this->unlockFile($path1, $lockTypePath1);
953
-				throw $e;
954
-			}
955
-
956
-			$this->unlockFile($path2, $lockTypePath2);
957
-			$this->unlockFile($path1, $lockTypePath1);
958
-
959
-		}
960
-		return $result;
961
-	}
962
-
963
-	/**
964
-	 * @param string $path
965
-	 * @param string $mode 'r' or 'w'
966
-	 * @return resource
967
-	 * @throws LockedException
968
-	 */
969
-	public function fopen($path, $mode) {
970
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
971
-		$hooks = [];
972
-		switch ($mode) {
973
-			case 'r':
974
-				$hooks[] = 'read';
975
-				break;
976
-			case 'r+':
977
-			case 'w+':
978
-			case 'x+':
979
-			case 'a+':
980
-				$hooks[] = 'read';
981
-				$hooks[] = 'write';
982
-				break;
983
-			case 'w':
984
-			case 'x':
985
-			case 'a':
986
-				$hooks[] = 'write';
987
-				break;
988
-			default:
989
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
990
-		}
991
-
992
-		if ($mode !== 'r' && $mode !== 'w') {
993
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
994
-		}
995
-
996
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
997
-	}
998
-
999
-	/**
1000
-	 * @param string $path
1001
-	 * @return bool|string
1002
-	 * @throws \OCP\Files\InvalidPathException
1003
-	 */
1004
-	public function toTmpFile($path) {
1005
-		$this->assertPathLength($path);
1006
-		if (Filesystem::isValidPath($path)) {
1007
-			$source = $this->fopen($path, 'r');
1008
-			if ($source) {
1009
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1010
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1011
-				file_put_contents($tmpFile, $source);
1012
-				return $tmpFile;
1013
-			} else {
1014
-				return false;
1015
-			}
1016
-		} else {
1017
-			return false;
1018
-		}
1019
-	}
1020
-
1021
-	/**
1022
-	 * @param string $tmpFile
1023
-	 * @param string $path
1024
-	 * @return bool|mixed
1025
-	 * @throws \OCP\Files\InvalidPathException
1026
-	 */
1027
-	public function fromTmpFile($tmpFile, $path) {
1028
-		$this->assertPathLength($path);
1029
-		if (Filesystem::isValidPath($path)) {
1030
-
1031
-			// Get directory that the file is going into
1032
-			$filePath = dirname($path);
1033
-
1034
-			// Create the directories if any
1035
-			if (!$this->file_exists($filePath)) {
1036
-				$result = $this->createParentDirectories($filePath);
1037
-				if ($result === false) {
1038
-					return false;
1039
-				}
1040
-			}
1041
-
1042
-			$source = fopen($tmpFile, 'r');
1043
-			if ($source) {
1044
-				$result = $this->file_put_contents($path, $source);
1045
-				// $this->file_put_contents() might have already closed
1046
-				// the resource, so we check it, before trying to close it
1047
-				// to avoid messages in the error log.
1048
-				if (is_resource($source)) {
1049
-					fclose($source);
1050
-				}
1051
-				unlink($tmpFile);
1052
-				return $result;
1053
-			} else {
1054
-				return false;
1055
-			}
1056
-		} else {
1057
-			return false;
1058
-		}
1059
-	}
1060
-
1061
-
1062
-	/**
1063
-	 * @param string $path
1064
-	 * @return mixed
1065
-	 * @throws \OCP\Files\InvalidPathException
1066
-	 */
1067
-	public function getMimeType($path) {
1068
-		$this->assertPathLength($path);
1069
-		return $this->basicOperation('getMimeType', $path);
1070
-	}
1071
-
1072
-	/**
1073
-	 * @param string $type
1074
-	 * @param string $path
1075
-	 * @param bool $raw
1076
-	 * @return bool|null|string
1077
-	 */
1078
-	public function hash($type, $path, $raw = false) {
1079
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1080
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1081
-		if (Filesystem::isValidPath($path)) {
1082
-			$path = $this->getRelativePath($absolutePath);
1083
-			if ($path == null) {
1084
-				return false;
1085
-			}
1086
-			if ($this->shouldEmitHooks($path)) {
1087
-				\OC_Hook::emit(
1088
-					Filesystem::CLASSNAME,
1089
-					Filesystem::signal_read,
1090
-					[Filesystem::signal_param_path => $this->getHookPath($path)]
1091
-				);
1092
-			}
1093
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1094
-			if ($storage) {
1095
-				return $storage->hash($type, $internalPath, $raw);
1096
-			}
1097
-		}
1098
-		return null;
1099
-	}
1100
-
1101
-	/**
1102
-	 * @param string $path
1103
-	 * @return mixed
1104
-	 * @throws \OCP\Files\InvalidPathException
1105
-	 */
1106
-	public function free_space($path = '/') {
1107
-		$this->assertPathLength($path);
1108
-		$result = $this->basicOperation('free_space', $path);
1109
-		if ($result === null) {
1110
-			throw new InvalidPathException();
1111
-		}
1112
-		return $result;
1113
-	}
1114
-
1115
-	/**
1116
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1117
-	 *
1118
-	 * @param string $operation
1119
-	 * @param string $path
1120
-	 * @param array $hooks (optional)
1121
-	 * @param mixed $extraParam (optional)
1122
-	 * @return mixed
1123
-	 * @throws LockedException
1124
-	 *
1125
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1126
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1127
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1128
-	 */
1129
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1130
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1131
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1132
-		if (Filesystem::isValidPath($path)
1133
-			and !Filesystem::isFileBlacklisted($path)
1134
-		) {
1135
-			$path = $this->getRelativePath($absolutePath);
1136
-			if ($path == null) {
1137
-				return false;
1138
-			}
1139
-
1140
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1141
-				// always a shared lock during pre-hooks so the hook can read the file
1142
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1143
-			}
1144
-
1145
-			$run = $this->runHooks($hooks, $path);
1146
-			/** @var \OC\Files\Storage\Storage $storage */
1147
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1148
-			if ($run and $storage) {
1149
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1150
-					try {
1151
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1152
-					} catch (LockedException $e) {
1153
-						// release the shared lock we acquired before quiting
1154
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1155
-						throw $e;
1156
-					}
1157
-				}
1158
-				try {
1159
-					if (!is_null($extraParam)) {
1160
-						$result = $storage->$operation($internalPath, $extraParam);
1161
-					} else {
1162
-						$result = $storage->$operation($internalPath);
1163
-					}
1164
-				} catch (\Exception $e) {
1165
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1166
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1167
-					} else if (in_array('read', $hooks)) {
1168
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1169
-					}
1170
-					throw $e;
1171
-				}
1172
-
1173
-				if ($result && in_array('delete', $hooks) and $result) {
1174
-					$this->removeUpdate($storage, $internalPath);
1175
-				}
1176
-				if ($result && in_array('write', $hooks,  true) && $operation !== 'fopen' && $operation !== 'touch') {
1177
-					$this->writeUpdate($storage, $internalPath);
1178
-				}
1179
-				if ($result && in_array('touch', $hooks)) {
1180
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1181
-				}
1182
-
1183
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1184
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1185
-				}
1186
-
1187
-				$unlockLater = false;
1188
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1189
-					$unlockLater = true;
1190
-					// make sure our unlocking callback will still be called if connection is aborted
1191
-					ignore_user_abort(true);
1192
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1193
-						if (in_array('write', $hooks)) {
1194
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1195
-						} else if (in_array('read', $hooks)) {
1196
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1197
-						}
1198
-					});
1199
-				}
1200
-
1201
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1202
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1203
-						$this->runHooks($hooks, $path, true);
1204
-					}
1205
-				}
1206
-
1207
-				if (!$unlockLater
1208
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1209
-				) {
1210
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1211
-				}
1212
-				return $result;
1213
-			} else {
1214
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1215
-			}
1216
-		}
1217
-		return null;
1218
-	}
1219
-
1220
-	/**
1221
-	 * get the path relative to the default root for hook usage
1222
-	 *
1223
-	 * @param string $path
1224
-	 * @return string
1225
-	 */
1226
-	private function getHookPath($path) {
1227
-		if (!Filesystem::getView()) {
1228
-			return $path;
1229
-		}
1230
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1231
-	}
1232
-
1233
-	private function shouldEmitHooks($path = '') {
1234
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1235
-			return false;
1236
-		}
1237
-		if (!Filesystem::$loaded) {
1238
-			return false;
1239
-		}
1240
-		$defaultRoot = Filesystem::getRoot();
1241
-		if ($defaultRoot === null) {
1242
-			return false;
1243
-		}
1244
-		if ($this->fakeRoot === $defaultRoot) {
1245
-			return true;
1246
-		}
1247
-		$fullPath = $this->getAbsolutePath($path);
1248
-
1249
-		if ($fullPath === $defaultRoot) {
1250
-			return true;
1251
-		}
1252
-
1253
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1254
-	}
1255
-
1256
-	/**
1257
-	 * @param string[] $hooks
1258
-	 * @param string $path
1259
-	 * @param bool $post
1260
-	 * @return bool
1261
-	 */
1262
-	private function runHooks($hooks, $path, $post = false) {
1263
-		$relativePath = $path;
1264
-		$path = $this->getHookPath($path);
1265
-		$prefix = $post ? 'post_' : '';
1266
-		$run = true;
1267
-		if ($this->shouldEmitHooks($relativePath)) {
1268
-			foreach ($hooks as $hook) {
1269
-				if ($hook != 'read') {
1270
-					\OC_Hook::emit(
1271
-						Filesystem::CLASSNAME,
1272
-						$prefix . $hook,
1273
-						[
1274
-							Filesystem::signal_param_run => &$run,
1275
-							Filesystem::signal_param_path => $path
1276
-						]
1277
-					);
1278
-				} elseif (!$post) {
1279
-					\OC_Hook::emit(
1280
-						Filesystem::CLASSNAME,
1281
-						$prefix . $hook,
1282
-						[
1283
-							Filesystem::signal_param_path => $path
1284
-						]
1285
-					);
1286
-				}
1287
-			}
1288
-		}
1289
-		return $run;
1290
-	}
1291
-
1292
-	/**
1293
-	 * check if a file or folder has been updated since $time
1294
-	 *
1295
-	 * @param string $path
1296
-	 * @param int $time
1297
-	 * @return bool
1298
-	 */
1299
-	public function hasUpdated($path, $time) {
1300
-		return $this->basicOperation('hasUpdated', $path, [], $time);
1301
-	}
1302
-
1303
-	/**
1304
-	 * @param string $ownerId
1305
-	 * @return \OC\User\User
1306
-	 */
1307
-	private function getUserObjectForOwner($ownerId) {
1308
-		$owner = $this->userManager->get($ownerId);
1309
-		if ($owner instanceof IUser) {
1310
-			return $owner;
1311
-		} else {
1312
-			return new User($ownerId, null, \OC::$server->getEventDispatcher());
1313
-		}
1314
-	}
1315
-
1316
-	/**
1317
-	 * Get file info from cache
1318
-	 *
1319
-	 * If the file is not in cached it will be scanned
1320
-	 * If the file has changed on storage the cache will be updated
1321
-	 *
1322
-	 * @param \OC\Files\Storage\Storage $storage
1323
-	 * @param string $internalPath
1324
-	 * @param string $relativePath
1325
-	 * @return ICacheEntry|bool
1326
-	 */
1327
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1328
-		$cache = $storage->getCache($internalPath);
1329
-		$data = $cache->get($internalPath);
1330
-		$watcher = $storage->getWatcher($internalPath);
1331
-
1332
-		try {
1333
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1334
-			if (!$data || $data['size'] === -1) {
1335
-				if (!$storage->file_exists($internalPath)) {
1336
-					return false;
1337
-				}
1338
-				// don't need to get a lock here since the scanner does it's own locking
1339
-				$scanner = $storage->getScanner($internalPath);
1340
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1341
-				$data = $cache->get($internalPath);
1342
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1343
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1344
-				$watcher->update($internalPath, $data);
1345
-				$storage->getPropagator()->propagateChange($internalPath, time());
1346
-				$data = $cache->get($internalPath);
1347
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1348
-			}
1349
-		} catch (LockedException $e) {
1350
-			// if the file is locked we just use the old cache info
1351
-		}
1352
-
1353
-		return $data;
1354
-	}
1355
-
1356
-	/**
1357
-	 * get the filesystem info
1358
-	 *
1359
-	 * @param string $path
1360
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1361
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1362
-	 * defaults to true
1363
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1364
-	 */
1365
-	public function getFileInfo($path, $includeMountPoints = true) {
1366
-		$this->assertPathLength($path);
1367
-		if (!Filesystem::isValidPath($path)) {
1368
-			return false;
1369
-		}
1370
-		if (Cache\Scanner::isPartialFile($path)) {
1371
-			return $this->getPartFileInfo($path);
1372
-		}
1373
-		$relativePath = $path;
1374
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1375
-
1376
-		$mount = Filesystem::getMountManager()->find($path);
1377
-		if (!$mount) {
1378
-			\OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
1379
-			return false;
1380
-		}
1381
-		$storage = $mount->getStorage();
1382
-		$internalPath = $mount->getInternalPath($path);
1383
-		if ($storage) {
1384
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1385
-
1386
-			if (!$data instanceof ICacheEntry) {
1387
-				return false;
1388
-			}
1389
-
1390
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1391
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1392
-			}
1393
-			$ownerId = $storage->getOwner($internalPath);
1394
-			$owner = null;
1395
-			if ($ownerId !== null && $ownerId !== false) {
1396
-				// ownerId might be null if files are accessed with an access token without file system access
1397
-				$owner = $this->getUserObjectForOwner($ownerId);
1398
-			}
1399
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1400
-
1401
-			if ($data and isset($data['fileid'])) {
1402
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1403
-					//add the sizes of other mount points to the folder
1404
-					$extOnly = ($includeMountPoints === 'ext');
1405
-					$mounts = Filesystem::getMountManager()->findIn($path);
1406
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1407
-						$subStorage = $mount->getStorage();
1408
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1409
-					}));
1410
-				}
1411
-			}
1412
-
1413
-			return $info;
1414
-		} else {
1415
-			\OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1416
-		}
1417
-
1418
-		return false;
1419
-	}
1420
-
1421
-	/**
1422
-	 * get the content of a directory
1423
-	 *
1424
-	 * @param string $directory path under datadirectory
1425
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1426
-	 * @return FileInfo[]
1427
-	 */
1428
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1429
-		$this->assertPathLength($directory);
1430
-		if (!Filesystem::isValidPath($directory)) {
1431
-			return [];
1432
-		}
1433
-		$path = $this->getAbsolutePath($directory);
1434
-		$path = Filesystem::normalizePath($path);
1435
-		$mount = $this->getMount($directory);
1436
-		if (!$mount) {
1437
-			return [];
1438
-		}
1439
-		$storage = $mount->getStorage();
1440
-		$internalPath = $mount->getInternalPath($path);
1441
-		if ($storage) {
1442
-			$cache = $storage->getCache($internalPath);
1443
-			$user = \OC_User::getUser();
1444
-
1445
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1446
-
1447
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1448
-				return [];
1449
-			}
1450
-
1451
-			$folderId = $data['fileid'];
1452
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1453
-
1454
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1455
-
1456
-			$fileNames = array_map(function(ICacheEntry $content) {
1457
-				return $content->getName();
1458
-			}, $contents);
1459
-			/**
1460
-			 * @var \OC\Files\FileInfo[] $fileInfos
1461
-			 */
1462
-			$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1463
-				if ($sharingDisabled) {
1464
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1465
-				}
1466
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1467
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1468
-			}, $contents);
1469
-			$files = array_combine($fileNames, $fileInfos);
1470
-
1471
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1472
-			$mounts = Filesystem::getMountManager()->findIn($path);
1473
-			$dirLength = strlen($path);
1474
-			foreach ($mounts as $mount) {
1475
-				$mountPoint = $mount->getMountPoint();
1476
-				$subStorage = $mount->getStorage();
1477
-				if ($subStorage) {
1478
-					$subCache = $subStorage->getCache('');
1479
-
1480
-					$rootEntry = $subCache->get('');
1481
-					if (!$rootEntry) {
1482
-						$subScanner = $subStorage->getScanner('');
1483
-						try {
1484
-							$subScanner->scanFile('');
1485
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1486
-							continue;
1487
-						} catch (\OCP\Files\StorageInvalidException $e) {
1488
-							continue;
1489
-						} catch (\Exception $e) {
1490
-							// sometimes when the storage is not available it can be any exception
1491
-							\OC::$server->getLogger()->logException($e, [
1492
-								'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1493
-								'level' => ILogger::ERROR,
1494
-								'app' => 'lib',
1495
-							]);
1496
-							continue;
1497
-						}
1498
-						$rootEntry = $subCache->get('');
1499
-					}
1500
-
1501
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1502
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1503
-						if ($pos = strpos($relativePath, '/')) {
1504
-							//mountpoint inside subfolder add size to the correct folder
1505
-							$entryName = substr($relativePath, 0, $pos);
1506
-							foreach ($files as &$entry) {
1507
-								if ($entry->getName() === $entryName) {
1508
-									$entry->addSubEntry($rootEntry, $mountPoint);
1509
-								}
1510
-							}
1511
-						} else { //mountpoint in this folder, add an entry for it
1512
-							$rootEntry['name'] = $relativePath;
1513
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1514
-							$permissions = $rootEntry['permissions'];
1515
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1516
-							// for shared files/folders we use the permissions given by the owner
1517
-							if ($mount instanceof MoveableMount) {
1518
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1519
-							} else {
1520
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1521
-							}
1522
-
1523
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1524
-
1525
-							// if sharing was disabled for the user we remove the share permissions
1526
-							if (\OCP\Util::isSharingDisabledForUser()) {
1527
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1528
-							}
1529
-
1530
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1531
-							$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1532
-						}
1533
-					}
1534
-				}
1535
-			}
1536
-
1537
-			if ($mimetype_filter) {
1538
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1539
-					if (strpos($mimetype_filter, '/')) {
1540
-						return $file->getMimetype() === $mimetype_filter;
1541
-					} else {
1542
-						return $file->getMimePart() === $mimetype_filter;
1543
-					}
1544
-				});
1545
-			}
1546
-
1547
-			return array_values($files);
1548
-		} else {
1549
-			return [];
1550
-		}
1551
-	}
1552
-
1553
-	/**
1554
-	 * change file metadata
1555
-	 *
1556
-	 * @param string $path
1557
-	 * @param array|\OCP\Files\FileInfo $data
1558
-	 * @return int
1559
-	 *
1560
-	 * returns the fileid of the updated file
1561
-	 */
1562
-	public function putFileInfo($path, $data) {
1563
-		$this->assertPathLength($path);
1564
-		if ($data instanceof FileInfo) {
1565
-			$data = $data->getData();
1566
-		}
1567
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1568
-		/**
1569
-		 * @var \OC\Files\Storage\Storage $storage
1570
-		 * @var string $internalPath
1571
-		 */
1572
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1573
-		if ($storage) {
1574
-			$cache = $storage->getCache($path);
1575
-
1576
-			if (!$cache->inCache($internalPath)) {
1577
-				$scanner = $storage->getScanner($internalPath);
1578
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1579
-			}
1580
-
1581
-			return $cache->put($internalPath, $data);
1582
-		} else {
1583
-			return -1;
1584
-		}
1585
-	}
1586
-
1587
-	/**
1588
-	 * search for files with the name matching $query
1589
-	 *
1590
-	 * @param string $query
1591
-	 * @return FileInfo[]
1592
-	 */
1593
-	public function search($query) {
1594
-		return $this->searchCommon('search', ['%' . $query . '%']);
1595
-	}
1596
-
1597
-	/**
1598
-	 * search for files with the name matching $query
1599
-	 *
1600
-	 * @param string $query
1601
-	 * @return FileInfo[]
1602
-	 */
1603
-	public function searchRaw($query) {
1604
-		return $this->searchCommon('search', [$query]);
1605
-	}
1606
-
1607
-	/**
1608
-	 * search for files by mimetype
1609
-	 *
1610
-	 * @param string $mimetype
1611
-	 * @return FileInfo[]
1612
-	 */
1613
-	public function searchByMime($mimetype) {
1614
-		return $this->searchCommon('searchByMime', [$mimetype]);
1615
-	}
1616
-
1617
-	/**
1618
-	 * search for files by tag
1619
-	 *
1620
-	 * @param string|int $tag name or tag id
1621
-	 * @param string $userId owner of the tags
1622
-	 * @return FileInfo[]
1623
-	 */
1624
-	public function searchByTag($tag, $userId) {
1625
-		return $this->searchCommon('searchByTag', [$tag, $userId]);
1626
-	}
1627
-
1628
-	/**
1629
-	 * @param string $method cache method
1630
-	 * @param array $args
1631
-	 * @return FileInfo[]
1632
-	 */
1633
-	private function searchCommon($method, $args) {
1634
-		$files = [];
1635
-		$rootLength = strlen($this->fakeRoot);
1636
-
1637
-		$mount = $this->getMount('');
1638
-		$mountPoint = $mount->getMountPoint();
1639
-		$storage = $mount->getStorage();
1640
-		if ($storage) {
1641
-			$cache = $storage->getCache('');
1642
-
1643
-			$results = call_user_func_array([$cache, $method], $args);
1644
-			foreach ($results as $result) {
1645
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1646
-					$internalPath = $result['path'];
1647
-					$path = $mountPoint . $result['path'];
1648
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1649
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1650
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1651
-				}
1652
-			}
1653
-
1654
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1655
-			foreach ($mounts as $mount) {
1656
-				$mountPoint = $mount->getMountPoint();
1657
-				$storage = $mount->getStorage();
1658
-				if ($storage) {
1659
-					$cache = $storage->getCache('');
1660
-
1661
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1662
-					$results = call_user_func_array([$cache, $method], $args);
1663
-					if ($results) {
1664
-						foreach ($results as $result) {
1665
-							$internalPath = $result['path'];
1666
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1667
-							$path = rtrim($mountPoint . $internalPath, '/');
1668
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1669
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1670
-						}
1671
-					}
1672
-				}
1673
-			}
1674
-		}
1675
-		return $files;
1676
-	}
1677
-
1678
-	/**
1679
-	 * Get the owner for a file or folder
1680
-	 *
1681
-	 * @param string $path
1682
-	 * @return string the user id of the owner
1683
-	 * @throws NotFoundException
1684
-	 */
1685
-	public function getOwner($path) {
1686
-		$info = $this->getFileInfo($path);
1687
-		if (!$info) {
1688
-			throw new NotFoundException($path . ' not found while trying to get owner');
1689
-		}
1690
-
1691
-		if ($info->getOwner() === null) {
1692
-			throw new NotFoundException($path . ' has no owner');
1693
-		}
1694
-
1695
-		return $info->getOwner()->getUID();
1696
-	}
1697
-
1698
-	/**
1699
-	 * get the ETag for a file or folder
1700
-	 *
1701
-	 * @param string $path
1702
-	 * @return string
1703
-	 */
1704
-	public function getETag($path) {
1705
-		/**
1706
-		 * @var Storage\Storage $storage
1707
-		 * @var string $internalPath
1708
-		 */
1709
-		list($storage, $internalPath) = $this->resolvePath($path);
1710
-		if ($storage) {
1711
-			return $storage->getETag($internalPath);
1712
-		} else {
1713
-			return null;
1714
-		}
1715
-	}
1716
-
1717
-	/**
1718
-	 * Get the path of a file by id, relative to the view
1719
-	 *
1720
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1721
-	 *
1722
-	 * @param int $id
1723
-	 * @throws NotFoundException
1724
-	 * @return string
1725
-	 */
1726
-	public function getPath($id) {
1727
-		$id = (int)$id;
1728
-		$manager = Filesystem::getMountManager();
1729
-		$mounts = $manager->findIn($this->fakeRoot);
1730
-		$mounts[] = $manager->find($this->fakeRoot);
1731
-		// reverse the array so we start with the storage this view is in
1732
-		// which is the most likely to contain the file we're looking for
1733
-		$mounts = array_reverse($mounts);
1734
-
1735
-		// put non shared mounts in front of the shared mount
1736
-		// this prevent unneeded recursion into shares
1737
-		usort($mounts, function(IMountPoint $a, IMountPoint $b) {
1738
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1739
-		});
1740
-
1741
-		foreach ($mounts as $mount) {
1742
-			/**
1743
-			 * @var \OC\Files\Mount\MountPoint $mount
1744
-			 */
1745
-			if ($mount->getStorage()) {
1746
-				$cache = $mount->getStorage()->getCache();
1747
-				$internalPath = $cache->getPathById($id);
1748
-				if (is_string($internalPath)) {
1749
-					$fullPath = $mount->getMountPoint() . $internalPath;
1750
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1751
-						return $path;
1752
-					}
1753
-				}
1754
-			}
1755
-		}
1756
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1757
-	}
1758
-
1759
-	/**
1760
-	 * @param string $path
1761
-	 * @throws InvalidPathException
1762
-	 */
1763
-	private function assertPathLength($path) {
1764
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1765
-		// Check for the string length - performed using isset() instead of strlen()
1766
-		// because isset() is about 5x-40x faster.
1767
-		if (isset($path[$maxLen])) {
1768
-			$pathLen = strlen($path);
1769
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1770
-		}
1771
-	}
1772
-
1773
-	/**
1774
-	 * check if it is allowed to move a mount point to a given target.
1775
-	 * It is not allowed to move a mount point into a different mount point or
1776
-	 * into an already shared folder
1777
-	 *
1778
-	 * @param IStorage $targetStorage
1779
-	 * @param string $targetInternalPath
1780
-	 * @return boolean
1781
-	 */
1782
-	private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1783
-
1784
-		// note: cannot use the view because the target is already locked
1785
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1786
-		if ($fileId === -1) {
1787
-			// target might not exist, need to check parent instead
1788
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1789
-		}
1790
-
1791
-		// check if any of the parents were shared by the current owner (include collections)
1792
-		$shares = \OCP\Share::getItemShared(
1793
-			'folder',
1794
-			$fileId,
1795
-			\OCP\Share::FORMAT_NONE,
1796
-			null,
1797
-			true
1798
-		);
1799
-
1800
-		if (count($shares) > 0) {
1801
-			\OCP\Util::writeLog('files',
1802
-				'It is not allowed to move one mount point into a shared folder',
1803
-				ILogger::DEBUG);
1804
-			return false;
1805
-		}
1806
-
1807
-		return true;
1808
-	}
1809
-
1810
-	/**
1811
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1812
-	 *
1813
-	 * @param string $path
1814
-	 * @return \OCP\Files\FileInfo
1815
-	 */
1816
-	private function getPartFileInfo($path) {
1817
-		$mount = $this->getMount($path);
1818
-		$storage = $mount->getStorage();
1819
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1820
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1821
-		return new FileInfo(
1822
-			$this->getAbsolutePath($path),
1823
-			$storage,
1824
-			$internalPath,
1825
-			[
1826
-				'fileid' => null,
1827
-				'mimetype' => $storage->getMimeType($internalPath),
1828
-				'name' => basename($path),
1829
-				'etag' => null,
1830
-				'size' => $storage->filesize($internalPath),
1831
-				'mtime' => $storage->filemtime($internalPath),
1832
-				'encrypted' => false,
1833
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1834
-			],
1835
-			$mount,
1836
-			$owner
1837
-		);
1838
-	}
1839
-
1840
-	/**
1841
-	 * @param string $path
1842
-	 * @param string $fileName
1843
-	 * @throws InvalidPathException
1844
-	 */
1845
-	public function verifyPath($path, $fileName) {
1846
-		try {
1847
-			/** @type \OCP\Files\Storage $storage */
1848
-			list($storage, $internalPath) = $this->resolvePath($path);
1849
-			$storage->verifyPath($internalPath, $fileName);
1850
-		} catch (ReservedWordException $ex) {
1851
-			$l = \OC::$server->getL10N('lib');
1852
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1853
-		} catch (InvalidCharacterInPathException $ex) {
1854
-			$l = \OC::$server->getL10N('lib');
1855
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1856
-		} catch (FileNameTooLongException $ex) {
1857
-			$l = \OC::$server->getL10N('lib');
1858
-			throw new InvalidPathException($l->t('File name is too long'));
1859
-		} catch (InvalidDirectoryException $ex) {
1860
-			$l = \OC::$server->getL10N('lib');
1861
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1862
-		} catch (EmptyFileNameException $ex) {
1863
-			$l = \OC::$server->getL10N('lib');
1864
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1865
-		}
1866
-	}
1867
-
1868
-	/**
1869
-	 * get all parent folders of $path
1870
-	 *
1871
-	 * @param string $path
1872
-	 * @return string[]
1873
-	 */
1874
-	private function getParents($path) {
1875
-		$path = trim($path, '/');
1876
-		if (!$path) {
1877
-			return [];
1878
-		}
1879
-
1880
-		$parts = explode('/', $path);
1881
-
1882
-		// remove the single file
1883
-		array_pop($parts);
1884
-		$result = ['/'];
1885
-		$resultPath = '';
1886
-		foreach ($parts as $part) {
1887
-			if ($part) {
1888
-				$resultPath .= '/' . $part;
1889
-				$result[] = $resultPath;
1890
-			}
1891
-		}
1892
-		return $result;
1893
-	}
1894
-
1895
-	/**
1896
-	 * Returns the mount point for which to lock
1897
-	 *
1898
-	 * @param string $absolutePath absolute path
1899
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1900
-	 * is mounted directly on the given path, false otherwise
1901
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1902
-	 */
1903
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1904
-		$results = [];
1905
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1906
-		if (!$mount) {
1907
-			return $results;
1908
-		}
1909
-
1910
-		if ($useParentMount) {
1911
-			// find out if something is mounted directly on the path
1912
-			$internalPath = $mount->getInternalPath($absolutePath);
1913
-			if ($internalPath === '') {
1914
-				// resolve the parent mount instead
1915
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1916
-			}
1917
-		}
1918
-
1919
-		return $mount;
1920
-	}
1921
-
1922
-	/**
1923
-	 * Lock the given path
1924
-	 *
1925
-	 * @param string $path the path of the file to lock, relative to the view
1926
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1927
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1928
-	 *
1929
-	 * @return bool False if the path is excluded from locking, true otherwise
1930
-	 * @throws LockedException if the path is already locked
1931
-	 */
1932
-	private function lockPath($path, $type, $lockMountPoint = false) {
1933
-		$absolutePath = $this->getAbsolutePath($path);
1934
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1935
-		if (!$this->shouldLockFile($absolutePath)) {
1936
-			return false;
1937
-		}
1938
-
1939
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1940
-		if ($mount) {
1941
-			try {
1942
-				$storage = $mount->getStorage();
1943
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1944
-					$storage->acquireLock(
1945
-						$mount->getInternalPath($absolutePath),
1946
-						$type,
1947
-						$this->lockingProvider
1948
-					);
1949
-				}
1950
-			} catch (LockedException $e) {
1951
-				// rethrow with the a human-readable path
1952
-				throw new LockedException(
1953
-					$this->getPathRelativeToFiles($absolutePath),
1954
-					$e,
1955
-					$e->getExistingLock()
1956
-				);
1957
-			}
1958
-		}
1959
-
1960
-		return true;
1961
-	}
1962
-
1963
-	/**
1964
-	 * Change the lock type
1965
-	 *
1966
-	 * @param string $path the path of the file to lock, relative to the view
1967
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1968
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1969
-	 *
1970
-	 * @return bool False if the path is excluded from locking, true otherwise
1971
-	 * @throws LockedException if the path is already locked
1972
-	 */
1973
-	public function changeLock($path, $type, $lockMountPoint = false) {
1974
-		$path = Filesystem::normalizePath($path);
1975
-		$absolutePath = $this->getAbsolutePath($path);
1976
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1977
-		if (!$this->shouldLockFile($absolutePath)) {
1978
-			return false;
1979
-		}
1980
-
1981
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1982
-		if ($mount) {
1983
-			try {
1984
-				$storage = $mount->getStorage();
1985
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1986
-					$storage->changeLock(
1987
-						$mount->getInternalPath($absolutePath),
1988
-						$type,
1989
-						$this->lockingProvider
1990
-					);
1991
-				}
1992
-			} catch (LockedException $e) {
1993
-				try {
1994
-					// rethrow with the a human-readable path
1995
-					throw new LockedException(
1996
-						$this->getPathRelativeToFiles($absolutePath),
1997
-						$e,
1998
-						$e->getExistingLock()
1999
-					);
2000
-				} catch (\InvalidArgumentException $ex) {
2001
-					throw new LockedException(
2002
-						$absolutePath,
2003
-						$ex,
2004
-						$e->getExistingLock()
2005
-					);
2006
-				}
2007
-			}
2008
-		}
2009
-
2010
-		return true;
2011
-	}
2012
-
2013
-	/**
2014
-	 * Unlock the given path
2015
-	 *
2016
-	 * @param string $path the path of the file to unlock, relative to the view
2017
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2018
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2019
-	 *
2020
-	 * @return bool False if the path is excluded from locking, true otherwise
2021
-	 * @throws LockedException
2022
-	 */
2023
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2024
-		$absolutePath = $this->getAbsolutePath($path);
2025
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2026
-		if (!$this->shouldLockFile($absolutePath)) {
2027
-			return false;
2028
-		}
2029
-
2030
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2031
-		if ($mount) {
2032
-			$storage = $mount->getStorage();
2033
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2034
-				$storage->releaseLock(
2035
-					$mount->getInternalPath($absolutePath),
2036
-					$type,
2037
-					$this->lockingProvider
2038
-				);
2039
-			}
2040
-		}
2041
-
2042
-		return true;
2043
-	}
2044
-
2045
-	/**
2046
-	 * Lock a path and all its parents up to the root of the view
2047
-	 *
2048
-	 * @param string $path the path of the file to lock relative to the view
2049
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2050
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2051
-	 *
2052
-	 * @return bool False if the path is excluded from locking, true otherwise
2053
-	 * @throws LockedException
2054
-	 */
2055
-	public function lockFile($path, $type, $lockMountPoint = false) {
2056
-		$absolutePath = $this->getAbsolutePath($path);
2057
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2058
-		if (!$this->shouldLockFile($absolutePath)) {
2059
-			return false;
2060
-		}
2061
-
2062
-		$this->lockPath($path, $type, $lockMountPoint);
2063
-
2064
-		$parents = $this->getParents($path);
2065
-		foreach ($parents as $parent) {
2066
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2067
-		}
2068
-
2069
-		return true;
2070
-	}
2071
-
2072
-	/**
2073
-	 * Unlock a path and all its parents up to the root of the view
2074
-	 *
2075
-	 * @param string $path the path of the file to lock relative to the view
2076
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2077
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2078
-	 *
2079
-	 * @return bool False if the path is excluded from locking, true otherwise
2080
-	 * @throws LockedException
2081
-	 */
2082
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2083
-		$absolutePath = $this->getAbsolutePath($path);
2084
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2085
-		if (!$this->shouldLockFile($absolutePath)) {
2086
-			return false;
2087
-		}
2088
-
2089
-		$this->unlockPath($path, $type, $lockMountPoint);
2090
-
2091
-		$parents = $this->getParents($path);
2092
-		foreach ($parents as $parent) {
2093
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2094
-		}
2095
-
2096
-		return true;
2097
-	}
2098
-
2099
-	/**
2100
-	 * Only lock files in data/user/files/
2101
-	 *
2102
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2103
-	 * @return bool
2104
-	 */
2105
-	protected function shouldLockFile($path) {
2106
-		$path = Filesystem::normalizePath($path);
2107
-
2108
-		$pathSegments = explode('/', $path);
2109
-		if (isset($pathSegments[2])) {
2110
-			// E.g.: /username/files/path-to-file
2111
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2112
-		}
2113
-
2114
-		return strpos($path, '/appdata_') !== 0;
2115
-	}
2116
-
2117
-	/**
2118
-	 * Shortens the given absolute path to be relative to
2119
-	 * "$user/files".
2120
-	 *
2121
-	 * @param string $absolutePath absolute path which is under "files"
2122
-	 *
2123
-	 * @return string path relative to "files" with trimmed slashes or null
2124
-	 * if the path was NOT relative to files
2125
-	 *
2126
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2127
-	 * @since 8.1.0
2128
-	 */
2129
-	public function getPathRelativeToFiles($absolutePath) {
2130
-		$path = Filesystem::normalizePath($absolutePath);
2131
-		$parts = explode('/', trim($path, '/'), 3);
2132
-		// "$user", "files", "path/to/dir"
2133
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2134
-			$this->logger->error(
2135
-				'$absolutePath must be relative to "files", value is "%s"',
2136
-				[
2137
-					$absolutePath
2138
-				]
2139
-			);
2140
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2141
-		}
2142
-		if (isset($parts[2])) {
2143
-			return $parts[2];
2144
-		}
2145
-		return '';
2146
-	}
2147
-
2148
-	/**
2149
-	 * @param string $filename
2150
-	 * @return array
2151
-	 * @throws \OC\User\NoUserException
2152
-	 * @throws NotFoundException
2153
-	 */
2154
-	public function getUidAndFilename($filename) {
2155
-		$info = $this->getFileInfo($filename);
2156
-		if (!$info instanceof \OCP\Files\FileInfo) {
2157
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2158
-		}
2159
-		$uid = $info->getOwner()->getUID();
2160
-		if ($uid != \OCP\User::getUser()) {
2161
-			Filesystem::initMountPoints($uid);
2162
-			$ownerView = new View('/' . $uid . '/files');
2163
-			try {
2164
-				$filename = $ownerView->getPath($info['fileid']);
2165
-			} catch (NotFoundException $e) {
2166
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2167
-			}
2168
-		}
2169
-		return [$uid, $filename];
2170
-	}
2171
-
2172
-	/**
2173
-	 * Creates parent non-existing folders
2174
-	 *
2175
-	 * @param string $filePath
2176
-	 * @return bool
2177
-	 */
2178
-	private function createParentDirectories($filePath) {
2179
-		$directoryParts = explode('/', $filePath);
2180
-		$directoryParts = array_filter($directoryParts);
2181
-		foreach ($directoryParts as $key => $part) {
2182
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2183
-			$currentPath = '/' . implode('/', $currentPathElements);
2184
-			if ($this->is_file($currentPath)) {
2185
-				return false;
2186
-			}
2187
-			if (!$this->file_exists($currentPath)) {
2188
-				$this->mkdir($currentPath);
2189
-			}
2190
-		}
2191
-
2192
-		return true;
2193
-	}
85
+    /** @var string */
86
+    private $fakeRoot = '';
87
+
88
+    /**
89
+     * @var \OCP\Lock\ILockingProvider
90
+     */
91
+    protected $lockingProvider;
92
+
93
+    private $lockingEnabled;
94
+
95
+    private $updaterEnabled = true;
96
+
97
+    /** @var \OC\User\Manager */
98
+    private $userManager;
99
+
100
+    /** @var \OCP\ILogger */
101
+    private $logger;
102
+
103
+    /**
104
+     * @param string $root
105
+     * @throws \Exception If $root contains an invalid path
106
+     */
107
+    public function __construct($root = '') {
108
+        if (is_null($root)) {
109
+            throw new \InvalidArgumentException('Root can\'t be null');
110
+        }
111
+        if (!Filesystem::isValidPath($root)) {
112
+            throw new \Exception();
113
+        }
114
+
115
+        $this->fakeRoot = $root;
116
+        $this->lockingProvider = \OC::$server->getLockingProvider();
117
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
+        $this->userManager = \OC::$server->getUserManager();
119
+        $this->logger = \OC::$server->getLogger();
120
+    }
121
+
122
+    public function getAbsolutePath($path = '/') {
123
+        if ($path === null) {
124
+            return null;
125
+        }
126
+        $this->assertPathLength($path);
127
+        if ($path === '') {
128
+            $path = '/';
129
+        }
130
+        if ($path[0] !== '/') {
131
+            $path = '/' . $path;
132
+        }
133
+        return $this->fakeRoot . $path;
134
+    }
135
+
136
+    /**
137
+     * change the root to a fake root
138
+     *
139
+     * @param string $fakeRoot
140
+     * @return boolean|null
141
+     */
142
+    public function chroot($fakeRoot) {
143
+        if (!$fakeRoot == '') {
144
+            if ($fakeRoot[0] !== '/') {
145
+                $fakeRoot = '/' . $fakeRoot;
146
+            }
147
+        }
148
+        $this->fakeRoot = $fakeRoot;
149
+    }
150
+
151
+    /**
152
+     * get the fake root
153
+     *
154
+     * @return string
155
+     */
156
+    public function getRoot() {
157
+        return $this->fakeRoot;
158
+    }
159
+
160
+    /**
161
+     * get path relative to the root of the view
162
+     *
163
+     * @param string $path
164
+     * @return string
165
+     */
166
+    public function getRelativePath($path) {
167
+        $this->assertPathLength($path);
168
+        if ($this->fakeRoot == '') {
169
+            return $path;
170
+        }
171
+
172
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
+            return '/';
174
+        }
175
+
176
+        // missing slashes can cause wrong matches!
177
+        $root = rtrim($this->fakeRoot, '/') . '/';
178
+
179
+        if (strpos($path, $root) !== 0) {
180
+            return null;
181
+        } else {
182
+            $path = substr($path, strlen($this->fakeRoot));
183
+            if (strlen($path) === 0) {
184
+                return '/';
185
+            } else {
186
+                return $path;
187
+            }
188
+        }
189
+    }
190
+
191
+    /**
192
+     * get the mountpoint of the storage object for a path
193
+     * ( note: because a storage is not always mounted inside the fakeroot, the
194
+     * returned mountpoint is relative to the absolute root of the filesystem
195
+     * and does not take the chroot into account )
196
+     *
197
+     * @param string $path
198
+     * @return string
199
+     */
200
+    public function getMountPoint($path) {
201
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
+    }
203
+
204
+    /**
205
+     * get the mountpoint of the storage object for a path
206
+     * ( note: because a storage is not always mounted inside the fakeroot, the
207
+     * returned mountpoint is relative to the absolute root of the filesystem
208
+     * and does not take the chroot into account )
209
+     *
210
+     * @param string $path
211
+     * @return \OCP\Files\Mount\IMountPoint
212
+     */
213
+    public function getMount($path) {
214
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
+    }
216
+
217
+    /**
218
+     * resolve a path to a storage and internal path
219
+     *
220
+     * @param string $path
221
+     * @return array an array consisting of the storage and the internal path
222
+     */
223
+    public function resolvePath($path) {
224
+        $a = $this->getAbsolutePath($path);
225
+        $p = Filesystem::normalizePath($a);
226
+        return Filesystem::resolvePath($p);
227
+    }
228
+
229
+    /**
230
+     * return the path to a local version of the file
231
+     * we need this because we can't know if a file is stored local or not from
232
+     * outside the filestorage and for some purposes a local file is needed
233
+     *
234
+     * @param string $path
235
+     * @return string
236
+     */
237
+    public function getLocalFile($path) {
238
+        $parent = substr($path, 0, strrpos($path, '/'));
239
+        $path = $this->getAbsolutePath($path);
240
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
241
+        if (Filesystem::isValidPath($parent) and $storage) {
242
+            return $storage->getLocalFile($internalPath);
243
+        } else {
244
+            return null;
245
+        }
246
+    }
247
+
248
+    /**
249
+     * @param string $path
250
+     * @return string
251
+     */
252
+    public function getLocalFolder($path) {
253
+        $parent = substr($path, 0, strrpos($path, '/'));
254
+        $path = $this->getAbsolutePath($path);
255
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
256
+        if (Filesystem::isValidPath($parent) and $storage) {
257
+            return $storage->getLocalFolder($internalPath);
258
+        } else {
259
+            return null;
260
+        }
261
+    }
262
+
263
+    /**
264
+     * the following functions operate with arguments and return values identical
265
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
+     * for \OC\Files\Storage\Storage via basicOperation().
267
+     */
268
+    public function mkdir($path) {
269
+        return $this->basicOperation('mkdir', $path, ['create', 'write']);
270
+    }
271
+
272
+    /**
273
+     * remove mount point
274
+     *
275
+     * @param \OC\Files\Mount\MoveableMount $mount
276
+     * @param string $path relative to data/
277
+     * @return boolean
278
+     */
279
+    protected function removeMount($mount, $path) {
280
+        if ($mount instanceof MoveableMount) {
281
+            // cut of /user/files to get the relative path to data/user/files
282
+            $pathParts = explode('/', $path, 4);
283
+            $relPath = '/' . $pathParts[3];
284
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
+            \OC_Hook::emit(
286
+                Filesystem::CLASSNAME, "umount",
287
+                [Filesystem::signal_param_path => $relPath]
288
+            );
289
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
+            $result = $mount->removeMount();
291
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
+            if ($result) {
293
+                \OC_Hook::emit(
294
+                    Filesystem::CLASSNAME, "post_umount",
295
+                    [Filesystem::signal_param_path => $relPath]
296
+                );
297
+            }
298
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
+            return $result;
300
+        } else {
301
+            // do not allow deleting the storage's root / the mount point
302
+            // because for some storages it might delete the whole contents
303
+            // but isn't supposed to work that way
304
+            return false;
305
+        }
306
+    }
307
+
308
+    public function disableCacheUpdate() {
309
+        $this->updaterEnabled = false;
310
+    }
311
+
312
+    public function enableCacheUpdate() {
313
+        $this->updaterEnabled = true;
314
+    }
315
+
316
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
+        if ($this->updaterEnabled) {
318
+            if (is_null($time)) {
319
+                $time = time();
320
+            }
321
+            $storage->getUpdater()->update($internalPath, $time);
322
+        }
323
+    }
324
+
325
+    protected function removeUpdate(Storage $storage, $internalPath) {
326
+        if ($this->updaterEnabled) {
327
+            $storage->getUpdater()->remove($internalPath);
328
+        }
329
+    }
330
+
331
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
+        if ($this->updaterEnabled) {
333
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
+        }
335
+    }
336
+
337
+    /**
338
+     * @param string $path
339
+     * @return bool|mixed
340
+     */
341
+    public function rmdir($path) {
342
+        $absolutePath = $this->getAbsolutePath($path);
343
+        $mount = Filesystem::getMountManager()->find($absolutePath);
344
+        if ($mount->getInternalPath($absolutePath) === '') {
345
+            return $this->removeMount($mount, $absolutePath);
346
+        }
347
+        if ($this->is_dir($path)) {
348
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
349
+        } else {
350
+            $result = false;
351
+        }
352
+
353
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
+            $storage = $mount->getStorage();
355
+            $internalPath = $mount->getInternalPath($absolutePath);
356
+            $storage->getUpdater()->remove($internalPath);
357
+        }
358
+        return $result;
359
+    }
360
+
361
+    /**
362
+     * @param string $path
363
+     * @return resource
364
+     */
365
+    public function opendir($path) {
366
+        return $this->basicOperation('opendir', $path, ['read']);
367
+    }
368
+
369
+    /**
370
+     * @param string $path
371
+     * @return bool|mixed
372
+     */
373
+    public function is_dir($path) {
374
+        if ($path == '/') {
375
+            return true;
376
+        }
377
+        return $this->basicOperation('is_dir', $path);
378
+    }
379
+
380
+    /**
381
+     * @param string $path
382
+     * @return bool|mixed
383
+     */
384
+    public function is_file($path) {
385
+        if ($path == '/') {
386
+            return false;
387
+        }
388
+        return $this->basicOperation('is_file', $path);
389
+    }
390
+
391
+    /**
392
+     * @param string $path
393
+     * @return mixed
394
+     */
395
+    public function stat($path) {
396
+        return $this->basicOperation('stat', $path);
397
+    }
398
+
399
+    /**
400
+     * @param string $path
401
+     * @return mixed
402
+     */
403
+    public function filetype($path) {
404
+        return $this->basicOperation('filetype', $path);
405
+    }
406
+
407
+    /**
408
+     * @param string $path
409
+     * @return mixed
410
+     */
411
+    public function filesize($path) {
412
+        return $this->basicOperation('filesize', $path);
413
+    }
414
+
415
+    /**
416
+     * @param string $path
417
+     * @return bool|mixed
418
+     * @throws \OCP\Files\InvalidPathException
419
+     */
420
+    public function readfile($path) {
421
+        $this->assertPathLength($path);
422
+        @ob_end_clean();
423
+        $handle = $this->fopen($path, 'rb');
424
+        if ($handle) {
425
+            $chunkSize = 8192; // 8 kB chunks
426
+            while (!feof($handle)) {
427
+                echo fread($handle, $chunkSize);
428
+                flush();
429
+            }
430
+            fclose($handle);
431
+            return $this->filesize($path);
432
+        }
433
+        return false;
434
+    }
435
+
436
+    /**
437
+     * @param string $path
438
+     * @param int $from
439
+     * @param int $to
440
+     * @return bool|mixed
441
+     * @throws \OCP\Files\InvalidPathException
442
+     * @throws \OCP\Files\UnseekableException
443
+     */
444
+    public function readfilePart($path, $from, $to) {
445
+        $this->assertPathLength($path);
446
+        @ob_end_clean();
447
+        $handle = $this->fopen($path, 'rb');
448
+        if ($handle) {
449
+            $chunkSize = 8192; // 8 kB chunks
450
+            $startReading = true;
451
+
452
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
453
+                // forward file handle via chunked fread because fseek seem to have failed
454
+
455
+                $end = $from + 1;
456
+                while (!feof($handle) && ftell($handle) < $end) {
457
+                    $len = $from - ftell($handle);
458
+                    if ($len > $chunkSize) {
459
+                        $len = $chunkSize;
460
+                    }
461
+                    $result = fread($handle, $len);
462
+
463
+                    if ($result === false) {
464
+                        $startReading = false;
465
+                        break;
466
+                    }
467
+                }
468
+            }
469
+
470
+            if ($startReading) {
471
+                $end = $to + 1;
472
+                while (!feof($handle) && ftell($handle) < $end) {
473
+                    $len = $end - ftell($handle);
474
+                    if ($len > $chunkSize) {
475
+                        $len = $chunkSize;
476
+                    }
477
+                    echo fread($handle, $len);
478
+                    flush();
479
+                }
480
+                return ftell($handle) - $from;
481
+            }
482
+
483
+            throw new \OCP\Files\UnseekableException('fseek error');
484
+        }
485
+        return false;
486
+    }
487
+
488
+    /**
489
+     * @param string $path
490
+     * @return mixed
491
+     */
492
+    public function isCreatable($path) {
493
+        return $this->basicOperation('isCreatable', $path);
494
+    }
495
+
496
+    /**
497
+     * @param string $path
498
+     * @return mixed
499
+     */
500
+    public function isReadable($path) {
501
+        return $this->basicOperation('isReadable', $path);
502
+    }
503
+
504
+    /**
505
+     * @param string $path
506
+     * @return mixed
507
+     */
508
+    public function isUpdatable($path) {
509
+        return $this->basicOperation('isUpdatable', $path);
510
+    }
511
+
512
+    /**
513
+     * @param string $path
514
+     * @return bool|mixed
515
+     */
516
+    public function isDeletable($path) {
517
+        $absolutePath = $this->getAbsolutePath($path);
518
+        $mount = Filesystem::getMountManager()->find($absolutePath);
519
+        if ($mount->getInternalPath($absolutePath) === '') {
520
+            return $mount instanceof MoveableMount;
521
+        }
522
+        return $this->basicOperation('isDeletable', $path);
523
+    }
524
+
525
+    /**
526
+     * @param string $path
527
+     * @return mixed
528
+     */
529
+    public function isSharable($path) {
530
+        return $this->basicOperation('isSharable', $path);
531
+    }
532
+
533
+    /**
534
+     * @param string $path
535
+     * @return bool|mixed
536
+     */
537
+    public function file_exists($path) {
538
+        if ($path == '/') {
539
+            return true;
540
+        }
541
+        return $this->basicOperation('file_exists', $path);
542
+    }
543
+
544
+    /**
545
+     * @param string $path
546
+     * @return mixed
547
+     */
548
+    public function filemtime($path) {
549
+        return $this->basicOperation('filemtime', $path);
550
+    }
551
+
552
+    /**
553
+     * @param string $path
554
+     * @param int|string $mtime
555
+     * @return bool
556
+     */
557
+    public function touch($path, $mtime = null) {
558
+        if (!is_null($mtime) and !is_numeric($mtime)) {
559
+            $mtime = strtotime($mtime);
560
+        }
561
+
562
+        $hooks = ['touch'];
563
+
564
+        if (!$this->file_exists($path)) {
565
+            $hooks[] = 'create';
566
+            $hooks[] = 'write';
567
+        }
568
+        try {
569
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
570
+        } catch (\Exception $e) {
571
+            $this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
572
+            $result = false;
573
+        }
574
+        if (!$result) {
575
+            // If create file fails because of permissions on external storage like SMB folders,
576
+            // check file exists and return false if not.
577
+            if (!$this->file_exists($path)) {
578
+                return false;
579
+            }
580
+            if (is_null($mtime)) {
581
+                $mtime = time();
582
+            }
583
+            //if native touch fails, we emulate it by changing the mtime in the cache
584
+            $this->putFileInfo($path, ['mtime' => floor($mtime)]);
585
+        }
586
+        return true;
587
+    }
588
+
589
+    /**
590
+     * @param string $path
591
+     * @return mixed
592
+     * @throws LockedException
593
+     */
594
+    public function file_get_contents($path) {
595
+        return $this->basicOperation('file_get_contents', $path, ['read']);
596
+    }
597
+
598
+    /**
599
+     * @param bool $exists
600
+     * @param string $path
601
+     * @param bool $run
602
+     */
603
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
604
+        if (!$exists) {
605
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
606
+                Filesystem::signal_param_path => $this->getHookPath($path),
607
+                Filesystem::signal_param_run => &$run,
608
+            ]);
609
+        } else {
610
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
611
+                Filesystem::signal_param_path => $this->getHookPath($path),
612
+                Filesystem::signal_param_run => &$run,
613
+            ]);
614
+        }
615
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
616
+            Filesystem::signal_param_path => $this->getHookPath($path),
617
+            Filesystem::signal_param_run => &$run,
618
+        ]);
619
+    }
620
+
621
+    /**
622
+     * @param bool $exists
623
+     * @param string $path
624
+     */
625
+    protected function emit_file_hooks_post($exists, $path) {
626
+        if (!$exists) {
627
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
628
+                Filesystem::signal_param_path => $this->getHookPath($path),
629
+            ]);
630
+        } else {
631
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
632
+                Filesystem::signal_param_path => $this->getHookPath($path),
633
+            ]);
634
+        }
635
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
636
+            Filesystem::signal_param_path => $this->getHookPath($path),
637
+        ]);
638
+    }
639
+
640
+    /**
641
+     * @param string $path
642
+     * @param string|resource $data
643
+     * @return bool|mixed
644
+     * @throws LockedException
645
+     */
646
+    public function file_put_contents($path, $data) {
647
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
648
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
649
+            if (Filesystem::isValidPath($path)
650
+                and !Filesystem::isFileBlacklisted($path)
651
+            ) {
652
+                $path = $this->getRelativePath($absolutePath);
653
+
654
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
655
+
656
+                $exists = $this->file_exists($path);
657
+                $run = true;
658
+                if ($this->shouldEmitHooks($path)) {
659
+                    $this->emit_file_hooks_pre($exists, $path, $run);
660
+                }
661
+                if (!$run) {
662
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
663
+                    return false;
664
+                }
665
+
666
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
667
+
668
+                /** @var \OC\Files\Storage\Storage $storage */
669
+                list($storage, $internalPath) = $this->resolvePath($path);
670
+                $target = $storage->fopen($internalPath, 'w');
671
+                if ($target) {
672
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
673
+                    fclose($target);
674
+                    fclose($data);
675
+
676
+                    $this->writeUpdate($storage, $internalPath);
677
+
678
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
679
+
680
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
681
+                        $this->emit_file_hooks_post($exists, $path);
682
+                    }
683
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
684
+                    return $result;
685
+                } else {
686
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
687
+                    return false;
688
+                }
689
+            } else {
690
+                return false;
691
+            }
692
+        } else {
693
+            $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
694
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
695
+        }
696
+    }
697
+
698
+    /**
699
+     * @param string $path
700
+     * @return bool|mixed
701
+     */
702
+    public function unlink($path) {
703
+        if ($path === '' || $path === '/') {
704
+            // do not allow deleting the root
705
+            return false;
706
+        }
707
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
708
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
709
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
710
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
711
+            return $this->removeMount($mount, $absolutePath);
712
+        }
713
+        if ($this->is_dir($path)) {
714
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
715
+        } else {
716
+            $result = $this->basicOperation('unlink', $path, ['delete']);
717
+        }
718
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
719
+            $storage = $mount->getStorage();
720
+            $internalPath = $mount->getInternalPath($absolutePath);
721
+            $storage->getUpdater()->remove($internalPath);
722
+            return true;
723
+        } else {
724
+            return $result;
725
+        }
726
+    }
727
+
728
+    /**
729
+     * @param string $directory
730
+     * @return bool|mixed
731
+     */
732
+    public function deleteAll($directory) {
733
+        return $this->rmdir($directory);
734
+    }
735
+
736
+    /**
737
+     * Rename/move a file or folder from the source path to target path.
738
+     *
739
+     * @param string $path1 source path
740
+     * @param string $path2 target path
741
+     *
742
+     * @return bool|mixed
743
+     * @throws LockedException
744
+     */
745
+    public function rename($path1, $path2) {
746
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
747
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
748
+        $result = false;
749
+        if (
750
+            Filesystem::isValidPath($path2)
751
+            and Filesystem::isValidPath($path1)
752
+            and !Filesystem::isFileBlacklisted($path2)
753
+        ) {
754
+            $path1 = $this->getRelativePath($absolutePath1);
755
+            $path2 = $this->getRelativePath($absolutePath2);
756
+            $exists = $this->file_exists($path2);
757
+
758
+            if ($path1 == null or $path2 == null) {
759
+                return false;
760
+            }
761
+
762
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
763
+            try {
764
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
765
+
766
+                $run = true;
767
+                if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
768
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
769
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
770
+                } elseif ($this->shouldEmitHooks($path1)) {
771
+                    \OC_Hook::emit(
772
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
773
+                        [
774
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
775
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
776
+                            Filesystem::signal_param_run => &$run
777
+                        ]
778
+                    );
779
+                }
780
+                if ($run) {
781
+                    $this->verifyPath(dirname($path2), basename($path2));
782
+
783
+                    $manager = Filesystem::getMountManager();
784
+                    $mount1 = $this->getMount($path1);
785
+                    $mount2 = $this->getMount($path2);
786
+                    $storage1 = $mount1->getStorage();
787
+                    $storage2 = $mount2->getStorage();
788
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
789
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
790
+
791
+                    $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
792
+                    try {
793
+                        $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
794
+
795
+                        if ($internalPath1 === '') {
796
+                            if ($mount1 instanceof MoveableMount) {
797
+                                $sourceParentMount = $this->getMount(dirname($path1));
798
+                                if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
799
+                                    /**
800
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
801
+                                     */
802
+                                    $sourceMountPoint = $mount1->getMountPoint();
803
+                                    $result = $mount1->moveMount($absolutePath2);
804
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
805
+                                } else {
806
+                                    $result = false;
807
+                                }
808
+                            } else {
809
+                                $result = false;
810
+                            }
811
+                            // moving a file/folder within the same mount point
812
+                        } elseif ($storage1 === $storage2) {
813
+                            if ($storage1) {
814
+                                $result = $storage1->rename($internalPath1, $internalPath2);
815
+                            } else {
816
+                                $result = false;
817
+                            }
818
+                            // moving a file/folder between storages (from $storage1 to $storage2)
819
+                        } else {
820
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
821
+                        }
822
+
823
+                        if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
824
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
825
+                            $this->writeUpdate($storage2, $internalPath2);
826
+                        } else if ($result) {
827
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
828
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
829
+                            }
830
+                        }
831
+                    } catch(\Exception $e) {
832
+                        throw $e;
833
+                    } finally {
834
+                        $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
835
+                        $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
836
+                    }
837
+
838
+                    if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
839
+                        if ($this->shouldEmitHooks()) {
840
+                            $this->emit_file_hooks_post($exists, $path2);
841
+                        }
842
+                    } elseif ($result) {
843
+                        if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
844
+                            \OC_Hook::emit(
845
+                                Filesystem::CLASSNAME,
846
+                                Filesystem::signal_post_rename,
847
+                                [
848
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($path1),
849
+                                    Filesystem::signal_param_newpath => $this->getHookPath($path2)
850
+                                ]
851
+                            );
852
+                        }
853
+                    }
854
+                }
855
+            } catch(\Exception $e) {
856
+                throw $e;
857
+            } finally {
858
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
859
+                $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
860
+            }
861
+        }
862
+        return $result;
863
+    }
864
+
865
+    /**
866
+     * Copy a file/folder from the source path to target path
867
+     *
868
+     * @param string $path1 source path
869
+     * @param string $path2 target path
870
+     * @param bool $preserveMtime whether to preserve mtime on the copy
871
+     *
872
+     * @return bool|mixed
873
+     */
874
+    public function copy($path1, $path2, $preserveMtime = false) {
875
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
876
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
877
+        $result = false;
878
+        if (
879
+            Filesystem::isValidPath($path2)
880
+            and Filesystem::isValidPath($path1)
881
+            and !Filesystem::isFileBlacklisted($path2)
882
+        ) {
883
+            $path1 = $this->getRelativePath($absolutePath1);
884
+            $path2 = $this->getRelativePath($absolutePath2);
885
+
886
+            if ($path1 == null or $path2 == null) {
887
+                return false;
888
+            }
889
+            $run = true;
890
+
891
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
892
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
893
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
894
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
895
+
896
+            try {
897
+
898
+                $exists = $this->file_exists($path2);
899
+                if ($this->shouldEmitHooks()) {
900
+                    \OC_Hook::emit(
901
+                        Filesystem::CLASSNAME,
902
+                        Filesystem::signal_copy,
903
+                        [
904
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
905
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
906
+                            Filesystem::signal_param_run => &$run
907
+                        ]
908
+                    );
909
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
910
+                }
911
+                if ($run) {
912
+                    $mount1 = $this->getMount($path1);
913
+                    $mount2 = $this->getMount($path2);
914
+                    $storage1 = $mount1->getStorage();
915
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
916
+                    $storage2 = $mount2->getStorage();
917
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
918
+
919
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
920
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
921
+
922
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
923
+                        if ($storage1) {
924
+                            $result = $storage1->copy($internalPath1, $internalPath2);
925
+                        } else {
926
+                            $result = false;
927
+                        }
928
+                    } else {
929
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
930
+                    }
931
+
932
+                    $this->writeUpdate($storage2, $internalPath2);
933
+
934
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
935
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
936
+
937
+                    if ($this->shouldEmitHooks() && $result !== false) {
938
+                        \OC_Hook::emit(
939
+                            Filesystem::CLASSNAME,
940
+                            Filesystem::signal_post_copy,
941
+                            [
942
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
943
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
944
+                            ]
945
+                        );
946
+                        $this->emit_file_hooks_post($exists, $path2);
947
+                    }
948
+
949
+                }
950
+            } catch (\Exception $e) {
951
+                $this->unlockFile($path2, $lockTypePath2);
952
+                $this->unlockFile($path1, $lockTypePath1);
953
+                throw $e;
954
+            }
955
+
956
+            $this->unlockFile($path2, $lockTypePath2);
957
+            $this->unlockFile($path1, $lockTypePath1);
958
+
959
+        }
960
+        return $result;
961
+    }
962
+
963
+    /**
964
+     * @param string $path
965
+     * @param string $mode 'r' or 'w'
966
+     * @return resource
967
+     * @throws LockedException
968
+     */
969
+    public function fopen($path, $mode) {
970
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
971
+        $hooks = [];
972
+        switch ($mode) {
973
+            case 'r':
974
+                $hooks[] = 'read';
975
+                break;
976
+            case 'r+':
977
+            case 'w+':
978
+            case 'x+':
979
+            case 'a+':
980
+                $hooks[] = 'read';
981
+                $hooks[] = 'write';
982
+                break;
983
+            case 'w':
984
+            case 'x':
985
+            case 'a':
986
+                $hooks[] = 'write';
987
+                break;
988
+            default:
989
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
990
+        }
991
+
992
+        if ($mode !== 'r' && $mode !== 'w') {
993
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
994
+        }
995
+
996
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
997
+    }
998
+
999
+    /**
1000
+     * @param string $path
1001
+     * @return bool|string
1002
+     * @throws \OCP\Files\InvalidPathException
1003
+     */
1004
+    public function toTmpFile($path) {
1005
+        $this->assertPathLength($path);
1006
+        if (Filesystem::isValidPath($path)) {
1007
+            $source = $this->fopen($path, 'r');
1008
+            if ($source) {
1009
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1010
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1011
+                file_put_contents($tmpFile, $source);
1012
+                return $tmpFile;
1013
+            } else {
1014
+                return false;
1015
+            }
1016
+        } else {
1017
+            return false;
1018
+        }
1019
+    }
1020
+
1021
+    /**
1022
+     * @param string $tmpFile
1023
+     * @param string $path
1024
+     * @return bool|mixed
1025
+     * @throws \OCP\Files\InvalidPathException
1026
+     */
1027
+    public function fromTmpFile($tmpFile, $path) {
1028
+        $this->assertPathLength($path);
1029
+        if (Filesystem::isValidPath($path)) {
1030
+
1031
+            // Get directory that the file is going into
1032
+            $filePath = dirname($path);
1033
+
1034
+            // Create the directories if any
1035
+            if (!$this->file_exists($filePath)) {
1036
+                $result = $this->createParentDirectories($filePath);
1037
+                if ($result === false) {
1038
+                    return false;
1039
+                }
1040
+            }
1041
+
1042
+            $source = fopen($tmpFile, 'r');
1043
+            if ($source) {
1044
+                $result = $this->file_put_contents($path, $source);
1045
+                // $this->file_put_contents() might have already closed
1046
+                // the resource, so we check it, before trying to close it
1047
+                // to avoid messages in the error log.
1048
+                if (is_resource($source)) {
1049
+                    fclose($source);
1050
+                }
1051
+                unlink($tmpFile);
1052
+                return $result;
1053
+            } else {
1054
+                return false;
1055
+            }
1056
+        } else {
1057
+            return false;
1058
+        }
1059
+    }
1060
+
1061
+
1062
+    /**
1063
+     * @param string $path
1064
+     * @return mixed
1065
+     * @throws \OCP\Files\InvalidPathException
1066
+     */
1067
+    public function getMimeType($path) {
1068
+        $this->assertPathLength($path);
1069
+        return $this->basicOperation('getMimeType', $path);
1070
+    }
1071
+
1072
+    /**
1073
+     * @param string $type
1074
+     * @param string $path
1075
+     * @param bool $raw
1076
+     * @return bool|null|string
1077
+     */
1078
+    public function hash($type, $path, $raw = false) {
1079
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1080
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1081
+        if (Filesystem::isValidPath($path)) {
1082
+            $path = $this->getRelativePath($absolutePath);
1083
+            if ($path == null) {
1084
+                return false;
1085
+            }
1086
+            if ($this->shouldEmitHooks($path)) {
1087
+                \OC_Hook::emit(
1088
+                    Filesystem::CLASSNAME,
1089
+                    Filesystem::signal_read,
1090
+                    [Filesystem::signal_param_path => $this->getHookPath($path)]
1091
+                );
1092
+            }
1093
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1094
+            if ($storage) {
1095
+                return $storage->hash($type, $internalPath, $raw);
1096
+            }
1097
+        }
1098
+        return null;
1099
+    }
1100
+
1101
+    /**
1102
+     * @param string $path
1103
+     * @return mixed
1104
+     * @throws \OCP\Files\InvalidPathException
1105
+     */
1106
+    public function free_space($path = '/') {
1107
+        $this->assertPathLength($path);
1108
+        $result = $this->basicOperation('free_space', $path);
1109
+        if ($result === null) {
1110
+            throw new InvalidPathException();
1111
+        }
1112
+        return $result;
1113
+    }
1114
+
1115
+    /**
1116
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1117
+     *
1118
+     * @param string $operation
1119
+     * @param string $path
1120
+     * @param array $hooks (optional)
1121
+     * @param mixed $extraParam (optional)
1122
+     * @return mixed
1123
+     * @throws LockedException
1124
+     *
1125
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1126
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1127
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1128
+     */
1129
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1130
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1131
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1132
+        if (Filesystem::isValidPath($path)
1133
+            and !Filesystem::isFileBlacklisted($path)
1134
+        ) {
1135
+            $path = $this->getRelativePath($absolutePath);
1136
+            if ($path == null) {
1137
+                return false;
1138
+            }
1139
+
1140
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1141
+                // always a shared lock during pre-hooks so the hook can read the file
1142
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1143
+            }
1144
+
1145
+            $run = $this->runHooks($hooks, $path);
1146
+            /** @var \OC\Files\Storage\Storage $storage */
1147
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1148
+            if ($run and $storage) {
1149
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1150
+                    try {
1151
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1152
+                    } catch (LockedException $e) {
1153
+                        // release the shared lock we acquired before quiting
1154
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1155
+                        throw $e;
1156
+                    }
1157
+                }
1158
+                try {
1159
+                    if (!is_null($extraParam)) {
1160
+                        $result = $storage->$operation($internalPath, $extraParam);
1161
+                    } else {
1162
+                        $result = $storage->$operation($internalPath);
1163
+                    }
1164
+                } catch (\Exception $e) {
1165
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1166
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1167
+                    } else if (in_array('read', $hooks)) {
1168
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1169
+                    }
1170
+                    throw $e;
1171
+                }
1172
+
1173
+                if ($result && in_array('delete', $hooks) and $result) {
1174
+                    $this->removeUpdate($storage, $internalPath);
1175
+                }
1176
+                if ($result && in_array('write', $hooks,  true) && $operation !== 'fopen' && $operation !== 'touch') {
1177
+                    $this->writeUpdate($storage, $internalPath);
1178
+                }
1179
+                if ($result && in_array('touch', $hooks)) {
1180
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1181
+                }
1182
+
1183
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1184
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1185
+                }
1186
+
1187
+                $unlockLater = false;
1188
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1189
+                    $unlockLater = true;
1190
+                    // make sure our unlocking callback will still be called if connection is aborted
1191
+                    ignore_user_abort(true);
1192
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1193
+                        if (in_array('write', $hooks)) {
1194
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1195
+                        } else if (in_array('read', $hooks)) {
1196
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1197
+                        }
1198
+                    });
1199
+                }
1200
+
1201
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1202
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1203
+                        $this->runHooks($hooks, $path, true);
1204
+                    }
1205
+                }
1206
+
1207
+                if (!$unlockLater
1208
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1209
+                ) {
1210
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1211
+                }
1212
+                return $result;
1213
+            } else {
1214
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1215
+            }
1216
+        }
1217
+        return null;
1218
+    }
1219
+
1220
+    /**
1221
+     * get the path relative to the default root for hook usage
1222
+     *
1223
+     * @param string $path
1224
+     * @return string
1225
+     */
1226
+    private function getHookPath($path) {
1227
+        if (!Filesystem::getView()) {
1228
+            return $path;
1229
+        }
1230
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1231
+    }
1232
+
1233
+    private function shouldEmitHooks($path = '') {
1234
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1235
+            return false;
1236
+        }
1237
+        if (!Filesystem::$loaded) {
1238
+            return false;
1239
+        }
1240
+        $defaultRoot = Filesystem::getRoot();
1241
+        if ($defaultRoot === null) {
1242
+            return false;
1243
+        }
1244
+        if ($this->fakeRoot === $defaultRoot) {
1245
+            return true;
1246
+        }
1247
+        $fullPath = $this->getAbsolutePath($path);
1248
+
1249
+        if ($fullPath === $defaultRoot) {
1250
+            return true;
1251
+        }
1252
+
1253
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1254
+    }
1255
+
1256
+    /**
1257
+     * @param string[] $hooks
1258
+     * @param string $path
1259
+     * @param bool $post
1260
+     * @return bool
1261
+     */
1262
+    private function runHooks($hooks, $path, $post = false) {
1263
+        $relativePath = $path;
1264
+        $path = $this->getHookPath($path);
1265
+        $prefix = $post ? 'post_' : '';
1266
+        $run = true;
1267
+        if ($this->shouldEmitHooks($relativePath)) {
1268
+            foreach ($hooks as $hook) {
1269
+                if ($hook != 'read') {
1270
+                    \OC_Hook::emit(
1271
+                        Filesystem::CLASSNAME,
1272
+                        $prefix . $hook,
1273
+                        [
1274
+                            Filesystem::signal_param_run => &$run,
1275
+                            Filesystem::signal_param_path => $path
1276
+                        ]
1277
+                    );
1278
+                } elseif (!$post) {
1279
+                    \OC_Hook::emit(
1280
+                        Filesystem::CLASSNAME,
1281
+                        $prefix . $hook,
1282
+                        [
1283
+                            Filesystem::signal_param_path => $path
1284
+                        ]
1285
+                    );
1286
+                }
1287
+            }
1288
+        }
1289
+        return $run;
1290
+    }
1291
+
1292
+    /**
1293
+     * check if a file or folder has been updated since $time
1294
+     *
1295
+     * @param string $path
1296
+     * @param int $time
1297
+     * @return bool
1298
+     */
1299
+    public function hasUpdated($path, $time) {
1300
+        return $this->basicOperation('hasUpdated', $path, [], $time);
1301
+    }
1302
+
1303
+    /**
1304
+     * @param string $ownerId
1305
+     * @return \OC\User\User
1306
+     */
1307
+    private function getUserObjectForOwner($ownerId) {
1308
+        $owner = $this->userManager->get($ownerId);
1309
+        if ($owner instanceof IUser) {
1310
+            return $owner;
1311
+        } else {
1312
+            return new User($ownerId, null, \OC::$server->getEventDispatcher());
1313
+        }
1314
+    }
1315
+
1316
+    /**
1317
+     * Get file info from cache
1318
+     *
1319
+     * If the file is not in cached it will be scanned
1320
+     * If the file has changed on storage the cache will be updated
1321
+     *
1322
+     * @param \OC\Files\Storage\Storage $storage
1323
+     * @param string $internalPath
1324
+     * @param string $relativePath
1325
+     * @return ICacheEntry|bool
1326
+     */
1327
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1328
+        $cache = $storage->getCache($internalPath);
1329
+        $data = $cache->get($internalPath);
1330
+        $watcher = $storage->getWatcher($internalPath);
1331
+
1332
+        try {
1333
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1334
+            if (!$data || $data['size'] === -1) {
1335
+                if (!$storage->file_exists($internalPath)) {
1336
+                    return false;
1337
+                }
1338
+                // don't need to get a lock here since the scanner does it's own locking
1339
+                $scanner = $storage->getScanner($internalPath);
1340
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1341
+                $data = $cache->get($internalPath);
1342
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1343
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1344
+                $watcher->update($internalPath, $data);
1345
+                $storage->getPropagator()->propagateChange($internalPath, time());
1346
+                $data = $cache->get($internalPath);
1347
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1348
+            }
1349
+        } catch (LockedException $e) {
1350
+            // if the file is locked we just use the old cache info
1351
+        }
1352
+
1353
+        return $data;
1354
+    }
1355
+
1356
+    /**
1357
+     * get the filesystem info
1358
+     *
1359
+     * @param string $path
1360
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1361
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1362
+     * defaults to true
1363
+     * @return \OC\Files\FileInfo|false False if file does not exist
1364
+     */
1365
+    public function getFileInfo($path, $includeMountPoints = true) {
1366
+        $this->assertPathLength($path);
1367
+        if (!Filesystem::isValidPath($path)) {
1368
+            return false;
1369
+        }
1370
+        if (Cache\Scanner::isPartialFile($path)) {
1371
+            return $this->getPartFileInfo($path);
1372
+        }
1373
+        $relativePath = $path;
1374
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1375
+
1376
+        $mount = Filesystem::getMountManager()->find($path);
1377
+        if (!$mount) {
1378
+            \OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
1379
+            return false;
1380
+        }
1381
+        $storage = $mount->getStorage();
1382
+        $internalPath = $mount->getInternalPath($path);
1383
+        if ($storage) {
1384
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1385
+
1386
+            if (!$data instanceof ICacheEntry) {
1387
+                return false;
1388
+            }
1389
+
1390
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1391
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1392
+            }
1393
+            $ownerId = $storage->getOwner($internalPath);
1394
+            $owner = null;
1395
+            if ($ownerId !== null && $ownerId !== false) {
1396
+                // ownerId might be null if files are accessed with an access token without file system access
1397
+                $owner = $this->getUserObjectForOwner($ownerId);
1398
+            }
1399
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1400
+
1401
+            if ($data and isset($data['fileid'])) {
1402
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1403
+                    //add the sizes of other mount points to the folder
1404
+                    $extOnly = ($includeMountPoints === 'ext');
1405
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1406
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1407
+                        $subStorage = $mount->getStorage();
1408
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1409
+                    }));
1410
+                }
1411
+            }
1412
+
1413
+            return $info;
1414
+        } else {
1415
+            \OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1416
+        }
1417
+
1418
+        return false;
1419
+    }
1420
+
1421
+    /**
1422
+     * get the content of a directory
1423
+     *
1424
+     * @param string $directory path under datadirectory
1425
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1426
+     * @return FileInfo[]
1427
+     */
1428
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1429
+        $this->assertPathLength($directory);
1430
+        if (!Filesystem::isValidPath($directory)) {
1431
+            return [];
1432
+        }
1433
+        $path = $this->getAbsolutePath($directory);
1434
+        $path = Filesystem::normalizePath($path);
1435
+        $mount = $this->getMount($directory);
1436
+        if (!$mount) {
1437
+            return [];
1438
+        }
1439
+        $storage = $mount->getStorage();
1440
+        $internalPath = $mount->getInternalPath($path);
1441
+        if ($storage) {
1442
+            $cache = $storage->getCache($internalPath);
1443
+            $user = \OC_User::getUser();
1444
+
1445
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1446
+
1447
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1448
+                return [];
1449
+            }
1450
+
1451
+            $folderId = $data['fileid'];
1452
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1453
+
1454
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1455
+
1456
+            $fileNames = array_map(function(ICacheEntry $content) {
1457
+                return $content->getName();
1458
+            }, $contents);
1459
+            /**
1460
+             * @var \OC\Files\FileInfo[] $fileInfos
1461
+             */
1462
+            $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1463
+                if ($sharingDisabled) {
1464
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1465
+                }
1466
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1467
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1468
+            }, $contents);
1469
+            $files = array_combine($fileNames, $fileInfos);
1470
+
1471
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1472
+            $mounts = Filesystem::getMountManager()->findIn($path);
1473
+            $dirLength = strlen($path);
1474
+            foreach ($mounts as $mount) {
1475
+                $mountPoint = $mount->getMountPoint();
1476
+                $subStorage = $mount->getStorage();
1477
+                if ($subStorage) {
1478
+                    $subCache = $subStorage->getCache('');
1479
+
1480
+                    $rootEntry = $subCache->get('');
1481
+                    if (!$rootEntry) {
1482
+                        $subScanner = $subStorage->getScanner('');
1483
+                        try {
1484
+                            $subScanner->scanFile('');
1485
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1486
+                            continue;
1487
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1488
+                            continue;
1489
+                        } catch (\Exception $e) {
1490
+                            // sometimes when the storage is not available it can be any exception
1491
+                            \OC::$server->getLogger()->logException($e, [
1492
+                                'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1493
+                                'level' => ILogger::ERROR,
1494
+                                'app' => 'lib',
1495
+                            ]);
1496
+                            continue;
1497
+                        }
1498
+                        $rootEntry = $subCache->get('');
1499
+                    }
1500
+
1501
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1502
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1503
+                        if ($pos = strpos($relativePath, '/')) {
1504
+                            //mountpoint inside subfolder add size to the correct folder
1505
+                            $entryName = substr($relativePath, 0, $pos);
1506
+                            foreach ($files as &$entry) {
1507
+                                if ($entry->getName() === $entryName) {
1508
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1509
+                                }
1510
+                            }
1511
+                        } else { //mountpoint in this folder, add an entry for it
1512
+                            $rootEntry['name'] = $relativePath;
1513
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1514
+                            $permissions = $rootEntry['permissions'];
1515
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1516
+                            // for shared files/folders we use the permissions given by the owner
1517
+                            if ($mount instanceof MoveableMount) {
1518
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1519
+                            } else {
1520
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1521
+                            }
1522
+
1523
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1524
+
1525
+                            // if sharing was disabled for the user we remove the share permissions
1526
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1527
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1528
+                            }
1529
+
1530
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1531
+                            $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1532
+                        }
1533
+                    }
1534
+                }
1535
+            }
1536
+
1537
+            if ($mimetype_filter) {
1538
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1539
+                    if (strpos($mimetype_filter, '/')) {
1540
+                        return $file->getMimetype() === $mimetype_filter;
1541
+                    } else {
1542
+                        return $file->getMimePart() === $mimetype_filter;
1543
+                    }
1544
+                });
1545
+            }
1546
+
1547
+            return array_values($files);
1548
+        } else {
1549
+            return [];
1550
+        }
1551
+    }
1552
+
1553
+    /**
1554
+     * change file metadata
1555
+     *
1556
+     * @param string $path
1557
+     * @param array|\OCP\Files\FileInfo $data
1558
+     * @return int
1559
+     *
1560
+     * returns the fileid of the updated file
1561
+     */
1562
+    public function putFileInfo($path, $data) {
1563
+        $this->assertPathLength($path);
1564
+        if ($data instanceof FileInfo) {
1565
+            $data = $data->getData();
1566
+        }
1567
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1568
+        /**
1569
+         * @var \OC\Files\Storage\Storage $storage
1570
+         * @var string $internalPath
1571
+         */
1572
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1573
+        if ($storage) {
1574
+            $cache = $storage->getCache($path);
1575
+
1576
+            if (!$cache->inCache($internalPath)) {
1577
+                $scanner = $storage->getScanner($internalPath);
1578
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1579
+            }
1580
+
1581
+            return $cache->put($internalPath, $data);
1582
+        } else {
1583
+            return -1;
1584
+        }
1585
+    }
1586
+
1587
+    /**
1588
+     * search for files with the name matching $query
1589
+     *
1590
+     * @param string $query
1591
+     * @return FileInfo[]
1592
+     */
1593
+    public function search($query) {
1594
+        return $this->searchCommon('search', ['%' . $query . '%']);
1595
+    }
1596
+
1597
+    /**
1598
+     * search for files with the name matching $query
1599
+     *
1600
+     * @param string $query
1601
+     * @return FileInfo[]
1602
+     */
1603
+    public function searchRaw($query) {
1604
+        return $this->searchCommon('search', [$query]);
1605
+    }
1606
+
1607
+    /**
1608
+     * search for files by mimetype
1609
+     *
1610
+     * @param string $mimetype
1611
+     * @return FileInfo[]
1612
+     */
1613
+    public function searchByMime($mimetype) {
1614
+        return $this->searchCommon('searchByMime', [$mimetype]);
1615
+    }
1616
+
1617
+    /**
1618
+     * search for files by tag
1619
+     *
1620
+     * @param string|int $tag name or tag id
1621
+     * @param string $userId owner of the tags
1622
+     * @return FileInfo[]
1623
+     */
1624
+    public function searchByTag($tag, $userId) {
1625
+        return $this->searchCommon('searchByTag', [$tag, $userId]);
1626
+    }
1627
+
1628
+    /**
1629
+     * @param string $method cache method
1630
+     * @param array $args
1631
+     * @return FileInfo[]
1632
+     */
1633
+    private function searchCommon($method, $args) {
1634
+        $files = [];
1635
+        $rootLength = strlen($this->fakeRoot);
1636
+
1637
+        $mount = $this->getMount('');
1638
+        $mountPoint = $mount->getMountPoint();
1639
+        $storage = $mount->getStorage();
1640
+        if ($storage) {
1641
+            $cache = $storage->getCache('');
1642
+
1643
+            $results = call_user_func_array([$cache, $method], $args);
1644
+            foreach ($results as $result) {
1645
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1646
+                    $internalPath = $result['path'];
1647
+                    $path = $mountPoint . $result['path'];
1648
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1649
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1650
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1651
+                }
1652
+            }
1653
+
1654
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1655
+            foreach ($mounts as $mount) {
1656
+                $mountPoint = $mount->getMountPoint();
1657
+                $storage = $mount->getStorage();
1658
+                if ($storage) {
1659
+                    $cache = $storage->getCache('');
1660
+
1661
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1662
+                    $results = call_user_func_array([$cache, $method], $args);
1663
+                    if ($results) {
1664
+                        foreach ($results as $result) {
1665
+                            $internalPath = $result['path'];
1666
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1667
+                            $path = rtrim($mountPoint . $internalPath, '/');
1668
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1669
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1670
+                        }
1671
+                    }
1672
+                }
1673
+            }
1674
+        }
1675
+        return $files;
1676
+    }
1677
+
1678
+    /**
1679
+     * Get the owner for a file or folder
1680
+     *
1681
+     * @param string $path
1682
+     * @return string the user id of the owner
1683
+     * @throws NotFoundException
1684
+     */
1685
+    public function getOwner($path) {
1686
+        $info = $this->getFileInfo($path);
1687
+        if (!$info) {
1688
+            throw new NotFoundException($path . ' not found while trying to get owner');
1689
+        }
1690
+
1691
+        if ($info->getOwner() === null) {
1692
+            throw new NotFoundException($path . ' has no owner');
1693
+        }
1694
+
1695
+        return $info->getOwner()->getUID();
1696
+    }
1697
+
1698
+    /**
1699
+     * get the ETag for a file or folder
1700
+     *
1701
+     * @param string $path
1702
+     * @return string
1703
+     */
1704
+    public function getETag($path) {
1705
+        /**
1706
+         * @var Storage\Storage $storage
1707
+         * @var string $internalPath
1708
+         */
1709
+        list($storage, $internalPath) = $this->resolvePath($path);
1710
+        if ($storage) {
1711
+            return $storage->getETag($internalPath);
1712
+        } else {
1713
+            return null;
1714
+        }
1715
+    }
1716
+
1717
+    /**
1718
+     * Get the path of a file by id, relative to the view
1719
+     *
1720
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1721
+     *
1722
+     * @param int $id
1723
+     * @throws NotFoundException
1724
+     * @return string
1725
+     */
1726
+    public function getPath($id) {
1727
+        $id = (int)$id;
1728
+        $manager = Filesystem::getMountManager();
1729
+        $mounts = $manager->findIn($this->fakeRoot);
1730
+        $mounts[] = $manager->find($this->fakeRoot);
1731
+        // reverse the array so we start with the storage this view is in
1732
+        // which is the most likely to contain the file we're looking for
1733
+        $mounts = array_reverse($mounts);
1734
+
1735
+        // put non shared mounts in front of the shared mount
1736
+        // this prevent unneeded recursion into shares
1737
+        usort($mounts, function(IMountPoint $a, IMountPoint $b) {
1738
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1739
+        });
1740
+
1741
+        foreach ($mounts as $mount) {
1742
+            /**
1743
+             * @var \OC\Files\Mount\MountPoint $mount
1744
+             */
1745
+            if ($mount->getStorage()) {
1746
+                $cache = $mount->getStorage()->getCache();
1747
+                $internalPath = $cache->getPathById($id);
1748
+                if (is_string($internalPath)) {
1749
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1750
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1751
+                        return $path;
1752
+                    }
1753
+                }
1754
+            }
1755
+        }
1756
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1757
+    }
1758
+
1759
+    /**
1760
+     * @param string $path
1761
+     * @throws InvalidPathException
1762
+     */
1763
+    private function assertPathLength($path) {
1764
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1765
+        // Check for the string length - performed using isset() instead of strlen()
1766
+        // because isset() is about 5x-40x faster.
1767
+        if (isset($path[$maxLen])) {
1768
+            $pathLen = strlen($path);
1769
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1770
+        }
1771
+    }
1772
+
1773
+    /**
1774
+     * check if it is allowed to move a mount point to a given target.
1775
+     * It is not allowed to move a mount point into a different mount point or
1776
+     * into an already shared folder
1777
+     *
1778
+     * @param IStorage $targetStorage
1779
+     * @param string $targetInternalPath
1780
+     * @return boolean
1781
+     */
1782
+    private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1783
+
1784
+        // note: cannot use the view because the target is already locked
1785
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1786
+        if ($fileId === -1) {
1787
+            // target might not exist, need to check parent instead
1788
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1789
+        }
1790
+
1791
+        // check if any of the parents were shared by the current owner (include collections)
1792
+        $shares = \OCP\Share::getItemShared(
1793
+            'folder',
1794
+            $fileId,
1795
+            \OCP\Share::FORMAT_NONE,
1796
+            null,
1797
+            true
1798
+        );
1799
+
1800
+        if (count($shares) > 0) {
1801
+            \OCP\Util::writeLog('files',
1802
+                'It is not allowed to move one mount point into a shared folder',
1803
+                ILogger::DEBUG);
1804
+            return false;
1805
+        }
1806
+
1807
+        return true;
1808
+    }
1809
+
1810
+    /**
1811
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1812
+     *
1813
+     * @param string $path
1814
+     * @return \OCP\Files\FileInfo
1815
+     */
1816
+    private function getPartFileInfo($path) {
1817
+        $mount = $this->getMount($path);
1818
+        $storage = $mount->getStorage();
1819
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1820
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1821
+        return new FileInfo(
1822
+            $this->getAbsolutePath($path),
1823
+            $storage,
1824
+            $internalPath,
1825
+            [
1826
+                'fileid' => null,
1827
+                'mimetype' => $storage->getMimeType($internalPath),
1828
+                'name' => basename($path),
1829
+                'etag' => null,
1830
+                'size' => $storage->filesize($internalPath),
1831
+                'mtime' => $storage->filemtime($internalPath),
1832
+                'encrypted' => false,
1833
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1834
+            ],
1835
+            $mount,
1836
+            $owner
1837
+        );
1838
+    }
1839
+
1840
+    /**
1841
+     * @param string $path
1842
+     * @param string $fileName
1843
+     * @throws InvalidPathException
1844
+     */
1845
+    public function verifyPath($path, $fileName) {
1846
+        try {
1847
+            /** @type \OCP\Files\Storage $storage */
1848
+            list($storage, $internalPath) = $this->resolvePath($path);
1849
+            $storage->verifyPath($internalPath, $fileName);
1850
+        } catch (ReservedWordException $ex) {
1851
+            $l = \OC::$server->getL10N('lib');
1852
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1853
+        } catch (InvalidCharacterInPathException $ex) {
1854
+            $l = \OC::$server->getL10N('lib');
1855
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1856
+        } catch (FileNameTooLongException $ex) {
1857
+            $l = \OC::$server->getL10N('lib');
1858
+            throw new InvalidPathException($l->t('File name is too long'));
1859
+        } catch (InvalidDirectoryException $ex) {
1860
+            $l = \OC::$server->getL10N('lib');
1861
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1862
+        } catch (EmptyFileNameException $ex) {
1863
+            $l = \OC::$server->getL10N('lib');
1864
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1865
+        }
1866
+    }
1867
+
1868
+    /**
1869
+     * get all parent folders of $path
1870
+     *
1871
+     * @param string $path
1872
+     * @return string[]
1873
+     */
1874
+    private function getParents($path) {
1875
+        $path = trim($path, '/');
1876
+        if (!$path) {
1877
+            return [];
1878
+        }
1879
+
1880
+        $parts = explode('/', $path);
1881
+
1882
+        // remove the single file
1883
+        array_pop($parts);
1884
+        $result = ['/'];
1885
+        $resultPath = '';
1886
+        foreach ($parts as $part) {
1887
+            if ($part) {
1888
+                $resultPath .= '/' . $part;
1889
+                $result[] = $resultPath;
1890
+            }
1891
+        }
1892
+        return $result;
1893
+    }
1894
+
1895
+    /**
1896
+     * Returns the mount point for which to lock
1897
+     *
1898
+     * @param string $absolutePath absolute path
1899
+     * @param bool $useParentMount true to return parent mount instead of whatever
1900
+     * is mounted directly on the given path, false otherwise
1901
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1902
+     */
1903
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1904
+        $results = [];
1905
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1906
+        if (!$mount) {
1907
+            return $results;
1908
+        }
1909
+
1910
+        if ($useParentMount) {
1911
+            // find out if something is mounted directly on the path
1912
+            $internalPath = $mount->getInternalPath($absolutePath);
1913
+            if ($internalPath === '') {
1914
+                // resolve the parent mount instead
1915
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1916
+            }
1917
+        }
1918
+
1919
+        return $mount;
1920
+    }
1921
+
1922
+    /**
1923
+     * Lock the given path
1924
+     *
1925
+     * @param string $path the path of the file to lock, relative to the view
1926
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1927
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1928
+     *
1929
+     * @return bool False if the path is excluded from locking, true otherwise
1930
+     * @throws LockedException if the path is already locked
1931
+     */
1932
+    private function lockPath($path, $type, $lockMountPoint = false) {
1933
+        $absolutePath = $this->getAbsolutePath($path);
1934
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1935
+        if (!$this->shouldLockFile($absolutePath)) {
1936
+            return false;
1937
+        }
1938
+
1939
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1940
+        if ($mount) {
1941
+            try {
1942
+                $storage = $mount->getStorage();
1943
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1944
+                    $storage->acquireLock(
1945
+                        $mount->getInternalPath($absolutePath),
1946
+                        $type,
1947
+                        $this->lockingProvider
1948
+                    );
1949
+                }
1950
+            } catch (LockedException $e) {
1951
+                // rethrow with the a human-readable path
1952
+                throw new LockedException(
1953
+                    $this->getPathRelativeToFiles($absolutePath),
1954
+                    $e,
1955
+                    $e->getExistingLock()
1956
+                );
1957
+            }
1958
+        }
1959
+
1960
+        return true;
1961
+    }
1962
+
1963
+    /**
1964
+     * Change the lock type
1965
+     *
1966
+     * @param string $path the path of the file to lock, relative to the view
1967
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1968
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1969
+     *
1970
+     * @return bool False if the path is excluded from locking, true otherwise
1971
+     * @throws LockedException if the path is already locked
1972
+     */
1973
+    public function changeLock($path, $type, $lockMountPoint = false) {
1974
+        $path = Filesystem::normalizePath($path);
1975
+        $absolutePath = $this->getAbsolutePath($path);
1976
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1977
+        if (!$this->shouldLockFile($absolutePath)) {
1978
+            return false;
1979
+        }
1980
+
1981
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1982
+        if ($mount) {
1983
+            try {
1984
+                $storage = $mount->getStorage();
1985
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1986
+                    $storage->changeLock(
1987
+                        $mount->getInternalPath($absolutePath),
1988
+                        $type,
1989
+                        $this->lockingProvider
1990
+                    );
1991
+                }
1992
+            } catch (LockedException $e) {
1993
+                try {
1994
+                    // rethrow with the a human-readable path
1995
+                    throw new LockedException(
1996
+                        $this->getPathRelativeToFiles($absolutePath),
1997
+                        $e,
1998
+                        $e->getExistingLock()
1999
+                    );
2000
+                } catch (\InvalidArgumentException $ex) {
2001
+                    throw new LockedException(
2002
+                        $absolutePath,
2003
+                        $ex,
2004
+                        $e->getExistingLock()
2005
+                    );
2006
+                }
2007
+            }
2008
+        }
2009
+
2010
+        return true;
2011
+    }
2012
+
2013
+    /**
2014
+     * Unlock the given path
2015
+     *
2016
+     * @param string $path the path of the file to unlock, relative to the view
2017
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2018
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2019
+     *
2020
+     * @return bool False if the path is excluded from locking, true otherwise
2021
+     * @throws LockedException
2022
+     */
2023
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2024
+        $absolutePath = $this->getAbsolutePath($path);
2025
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2026
+        if (!$this->shouldLockFile($absolutePath)) {
2027
+            return false;
2028
+        }
2029
+
2030
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2031
+        if ($mount) {
2032
+            $storage = $mount->getStorage();
2033
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2034
+                $storage->releaseLock(
2035
+                    $mount->getInternalPath($absolutePath),
2036
+                    $type,
2037
+                    $this->lockingProvider
2038
+                );
2039
+            }
2040
+        }
2041
+
2042
+        return true;
2043
+    }
2044
+
2045
+    /**
2046
+     * Lock a path and all its parents up to the root of the view
2047
+     *
2048
+     * @param string $path the path of the file to lock relative to the view
2049
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2050
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2051
+     *
2052
+     * @return bool False if the path is excluded from locking, true otherwise
2053
+     * @throws LockedException
2054
+     */
2055
+    public function lockFile($path, $type, $lockMountPoint = false) {
2056
+        $absolutePath = $this->getAbsolutePath($path);
2057
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2058
+        if (!$this->shouldLockFile($absolutePath)) {
2059
+            return false;
2060
+        }
2061
+
2062
+        $this->lockPath($path, $type, $lockMountPoint);
2063
+
2064
+        $parents = $this->getParents($path);
2065
+        foreach ($parents as $parent) {
2066
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2067
+        }
2068
+
2069
+        return true;
2070
+    }
2071
+
2072
+    /**
2073
+     * Unlock a path and all its parents up to the root of the view
2074
+     *
2075
+     * @param string $path the path of the file to lock relative to the view
2076
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2077
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2078
+     *
2079
+     * @return bool False if the path is excluded from locking, true otherwise
2080
+     * @throws LockedException
2081
+     */
2082
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2083
+        $absolutePath = $this->getAbsolutePath($path);
2084
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2085
+        if (!$this->shouldLockFile($absolutePath)) {
2086
+            return false;
2087
+        }
2088
+
2089
+        $this->unlockPath($path, $type, $lockMountPoint);
2090
+
2091
+        $parents = $this->getParents($path);
2092
+        foreach ($parents as $parent) {
2093
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2094
+        }
2095
+
2096
+        return true;
2097
+    }
2098
+
2099
+    /**
2100
+     * Only lock files in data/user/files/
2101
+     *
2102
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2103
+     * @return bool
2104
+     */
2105
+    protected function shouldLockFile($path) {
2106
+        $path = Filesystem::normalizePath($path);
2107
+
2108
+        $pathSegments = explode('/', $path);
2109
+        if (isset($pathSegments[2])) {
2110
+            // E.g.: /username/files/path-to-file
2111
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2112
+        }
2113
+
2114
+        return strpos($path, '/appdata_') !== 0;
2115
+    }
2116
+
2117
+    /**
2118
+     * Shortens the given absolute path to be relative to
2119
+     * "$user/files".
2120
+     *
2121
+     * @param string $absolutePath absolute path which is under "files"
2122
+     *
2123
+     * @return string path relative to "files" with trimmed slashes or null
2124
+     * if the path was NOT relative to files
2125
+     *
2126
+     * @throws \InvalidArgumentException if the given path was not under "files"
2127
+     * @since 8.1.0
2128
+     */
2129
+    public function getPathRelativeToFiles($absolutePath) {
2130
+        $path = Filesystem::normalizePath($absolutePath);
2131
+        $parts = explode('/', trim($path, '/'), 3);
2132
+        // "$user", "files", "path/to/dir"
2133
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2134
+            $this->logger->error(
2135
+                '$absolutePath must be relative to "files", value is "%s"',
2136
+                [
2137
+                    $absolutePath
2138
+                ]
2139
+            );
2140
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2141
+        }
2142
+        if (isset($parts[2])) {
2143
+            return $parts[2];
2144
+        }
2145
+        return '';
2146
+    }
2147
+
2148
+    /**
2149
+     * @param string $filename
2150
+     * @return array
2151
+     * @throws \OC\User\NoUserException
2152
+     * @throws NotFoundException
2153
+     */
2154
+    public function getUidAndFilename($filename) {
2155
+        $info = $this->getFileInfo($filename);
2156
+        if (!$info instanceof \OCP\Files\FileInfo) {
2157
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2158
+        }
2159
+        $uid = $info->getOwner()->getUID();
2160
+        if ($uid != \OCP\User::getUser()) {
2161
+            Filesystem::initMountPoints($uid);
2162
+            $ownerView = new View('/' . $uid . '/files');
2163
+            try {
2164
+                $filename = $ownerView->getPath($info['fileid']);
2165
+            } catch (NotFoundException $e) {
2166
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2167
+            }
2168
+        }
2169
+        return [$uid, $filename];
2170
+    }
2171
+
2172
+    /**
2173
+     * Creates parent non-existing folders
2174
+     *
2175
+     * @param string $filePath
2176
+     * @return bool
2177
+     */
2178
+    private function createParentDirectories($filePath) {
2179
+        $directoryParts = explode('/', $filePath);
2180
+        $directoryParts = array_filter($directoryParts);
2181
+        foreach ($directoryParts as $key => $part) {
2182
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2183
+            $currentPath = '/' . implode('/', $currentPathElements);
2184
+            if ($this->is_file($currentPath)) {
2185
+                return false;
2186
+            }
2187
+            if (!$this->file_exists($currentPath)) {
2188
+                $this->mkdir($currentPath);
2189
+            }
2190
+        }
2191
+
2192
+        return true;
2193
+    }
2194 2194
 }
Please login to merge, or discard this patch.
lib/private/Files/Config/MountProviderCollection.php 1 patch
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -36,165 +36,165 @@
 block discarded – undo
36 36
 use OCP\IUser;
37 37
 
38 38
 class MountProviderCollection implements IMountProviderCollection, Emitter {
39
-	use EmitterTrait;
40
-
41
-	/**
42
-	 * @var \OCP\Files\Config\IHomeMountProvider[]
43
-	 */
44
-	private $homeProviders = [];
45
-
46
-	/**
47
-	 * @var \OCP\Files\Config\IMountProvider[]
48
-	 */
49
-	private $providers = [];
50
-
51
-	/**
52
-	 * @var \OCP\Files\Storage\IStorageFactory
53
-	 */
54
-	private $loader;
55
-
56
-	/**
57
-	 * @var \OCP\Files\Config\IUserMountCache
58
-	 */
59
-	private $mountCache;
60
-
61
-	/** @var callable[] */
62
-	private $mountFilters = [];
63
-
64
-	/**
65
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
66
-	 * @param IUserMountCache $mountCache
67
-	 */
68
-	public function __construct(IStorageFactory $loader, IUserMountCache $mountCache) {
69
-		$this->loader = $loader;
70
-		$this->mountCache = $mountCache;
71
-	}
72
-
73
-	/**
74
-	 * Get all configured mount points for the user
75
-	 *
76
-	 * @param \OCP\IUser $user
77
-	 * @return \OCP\Files\Mount\IMountPoint[]
78
-	 */
79
-	public function getMountsForUser(IUser $user) {
80
-		$loader = $this->loader;
81
-		$mounts = array_map(function (IMountProvider $provider) use ($user, $loader) {
82
-			return $provider->getMountsForUser($user, $loader);
83
-		}, $this->providers);
84
-		$mounts = array_filter($mounts, function ($result) {
85
-			return is_array($result);
86
-		});
87
-		$mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
88
-			return array_merge($mounts, $providerMounts);
89
-		}, []);
90
-		return $this->filterMounts($user, $mounts);
91
-	}
92
-
93
-	public function addMountForUser(IUser $user, IMountManager $mountManager) {
94
-		// shared mount provider gets to go last since it needs to know existing files
95
-		// to check for name collisions
96
-		$firstMounts = [];
97
-		$firstProviders = array_filter($this->providers, function (IMountProvider $provider) {
98
-			return (get_class($provider) !== 'OCA\Files_Sharing\MountProvider');
99
-		});
100
-		$lastProviders = array_filter($this->providers, function (IMountProvider $provider) {
101
-			return (get_class($provider) === 'OCA\Files_Sharing\MountProvider');
102
-		});
103
-		foreach ($firstProviders as $provider) {
104
-			$mounts = $provider->getMountsForUser($user, $this->loader);
105
-			if (is_array($mounts)) {
106
-				$firstMounts = array_merge($firstMounts, $mounts);
107
-			}
108
-		}
109
-		$firstMounts = $this->filterMounts($user, $firstMounts);
110
-		array_walk($firstMounts, [$mountManager, 'addMount']);
111
-
112
-		$lateMounts = [];
113
-		foreach ($lastProviders as $provider) {
114
-			$mounts = $provider->getMountsForUser($user, $this->loader);
115
-			if (is_array($mounts)) {
116
-				$lateMounts = array_merge($lateMounts, $mounts);
117
-			}
118
-		}
119
-
120
-		$lateMounts = $this->filterMounts($user, $lateMounts);
121
-		array_walk($lateMounts, [$mountManager, 'addMount']);
122
-
123
-		return array_merge($lateMounts, $firstMounts);
124
-	}
125
-
126
-	/**
127
-	 * Get the configured home mount for this user
128
-	 *
129
-	 * @param \OCP\IUser $user
130
-	 * @return \OCP\Files\Mount\IMountPoint
131
-	 * @since 9.1.0
132
-	 */
133
-	public function getHomeMountForUser(IUser $user) {
134
-		/** @var \OCP\Files\Config\IHomeMountProvider[] $providers */
135
-		$providers = array_reverse($this->homeProviders); // call the latest registered provider first to give apps an opportunity to overwrite builtin
136
-		foreach ($providers as $homeProvider) {
137
-			if ($mount = $homeProvider->getHomeMountForUser($user, $this->loader)) {
138
-				$mount->setMountPoint('/' . $user->getUID()); //make sure the mountpoint is what we expect
139
-				return $mount;
140
-			}
141
-		}
142
-		throw new \Exception('No home storage configured for user ' . $user);
143
-	}
144
-
145
-	/**
146
-	 * Add a provider for mount points
147
-	 *
148
-	 * @param \OCP\Files\Config\IMountProvider $provider
149
-	 */
150
-	public function registerProvider(IMountProvider $provider) {
151
-		$this->providers[] = $provider;
152
-
153
-		$this->emit('\OC\Files\Config', 'registerMountProvider', [$provider]);
154
-	}
155
-
156
-	public function registerMountFilter(callable $filter) {
157
-		$this->mountFilters[] = $filter;
158
-	}
159
-
160
-	private function filterMounts(IUser $user, array $mountPoints) {
161
-		return array_filter($mountPoints, function (IMountPoint $mountPoint) use ($user) {
162
-			foreach ($this->mountFilters as $filter) {
163
-				if ($filter($mountPoint, $user) === false) {
164
-					return false;
165
-				}
166
-			}
167
-			return true;
168
-		});
169
-	}
170
-
171
-	/**
172
-	 * Add a provider for home mount points
173
-	 *
174
-	 * @param \OCP\Files\Config\IHomeMountProvider $provider
175
-	 * @since 9.1.0
176
-	 */
177
-	public function registerHomeProvider(IHomeMountProvider $provider) {
178
-		$this->homeProviders[] = $provider;
179
-		$this->emit('\OC\Files\Config', 'registerHomeMountProvider', [$provider]);
180
-	}
181
-
182
-	/**
183
-	 * Cache mounts for user
184
-	 *
185
-	 * @param IUser $user
186
-	 * @param IMountPoint[] $mountPoints
187
-	 */
188
-	public function registerMounts(IUser $user, array $mountPoints) {
189
-		$this->mountCache->registerMounts($user, $mountPoints);
190
-	}
191
-
192
-	/**
193
-	 * Get the mount cache which can be used to search for mounts without setting up the filesystem
194
-	 *
195
-	 * @return IUserMountCache
196
-	 */
197
-	public function getMountCache() {
198
-		return $this->mountCache;
199
-	}
39
+    use EmitterTrait;
40
+
41
+    /**
42
+     * @var \OCP\Files\Config\IHomeMountProvider[]
43
+     */
44
+    private $homeProviders = [];
45
+
46
+    /**
47
+     * @var \OCP\Files\Config\IMountProvider[]
48
+     */
49
+    private $providers = [];
50
+
51
+    /**
52
+     * @var \OCP\Files\Storage\IStorageFactory
53
+     */
54
+    private $loader;
55
+
56
+    /**
57
+     * @var \OCP\Files\Config\IUserMountCache
58
+     */
59
+    private $mountCache;
60
+
61
+    /** @var callable[] */
62
+    private $mountFilters = [];
63
+
64
+    /**
65
+     * @param \OCP\Files\Storage\IStorageFactory $loader
66
+     * @param IUserMountCache $mountCache
67
+     */
68
+    public function __construct(IStorageFactory $loader, IUserMountCache $mountCache) {
69
+        $this->loader = $loader;
70
+        $this->mountCache = $mountCache;
71
+    }
72
+
73
+    /**
74
+     * Get all configured mount points for the user
75
+     *
76
+     * @param \OCP\IUser $user
77
+     * @return \OCP\Files\Mount\IMountPoint[]
78
+     */
79
+    public function getMountsForUser(IUser $user) {
80
+        $loader = $this->loader;
81
+        $mounts = array_map(function (IMountProvider $provider) use ($user, $loader) {
82
+            return $provider->getMountsForUser($user, $loader);
83
+        }, $this->providers);
84
+        $mounts = array_filter($mounts, function ($result) {
85
+            return is_array($result);
86
+        });
87
+        $mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
88
+            return array_merge($mounts, $providerMounts);
89
+        }, []);
90
+        return $this->filterMounts($user, $mounts);
91
+    }
92
+
93
+    public function addMountForUser(IUser $user, IMountManager $mountManager) {
94
+        // shared mount provider gets to go last since it needs to know existing files
95
+        // to check for name collisions
96
+        $firstMounts = [];
97
+        $firstProviders = array_filter($this->providers, function (IMountProvider $provider) {
98
+            return (get_class($provider) !== 'OCA\Files_Sharing\MountProvider');
99
+        });
100
+        $lastProviders = array_filter($this->providers, function (IMountProvider $provider) {
101
+            return (get_class($provider) === 'OCA\Files_Sharing\MountProvider');
102
+        });
103
+        foreach ($firstProviders as $provider) {
104
+            $mounts = $provider->getMountsForUser($user, $this->loader);
105
+            if (is_array($mounts)) {
106
+                $firstMounts = array_merge($firstMounts, $mounts);
107
+            }
108
+        }
109
+        $firstMounts = $this->filterMounts($user, $firstMounts);
110
+        array_walk($firstMounts, [$mountManager, 'addMount']);
111
+
112
+        $lateMounts = [];
113
+        foreach ($lastProviders as $provider) {
114
+            $mounts = $provider->getMountsForUser($user, $this->loader);
115
+            if (is_array($mounts)) {
116
+                $lateMounts = array_merge($lateMounts, $mounts);
117
+            }
118
+        }
119
+
120
+        $lateMounts = $this->filterMounts($user, $lateMounts);
121
+        array_walk($lateMounts, [$mountManager, 'addMount']);
122
+
123
+        return array_merge($lateMounts, $firstMounts);
124
+    }
125
+
126
+    /**
127
+     * Get the configured home mount for this user
128
+     *
129
+     * @param \OCP\IUser $user
130
+     * @return \OCP\Files\Mount\IMountPoint
131
+     * @since 9.1.0
132
+     */
133
+    public function getHomeMountForUser(IUser $user) {
134
+        /** @var \OCP\Files\Config\IHomeMountProvider[] $providers */
135
+        $providers = array_reverse($this->homeProviders); // call the latest registered provider first to give apps an opportunity to overwrite builtin
136
+        foreach ($providers as $homeProvider) {
137
+            if ($mount = $homeProvider->getHomeMountForUser($user, $this->loader)) {
138
+                $mount->setMountPoint('/' . $user->getUID()); //make sure the mountpoint is what we expect
139
+                return $mount;
140
+            }
141
+        }
142
+        throw new \Exception('No home storage configured for user ' . $user);
143
+    }
144
+
145
+    /**
146
+     * Add a provider for mount points
147
+     *
148
+     * @param \OCP\Files\Config\IMountProvider $provider
149
+     */
150
+    public function registerProvider(IMountProvider $provider) {
151
+        $this->providers[] = $provider;
152
+
153
+        $this->emit('\OC\Files\Config', 'registerMountProvider', [$provider]);
154
+    }
155
+
156
+    public function registerMountFilter(callable $filter) {
157
+        $this->mountFilters[] = $filter;
158
+    }
159
+
160
+    private function filterMounts(IUser $user, array $mountPoints) {
161
+        return array_filter($mountPoints, function (IMountPoint $mountPoint) use ($user) {
162
+            foreach ($this->mountFilters as $filter) {
163
+                if ($filter($mountPoint, $user) === false) {
164
+                    return false;
165
+                }
166
+            }
167
+            return true;
168
+        });
169
+    }
170
+
171
+    /**
172
+     * Add a provider for home mount points
173
+     *
174
+     * @param \OCP\Files\Config\IHomeMountProvider $provider
175
+     * @since 9.1.0
176
+     */
177
+    public function registerHomeProvider(IHomeMountProvider $provider) {
178
+        $this->homeProviders[] = $provider;
179
+        $this->emit('\OC\Files\Config', 'registerHomeMountProvider', [$provider]);
180
+    }
181
+
182
+    /**
183
+     * Cache mounts for user
184
+     *
185
+     * @param IUser $user
186
+     * @param IMountPoint[] $mountPoints
187
+     */
188
+    public function registerMounts(IUser $user, array $mountPoints) {
189
+        $this->mountCache->registerMounts($user, $mountPoints);
190
+    }
191
+
192
+    /**
193
+     * Get the mount cache which can be used to search for mounts without setting up the filesystem
194
+     *
195
+     * @return IUserMountCache
196
+     */
197
+    public function getMountCache() {
198
+        return $this->mountCache;
199
+    }
200 200
 }
Please login to merge, or discard this patch.
lib/private/Files/Mount/MountPoint.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -37,247 +37,247 @@
 block discarded – undo
37 37
 use OCP\ILogger;
38 38
 
39 39
 class MountPoint implements IMountPoint {
40
-	/**
41
-	 * @var \OC\Files\Storage\Storage $storage
42
-	 */
43
-	protected $storage = null;
44
-	protected $class;
45
-	protected $storageId;
46
-	protected $rootId = null;
40
+    /**
41
+     * @var \OC\Files\Storage\Storage $storage
42
+     */
43
+    protected $storage = null;
44
+    protected $class;
45
+    protected $storageId;
46
+    protected $rootId = null;
47 47
 
48
-	/**
49
-	 * Configuration options for the storage backend
50
-	 *
51
-	 * @var array
52
-	 */
53
-	protected $arguments = [];
54
-	protected $mountPoint;
48
+    /**
49
+     * Configuration options for the storage backend
50
+     *
51
+     * @var array
52
+     */
53
+    protected $arguments = [];
54
+    protected $mountPoint;
55 55
 
56
-	/**
57
-	 * Mount specific options
58
-	 *
59
-	 * @var array
60
-	 */
61
-	protected $mountOptions = [];
56
+    /**
57
+     * Mount specific options
58
+     *
59
+     * @var array
60
+     */
61
+    protected $mountOptions = [];
62 62
 
63
-	/**
64
-	 * @var \OC\Files\Storage\StorageFactory $loader
65
-	 */
66
-	private $loader;
63
+    /**
64
+     * @var \OC\Files\Storage\StorageFactory $loader
65
+     */
66
+    private $loader;
67 67
 
68
-	/**
69
-	 * Specified whether the storage is invalid after failing to
70
-	 * instantiate it.
71
-	 *
72
-	 * @var bool
73
-	 */
74
-	private $invalidStorage = false;
68
+    /**
69
+     * Specified whether the storage is invalid after failing to
70
+     * instantiate it.
71
+     *
72
+     * @var bool
73
+     */
74
+    private $invalidStorage = false;
75 75
 
76
-	/** @var int|null */
77
-	protected $mountId;
76
+    /** @var int|null */
77
+    protected $mountId;
78 78
 
79
-	/**
80
-	 * @param string|\OC\Files\Storage\Storage $storage
81
-	 * @param string $mountpoint
82
-	 * @param array $arguments (optional) configuration for the storage backend
83
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
84
-	 * @param array $mountOptions mount specific options
85
-	 * @param int|null $mountId
86
-	 * @throws \Exception
87
-	 */
88
-	public function __construct($storage, $mountpoint, $arguments = null, $loader = null, $mountOptions = null, $mountId = null) {
89
-		if (is_null($arguments)) {
90
-			$arguments = [];
91
-		}
92
-		if (is_null($loader)) {
93
-			$this->loader = new StorageFactory();
94
-		} else {
95
-			$this->loader = $loader;
96
-		}
79
+    /**
80
+     * @param string|\OC\Files\Storage\Storage $storage
81
+     * @param string $mountpoint
82
+     * @param array $arguments (optional) configuration for the storage backend
83
+     * @param \OCP\Files\Storage\IStorageFactory $loader
84
+     * @param array $mountOptions mount specific options
85
+     * @param int|null $mountId
86
+     * @throws \Exception
87
+     */
88
+    public function __construct($storage, $mountpoint, $arguments = null, $loader = null, $mountOptions = null, $mountId = null) {
89
+        if (is_null($arguments)) {
90
+            $arguments = [];
91
+        }
92
+        if (is_null($loader)) {
93
+            $this->loader = new StorageFactory();
94
+        } else {
95
+            $this->loader = $loader;
96
+        }
97 97
 
98
-		if (!is_null($mountOptions)) {
99
-			$this->mountOptions = $mountOptions;
100
-		}
98
+        if (!is_null($mountOptions)) {
99
+            $this->mountOptions = $mountOptions;
100
+        }
101 101
 
102
-		$mountpoint = $this->formatPath($mountpoint);
103
-		$this->mountPoint = $mountpoint;
104
-		if ($storage instanceof Storage) {
105
-			$this->class = get_class($storage);
106
-			$this->storage = $this->loader->wrap($this, $storage);
107
-		} else {
108
-			// Update old classes to new namespace
109
-			if (strpos($storage, 'OC_Filestorage_') !== false) {
110
-				$storage = '\OC\Files\Storage\\' . substr($storage, 15);
111
-			}
112
-			$this->class = $storage;
113
-			$this->arguments = $arguments;
114
-		}
115
-		$this->mountId = $mountId;
116
-	}
102
+        $mountpoint = $this->formatPath($mountpoint);
103
+        $this->mountPoint = $mountpoint;
104
+        if ($storage instanceof Storage) {
105
+            $this->class = get_class($storage);
106
+            $this->storage = $this->loader->wrap($this, $storage);
107
+        } else {
108
+            // Update old classes to new namespace
109
+            if (strpos($storage, 'OC_Filestorage_') !== false) {
110
+                $storage = '\OC\Files\Storage\\' . substr($storage, 15);
111
+            }
112
+            $this->class = $storage;
113
+            $this->arguments = $arguments;
114
+        }
115
+        $this->mountId = $mountId;
116
+    }
117 117
 
118
-	/**
119
-	 * get complete path to the mount point, relative to data/
120
-	 *
121
-	 * @return string
122
-	 */
123
-	public function getMountPoint() {
124
-		return $this->mountPoint;
125
-	}
118
+    /**
119
+     * get complete path to the mount point, relative to data/
120
+     *
121
+     * @return string
122
+     */
123
+    public function getMountPoint() {
124
+        return $this->mountPoint;
125
+    }
126 126
 
127
-	/**
128
-	 * Sets the mount point path, relative to data/
129
-	 *
130
-	 * @param string $mountPoint new mount point
131
-	 */
132
-	public function setMountPoint($mountPoint) {
133
-		$this->mountPoint = $this->formatPath($mountPoint);
134
-	}
127
+    /**
128
+     * Sets the mount point path, relative to data/
129
+     *
130
+     * @param string $mountPoint new mount point
131
+     */
132
+    public function setMountPoint($mountPoint) {
133
+        $this->mountPoint = $this->formatPath($mountPoint);
134
+    }
135 135
 
136
-	/**
137
-	 * create the storage that is mounted
138
-	 */
139
-	private function createStorage() {
140
-		if ($this->invalidStorage) {
141
-			return;
142
-		}
136
+    /**
137
+     * create the storage that is mounted
138
+     */
139
+    private function createStorage() {
140
+        if ($this->invalidStorage) {
141
+            return;
142
+        }
143 143
 
144
-		if (class_exists($this->class)) {
145
-			try {
146
-				$class = $this->class;
147
-				// prevent recursion by setting the storage before applying wrappers
148
-				$this->storage = new $class($this->arguments);
149
-				$this->storage = $this->loader->wrap($this, $this->storage);
150
-			} catch (\Exception $exception) {
151
-				$this->storage = null;
152
-				$this->invalidStorage = true;
153
-				if ($this->mountPoint === '/') {
154
-					// the root storage could not be initialized, show the user!
155
-					throw new \Exception('The root storage could not be initialized. Please contact your local administrator.', $exception->getCode(), $exception);
156
-				} else {
157
-					\OC::$server->getLogger()->logException($exception, ['level' => ILogger::ERROR]);
158
-				}
159
-				return;
160
-			}
161
-		} else {
162
-			\OCP\Util::writeLog('core', 'storage backend ' . $this->class . ' not found', ILogger::ERROR);
163
-			$this->invalidStorage = true;
164
-			return;
165
-		}
166
-	}
144
+        if (class_exists($this->class)) {
145
+            try {
146
+                $class = $this->class;
147
+                // prevent recursion by setting the storage before applying wrappers
148
+                $this->storage = new $class($this->arguments);
149
+                $this->storage = $this->loader->wrap($this, $this->storage);
150
+            } catch (\Exception $exception) {
151
+                $this->storage = null;
152
+                $this->invalidStorage = true;
153
+                if ($this->mountPoint === '/') {
154
+                    // the root storage could not be initialized, show the user!
155
+                    throw new \Exception('The root storage could not be initialized. Please contact your local administrator.', $exception->getCode(), $exception);
156
+                } else {
157
+                    \OC::$server->getLogger()->logException($exception, ['level' => ILogger::ERROR]);
158
+                }
159
+                return;
160
+            }
161
+        } else {
162
+            \OCP\Util::writeLog('core', 'storage backend ' . $this->class . ' not found', ILogger::ERROR);
163
+            $this->invalidStorage = true;
164
+            return;
165
+        }
166
+    }
167 167
 
168
-	/**
169
-	 * @return \OC\Files\Storage\Storage
170
-	 */
171
-	public function getStorage() {
172
-		if (is_null($this->storage)) {
173
-			$this->createStorage();
174
-		}
175
-		return $this->storage;
176
-	}
168
+    /**
169
+     * @return \OC\Files\Storage\Storage
170
+     */
171
+    public function getStorage() {
172
+        if (is_null($this->storage)) {
173
+            $this->createStorage();
174
+        }
175
+        return $this->storage;
176
+    }
177 177
 
178
-	/**
179
-	 * @return string
180
-	 */
181
-	public function getStorageId() {
182
-		if (!$this->storageId) {
183
-			if (is_null($this->storage)) {
184
-				$storage = $this->createStorage(); //FIXME: start using exceptions
185
-				if (is_null($storage)) {
186
-					return null;
187
-				}
178
+    /**
179
+     * @return string
180
+     */
181
+    public function getStorageId() {
182
+        if (!$this->storageId) {
183
+            if (is_null($this->storage)) {
184
+                $storage = $this->createStorage(); //FIXME: start using exceptions
185
+                if (is_null($storage)) {
186
+                    return null;
187
+                }
188 188
 
189
-				$this->storage = $storage;
190
-			}
191
-			$this->storageId = $this->storage->getId();
192
-			if (strlen($this->storageId) > 64) {
193
-				$this->storageId = md5($this->storageId);
194
-			}
195
-		}
196
-		return $this->storageId;
197
-	}
189
+                $this->storage = $storage;
190
+            }
191
+            $this->storageId = $this->storage->getId();
192
+            if (strlen($this->storageId) > 64) {
193
+                $this->storageId = md5($this->storageId);
194
+            }
195
+        }
196
+        return $this->storageId;
197
+    }
198 198
 
199
-	/**
200
-	 * @return int
201
-	 */
202
-	public function getNumericStorageId() {
203
-		return $this->getStorage()->getStorageCache()->getNumericId();
204
-	}
199
+    /**
200
+     * @return int
201
+     */
202
+    public function getNumericStorageId() {
203
+        return $this->getStorage()->getStorageCache()->getNumericId();
204
+    }
205 205
 
206
-	/**
207
-	 * @param string $path
208
-	 * @return string
209
-	 */
210
-	public function getInternalPath($path) {
211
-		$path = Filesystem::normalizePath($path, true, false, true);
212
-		if ($this->mountPoint === $path or $this->mountPoint . '/' === $path) {
213
-			$internalPath = '';
214
-		} else {
215
-			$internalPath = substr($path, strlen($this->mountPoint));
216
-		}
217
-		// substr returns false instead of an empty string, we always want a string
218
-		return (string)$internalPath;
219
-	}
206
+    /**
207
+     * @param string $path
208
+     * @return string
209
+     */
210
+    public function getInternalPath($path) {
211
+        $path = Filesystem::normalizePath($path, true, false, true);
212
+        if ($this->mountPoint === $path or $this->mountPoint . '/' === $path) {
213
+            $internalPath = '';
214
+        } else {
215
+            $internalPath = substr($path, strlen($this->mountPoint));
216
+        }
217
+        // substr returns false instead of an empty string, we always want a string
218
+        return (string)$internalPath;
219
+    }
220 220
 
221
-	/**
222
-	 * @param string $path
223
-	 * @return string
224
-	 */
225
-	private function formatPath($path) {
226
-		$path = Filesystem::normalizePath($path);
227
-		if (strlen($path) > 1) {
228
-			$path .= '/';
229
-		}
230
-		return $path;
231
-	}
221
+    /**
222
+     * @param string $path
223
+     * @return string
224
+     */
225
+    private function formatPath($path) {
226
+        $path = Filesystem::normalizePath($path);
227
+        if (strlen($path) > 1) {
228
+            $path .= '/';
229
+        }
230
+        return $path;
231
+    }
232 232
 
233
-	/**
234
-	 * @param callable $wrapper
235
-	 */
236
-	public function wrapStorage($wrapper) {
237
-		$storage = $this->getStorage();
238
-		// storage can be null if it couldn't be initialized
239
-		if ($storage != null) {
240
-			$this->storage = $wrapper($this->mountPoint, $storage, $this);
241
-		}
242
-	}
233
+    /**
234
+     * @param callable $wrapper
235
+     */
236
+    public function wrapStorage($wrapper) {
237
+        $storage = $this->getStorage();
238
+        // storage can be null if it couldn't be initialized
239
+        if ($storage != null) {
240
+            $this->storage = $wrapper($this->mountPoint, $storage, $this);
241
+        }
242
+    }
243 243
 
244
-	/**
245
-	 * Get a mount option
246
-	 *
247
-	 * @param string $name Name of the mount option to get
248
-	 * @param mixed $default Default value for the mount option
249
-	 * @return mixed
250
-	 */
251
-	public function getOption($name, $default) {
252
-		return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default;
253
-	}
244
+    /**
245
+     * Get a mount option
246
+     *
247
+     * @param string $name Name of the mount option to get
248
+     * @param mixed $default Default value for the mount option
249
+     * @return mixed
250
+     */
251
+    public function getOption($name, $default) {
252
+        return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default;
253
+    }
254 254
 
255
-	/**
256
-	 * Get all options for the mount
257
-	 *
258
-	 * @return array
259
-	 */
260
-	public function getOptions() {
261
-		return $this->mountOptions;
262
-	}
255
+    /**
256
+     * Get all options for the mount
257
+     *
258
+     * @return array
259
+     */
260
+    public function getOptions() {
261
+        return $this->mountOptions;
262
+    }
263 263
 
264
-	/**
265
-	 * Get the file id of the root of the storage
266
-	 *
267
-	 * @return int
268
-	 */
269
-	public function getStorageRootId() {
270
-		if (is_null($this->rootId)) {
271
-			$this->rootId = (int)$this->getStorage()->getCache()->getId('');
272
-		}
273
-		return $this->rootId;
274
-	}
264
+    /**
265
+     * Get the file id of the root of the storage
266
+     *
267
+     * @return int
268
+     */
269
+    public function getStorageRootId() {
270
+        if (is_null($this->rootId)) {
271
+            $this->rootId = (int)$this->getStorage()->getCache()->getId('');
272
+        }
273
+        return $this->rootId;
274
+    }
275 275
 
276
-	public function getMountId() {
277
-		return $this->mountId;
278
-	}
276
+    public function getMountId() {
277
+        return $this->mountId;
278
+    }
279 279
 
280
-	public function getMountType() {
281
-		return '';
282
-	}
280
+    public function getMountType() {
281
+        return '';
282
+    }
283 283
 }
Please login to merge, or discard this patch.
lib/private/Files/ObjectStore/S3ConnectionTrait.php 1 patch
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -32,127 +32,127 @@
 block discarded – undo
32 32
 use OCP\ILogger;
33 33
 
34 34
 trait S3ConnectionTrait {
35
-	/** @var array */
36
-	protected $params;
37
-
38
-	/** @var S3Client */
39
-	protected $connection;
40
-
41
-	/** @var string */
42
-	protected $id;
43
-
44
-	/** @var string */
45
-	protected $bucket;
46
-
47
-	/** @var int */
48
-	protected $timeout;
49
-
50
-	protected $test;
51
-
52
-	protected function parseParams($params) {
53
-		if (empty($params['key']) || empty($params['secret']) || empty($params['bucket'])) {
54
-			throw new \Exception("Access Key, Secret and Bucket have to be configured.");
55
-		}
56
-
57
-		$this->id = 'amazon::' . $params['bucket'];
58
-
59
-		$this->test = isset($params['test']);
60
-		$this->bucket = $params['bucket'];
61
-		$this->timeout = !isset($params['timeout']) ? 15 : $params['timeout'];
62
-		$params['region'] = empty($params['region']) ? 'eu-west-1' : $params['region'];
63
-		$params['hostname'] = empty($params['hostname']) ? 's3.' . $params['region'] . '.amazonaws.com' : $params['hostname'];
64
-		if (!isset($params['port']) || $params['port'] === '') {
65
-			$params['port'] = (isset($params['use_ssl']) && $params['use_ssl'] === false) ? 80 : 443;
66
-		}
67
-		$this->params = $params;
68
-	}
69
-
70
-	public function getBucket() {
71
-		return $this->bucket;
72
-	}
73
-
74
-	/**
75
-	 * Returns the connection
76
-	 *
77
-	 * @return S3Client connected client
78
-	 * @throws \Exception if connection could not be made
79
-	 */
80
-	public function getConnection() {
81
-		if (!is_null($this->connection)) {
82
-			return $this->connection;
83
-		}
84
-
85
-		$scheme = (isset($this->params['use_ssl']) && $this->params['use_ssl'] === false) ? 'http' : 'https';
86
-		$base_url = $scheme . '://' . $this->params['hostname'] . ':' . $this->params['port'] . '/';
87
-
88
-		$options = [
89
-			'version' => isset($this->params['version']) ? $this->params['version'] : 'latest',
90
-			'credentials' => [
91
-				'key' => $this->params['key'],
92
-				'secret' => $this->params['secret'],
93
-			],
94
-			'endpoint' => $base_url,
95
-			'region' => $this->params['region'],
96
-			'use_path_style_endpoint' => isset($this->params['use_path_style']) ? $this->params['use_path_style'] : false,
97
-			'signature_provider' => \Aws\or_chain([self::class, 'legacySignatureProvider'], ClientResolver::_default_signature_provider())
98
-		];
99
-		if (isset($this->params['proxy'])) {
100
-			$options['request.options'] = ['proxy' => $this->params['proxy']];
101
-		}
102
-		if (isset($this->params['legacy_auth']) && $this->params['legacy_auth']) {
103
-			$options['signature_version'] = 'v2';
104
-		}
105
-		$this->connection = new S3Client($options);
106
-
107
-		if (!$this->connection->isBucketDnsCompatible($this->bucket)) {
108
-			$logger = \OC::$server->getLogger();
109
-			$logger->debug('Bucket "' . $this->bucket . '" This bucket name is not dns compatible, it may contain invalid characters.',
110
-					 ['app' => 'objectstore']);
111
-		}
112
-
113
-		if (!$this->connection->doesBucketExist($this->bucket)) {
114
-			$logger = \OC::$server->getLogger();
115
-			try {
116
-				$logger->info('Bucket "' . $this->bucket . '" does not exist - creating it.', ['app' => 'objectstore']);
117
-				if (!$this->connection->isBucketDnsCompatible($this->bucket)) {
118
-					throw new \Exception("The bucket will not be created because the name is not dns compatible, please correct it: " . $this->bucket);
119
-				}
120
-				$this->connection->createBucket(['Bucket' => $this->bucket]);
121
-				$this->testTimeout();
122
-			} catch (S3Exception $e) {
123
-				$logger->logException($e, [
124
-					'message' => 'Invalid remote storage.',
125
-					'level' => ILogger::DEBUG,
126
-					'app' => 'objectstore',
127
-				]);
128
-				throw new \Exception('Creation of bucket "' . $this->bucket . '" failed. ' . $e->getMessage());
129
-			}
130
-		}
131
-
132
-		// google cloud's s3 compatibility doesn't like the EncodingType parameter
133
-		if (strpos($base_url, 'storage.googleapis.com')) {
134
-			$this->connection->getHandlerList()->remove('s3.auto_encode');
135
-		}
136
-
137
-		return $this->connection;
138
-	}
139
-
140
-	/**
141
-	 * when running the tests wait to let the buckets catch up
142
-	 */
143
-	private function testTimeout() {
144
-		if ($this->test) {
145
-			sleep($this->timeout);
146
-		}
147
-	}
148
-
149
-	public static function legacySignatureProvider($version, $service, $region) {
150
-		switch ($version) {
151
-			case 'v2':
152
-			case 's3':
153
-				return new S3Signature();
154
-			default:
155
-				return null;
156
-		}
157
-	}
35
+    /** @var array */
36
+    protected $params;
37
+
38
+    /** @var S3Client */
39
+    protected $connection;
40
+
41
+    /** @var string */
42
+    protected $id;
43
+
44
+    /** @var string */
45
+    protected $bucket;
46
+
47
+    /** @var int */
48
+    protected $timeout;
49
+
50
+    protected $test;
51
+
52
+    protected function parseParams($params) {
53
+        if (empty($params['key']) || empty($params['secret']) || empty($params['bucket'])) {
54
+            throw new \Exception("Access Key, Secret and Bucket have to be configured.");
55
+        }
56
+
57
+        $this->id = 'amazon::' . $params['bucket'];
58
+
59
+        $this->test = isset($params['test']);
60
+        $this->bucket = $params['bucket'];
61
+        $this->timeout = !isset($params['timeout']) ? 15 : $params['timeout'];
62
+        $params['region'] = empty($params['region']) ? 'eu-west-1' : $params['region'];
63
+        $params['hostname'] = empty($params['hostname']) ? 's3.' . $params['region'] . '.amazonaws.com' : $params['hostname'];
64
+        if (!isset($params['port']) || $params['port'] === '') {
65
+            $params['port'] = (isset($params['use_ssl']) && $params['use_ssl'] === false) ? 80 : 443;
66
+        }
67
+        $this->params = $params;
68
+    }
69
+
70
+    public function getBucket() {
71
+        return $this->bucket;
72
+    }
73
+
74
+    /**
75
+     * Returns the connection
76
+     *
77
+     * @return S3Client connected client
78
+     * @throws \Exception if connection could not be made
79
+     */
80
+    public function getConnection() {
81
+        if (!is_null($this->connection)) {
82
+            return $this->connection;
83
+        }
84
+
85
+        $scheme = (isset($this->params['use_ssl']) && $this->params['use_ssl'] === false) ? 'http' : 'https';
86
+        $base_url = $scheme . '://' . $this->params['hostname'] . ':' . $this->params['port'] . '/';
87
+
88
+        $options = [
89
+            'version' => isset($this->params['version']) ? $this->params['version'] : 'latest',
90
+            'credentials' => [
91
+                'key' => $this->params['key'],
92
+                'secret' => $this->params['secret'],
93
+            ],
94
+            'endpoint' => $base_url,
95
+            'region' => $this->params['region'],
96
+            'use_path_style_endpoint' => isset($this->params['use_path_style']) ? $this->params['use_path_style'] : false,
97
+            'signature_provider' => \Aws\or_chain([self::class, 'legacySignatureProvider'], ClientResolver::_default_signature_provider())
98
+        ];
99
+        if (isset($this->params['proxy'])) {
100
+            $options['request.options'] = ['proxy' => $this->params['proxy']];
101
+        }
102
+        if (isset($this->params['legacy_auth']) && $this->params['legacy_auth']) {
103
+            $options['signature_version'] = 'v2';
104
+        }
105
+        $this->connection = new S3Client($options);
106
+
107
+        if (!$this->connection->isBucketDnsCompatible($this->bucket)) {
108
+            $logger = \OC::$server->getLogger();
109
+            $logger->debug('Bucket "' . $this->bucket . '" This bucket name is not dns compatible, it may contain invalid characters.',
110
+                        ['app' => 'objectstore']);
111
+        }
112
+
113
+        if (!$this->connection->doesBucketExist($this->bucket)) {
114
+            $logger = \OC::$server->getLogger();
115
+            try {
116
+                $logger->info('Bucket "' . $this->bucket . '" does not exist - creating it.', ['app' => 'objectstore']);
117
+                if (!$this->connection->isBucketDnsCompatible($this->bucket)) {
118
+                    throw new \Exception("The bucket will not be created because the name is not dns compatible, please correct it: " . $this->bucket);
119
+                }
120
+                $this->connection->createBucket(['Bucket' => $this->bucket]);
121
+                $this->testTimeout();
122
+            } catch (S3Exception $e) {
123
+                $logger->logException($e, [
124
+                    'message' => 'Invalid remote storage.',
125
+                    'level' => ILogger::DEBUG,
126
+                    'app' => 'objectstore',
127
+                ]);
128
+                throw new \Exception('Creation of bucket "' . $this->bucket . '" failed. ' . $e->getMessage());
129
+            }
130
+        }
131
+
132
+        // google cloud's s3 compatibility doesn't like the EncodingType parameter
133
+        if (strpos($base_url, 'storage.googleapis.com')) {
134
+            $this->connection->getHandlerList()->remove('s3.auto_encode');
135
+        }
136
+
137
+        return $this->connection;
138
+    }
139
+
140
+    /**
141
+     * when running the tests wait to let the buckets catch up
142
+     */
143
+    private function testTimeout() {
144
+        if ($this->test) {
145
+            sleep($this->timeout);
146
+        }
147
+    }
148
+
149
+    public static function legacySignatureProvider($version, $service, $region) {
150
+        switch ($version) {
151
+            case 'v2':
152
+            case 's3':
153
+                return new S3Signature();
154
+            default:
155
+                return null;
156
+        }
157
+    }
158 158
 }
Please login to merge, or discard this patch.
lib/private/Files/ObjectStore/NoopScanner.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -30,52 +30,52 @@
 block discarded – undo
30 30
 
31 31
 class NoopScanner extends Scanner {
32 32
 
33
-	public function __construct(Storage $storage) {
34
-		//we don't need the storage, so do nothing here
35
-	}
33
+    public function __construct(Storage $storage) {
34
+        //we don't need the storage, so do nothing here
35
+    }
36 36
 
37
-	/**
38
-	 * scan a single file and store it in the cache
39
-	 *
40
-	 * @param string $file
41
-	 * @param int $reuseExisting
42
-	 * @param int $parentId
43
-	 * @param array|null $cacheData existing data in the cache for the file to be scanned
44
-	 * @return array an array of metadata of the scanned file
45
-	 */
46
-	public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
47
-		return [];
48
-	}
37
+    /**
38
+     * scan a single file and store it in the cache
39
+     *
40
+     * @param string $file
41
+     * @param int $reuseExisting
42
+     * @param int $parentId
43
+     * @param array|null $cacheData existing data in the cache for the file to be scanned
44
+     * @return array an array of metadata of the scanned file
45
+     */
46
+    public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
47
+        return [];
48
+    }
49 49
 
50
-	/**
51
-	 * scan a folder and all it's children
52
-	 *
53
-	 * @param string $path
54
-	 * @param bool $recursive
55
-	 * @param int $reuse
56
-	 * @return array with the meta data of the scanned file or folder
57
-	 */
58
-	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
59
-		return [];
60
-	}
50
+    /**
51
+     * scan a folder and all it's children
52
+     *
53
+     * @param string $path
54
+     * @param bool $recursive
55
+     * @param int $reuse
56
+     * @return array with the meta data of the scanned file or folder
57
+     */
58
+    public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
59
+        return [];
60
+    }
61 61
 
62
-	/**
63
-	 * scan all the files and folders in a folder
64
-	 *
65
-	 * @param string $path
66
-	 * @param bool $recursive
67
-	 * @param int $reuse
68
-	 * @param array $folderData existing cache data for the folder to be scanned
69
-	 * @return int the size of the scanned folder or -1 if the size is unknown at this stage
70
-	 */
71
-	protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderData = null, $lock = true) {
72
-		return 0;
73
-	}
62
+    /**
63
+     * scan all the files and folders in a folder
64
+     *
65
+     * @param string $path
66
+     * @param bool $recursive
67
+     * @param int $reuse
68
+     * @param array $folderData existing cache data for the folder to be scanned
69
+     * @return int the size of the scanned folder or -1 if the size is unknown at this stage
70
+     */
71
+    protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderData = null, $lock = true) {
72
+        return 0;
73
+    }
74 74
 
75
-	/**
76
-	 * walk over any folders that are not fully scanned yet and scan them
77
-	 */
78
-	public function backgroundScan() {
79
-		//noop
80
-	}
75
+    /**
76
+     * walk over any folders that are not fully scanned yet and scan them
77
+     */
78
+    public function backgroundScan() {
79
+        //noop
80
+    }
81 81
 }
Please login to merge, or discard this patch.