Completed
Pull Request — master (#4524)
by Joas
13:17
created
apps/dav/lib/Connector/Sabre/FilesPlugin.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -448,7 +448,7 @@
 block discarded – undo
448 448
 	 *
449 449
 	 * @param string $path source path
450 450
 	 * @param string $destination destination path
451
-	 * @return bool|void false to stop handling, void to skip this handler
451
+	 * @return null|false false to stop handling, void to skip this handler
452 452
 	 */
453 453
 	public function beforeMoveFutureFile($path, $destination) {
454 454
 		$sourceNode = $this->tree->getNodeForPath($path);
Please login to merge, or discard this patch.
Indentation   +431 added lines, -431 removed lines patch added patch discarded remove patch
@@ -49,436 +49,436 @@
 block discarded – undo
49 49
 
50 50
 class FilesPlugin extends ServerPlugin {
51 51
 
52
-	// namespace
53
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
54
-	const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
55
-	const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
56
-	const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
57
-	const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
58
-	const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
59
-	const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
60
-	const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
61
-	const GETETAG_PROPERTYNAME = '{DAV:}getetag';
62
-	const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
63
-	const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
64
-	const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
65
-	const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
66
-	const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
67
-	const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
68
-
69
-	/**
70
-	 * Reference to main server object
71
-	 *
72
-	 * @var \Sabre\DAV\Server
73
-	 */
74
-	private $server;
75
-
76
-	/**
77
-	 * @var Tree
78
-	 */
79
-	private $tree;
80
-
81
-	/**
82
-	 * Whether this is public webdav.
83
-	 * If true, some returned information will be stripped off.
84
-	 *
85
-	 * @var bool
86
-	 */
87
-	private $isPublic;
88
-
89
-	/**
90
-	 * @var View
91
-	 */
92
-	private $fileView;
93
-
94
-	/**
95
-	 * @var bool
96
-	 */
97
-	private $downloadAttachment;
98
-
99
-	/**
100
-	 * @var IConfig
101
-	 */
102
-	private $config;
103
-
104
-	/**
105
-	 * @var IRequest
106
-	 */
107
-	private $request;
108
-
109
-	/**
110
-	 * @var IPreview
111
-	 */
112
-	private $previewManager;
113
-
114
-	/**
115
-	 * @param Tree $tree
116
-	 * @param IConfig $config
117
-	 * @param IRequest $request
118
-	 * @param IPreview $previewManager
119
-	 * @param bool $isPublic
120
-	 * @param bool $downloadAttachment
121
-	 */
122
-	public function __construct(Tree $tree,
123
-								IConfig $config,
124
-								IRequest $request,
125
-								IPreview $previewManager,
126
-								$isPublic = false,
127
-								$downloadAttachment = true) {
128
-		$this->tree = $tree;
129
-		$this->config = $config;
130
-		$this->request = $request;
131
-		$this->isPublic = $isPublic;
132
-		$this->downloadAttachment = $downloadAttachment;
133
-		$this->previewManager = $previewManager;
134
-	}
135
-
136
-	/**
137
-	 * This initializes the plugin.
138
-	 *
139
-	 * This function is called by \Sabre\DAV\Server, after
140
-	 * addPlugin is called.
141
-	 *
142
-	 * This method should set up the required event subscriptions.
143
-	 *
144
-	 * @param \Sabre\DAV\Server $server
145
-	 * @return void
146
-	 */
147
-	public function initialize(\Sabre\DAV\Server $server) {
148
-
149
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
150
-		$server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
151
-		$server->protectedProperties[] = self::FILEID_PROPERTYNAME;
152
-		$server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
153
-		$server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
154
-		$server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
155
-		$server->protectedProperties[] = self::SIZE_PROPERTYNAME;
156
-		$server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
157
-		$server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
158
-		$server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
159
-		$server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
160
-		$server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
161
-		$server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
162
-
163
-		// normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
164
-		$allowedProperties = ['{DAV:}getetag'];
165
-		$server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
166
-
167
-		$this->server = $server;
168
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
169
-		$this->server->on('propPatch', array($this, 'handleUpdateProperties'));
170
-		$this->server->on('afterBind', array($this, 'sendFileIdHeader'));
171
-		$this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
172
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
173
-		$this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
174
-		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
175
-			$body = $response->getBody();
176
-			if (is_resource($body)) {
177
-				fclose($body);
178
-			}
179
-		});
180
-		$this->server->on('beforeMove', [$this, 'checkMove']);
181
-		$this->server->on('beforeMove', [$this, 'beforeMoveFutureFile']);
182
-	}
183
-
184
-	/**
185
-	 * Plugin that checks if a move can actually be performed.
186
-	 *
187
-	 * @param string $source source path
188
-	 * @param string $destination destination path
189
-	 * @throws Forbidden
190
-	 * @throws NotFound
191
-	 */
192
-	function checkMove($source, $destination) {
193
-		$sourceNode = $this->tree->getNodeForPath($source);
194
-		if (!$sourceNode instanceof Node) {
195
-			return;
196
-		}
197
-		list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($source);
198
-		list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
199
-
200
-		if ($sourceDir !== $destinationDir) {
201
-			$sourceNodeFileInfo = $sourceNode->getFileInfo();
202
-			if (is_null($sourceNodeFileInfo)) {
203
-				throw new NotFound($source . ' does not exist');
204
-			}
205
-
206
-			if (!$sourceNodeFileInfo->isDeletable()) {
207
-				throw new Forbidden($source . " cannot be deleted");
208
-			}
209
-		}
210
-	}
211
-
212
-	/**
213
-	 * This sets a cookie to be able to recognize the start of the download
214
-	 * the content must not be longer than 32 characters and must only contain
215
-	 * alphanumeric characters
216
-	 *
217
-	 * @param RequestInterface $request
218
-	 * @param ResponseInterface $response
219
-	 */
220
-	function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
221
-		$queryParams = $request->getQueryParameters();
222
-
223
-		/**
224
-		 * this sets a cookie to be able to recognize the start of the download
225
-		 * the content must not be longer than 32 characters and must only contain
226
-		 * alphanumeric characters
227
-		 */
228
-		if (isset($queryParams['downloadStartSecret'])) {
229
-			$token = $queryParams['downloadStartSecret'];
230
-			if (!isset($token[32])
231
-				&& preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
232
-				// FIXME: use $response->setHeader() instead
233
-				setcookie('ocDownloadStarted', $token, time() + 20, '/');
234
-			}
235
-		}
236
-	}
237
-
238
-	/**
239
-	 * Add headers to file download
240
-	 *
241
-	 * @param RequestInterface $request
242
-	 * @param ResponseInterface $response
243
-	 */
244
-	function httpGet(RequestInterface $request, ResponseInterface $response) {
245
-		// Only handle valid files
246
-		$node = $this->tree->getNodeForPath($request->getPath());
247
-		if (!($node instanceof IFile)) return;
248
-
249
-		// adds a 'Content-Disposition: attachment' header in case no disposition
250
-		// header has been set before
251
-		if ($this->downloadAttachment &&
252
-			$response->getHeader('Content-Disposition') === null) {
253
-			$filename = $node->getName();
254
-			if ($this->request->isUserAgent(
255
-				[
256
-					\OC\AppFramework\Http\Request::USER_AGENT_IE,
257
-					\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
258
-					\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
259
-				])) {
260
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
261
-			} else {
262
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
263
-													 . '; filename="' . rawurlencode($filename) . '"');
264
-			}
265
-		}
266
-
267
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
268
-			//Add OC-Checksum header
269
-			/** @var $node File */
270
-			$checksum = $node->getChecksum();
271
-			if ($checksum !== null && $checksum !== '') {
272
-				$response->addHeader('OC-Checksum', $checksum);
273
-			}
274
-		}
275
-	}
276
-
277
-	/**
278
-	 * Adds all ownCloud-specific properties
279
-	 *
280
-	 * @param PropFind $propFind
281
-	 * @param \Sabre\DAV\INode $node
282
-	 * @return void
283
-	 */
284
-	public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
285
-
286
-		$httpRequest = $this->server->httpRequest;
287
-
288
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
289
-			if (!$node->getFileInfo()->isReadable()) {
290
-				// avoid detecting files through this means
291
-				throw new NotFound();
292
-			}
293
-
294
-			$propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
295
-				return $node->getFileId();
296
-			});
297
-
298
-			$propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
299
-				return $node->getInternalFileId();
300
-			});
301
-
302
-			$propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
303
-				$perms = $node->getDavPermissions();
304
-				if ($this->isPublic) {
305
-					// remove mount information
306
-					$perms = str_replace(['S', 'M'], '', $perms);
307
-				}
308
-				return $perms;
309
-			});
310
-
311
-			$propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
312
-				return $node->getSharePermissions(
313
-					$httpRequest->getRawServerValue('PHP_AUTH_USER')
314
-				);
315
-			});
316
-
317
-			$propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
318
-				return $node->getETag();
319
-			});
320
-
321
-			$propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
322
-				$owner = $node->getOwner();
323
-				if (!$owner) {
324
-					return null;
325
-				} else {
326
-					return $owner->getUID();
327
-				}
328
-			});
329
-			$propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
330
-				$owner = $node->getOwner();
331
-				if (!$owner) {
332
-					return null;
333
-				} else {
334
-					return $owner->getDisplayName();
335
-				}
336
-			});
337
-
338
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
339
-				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
340
-			});
341
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
342
-				return $node->getSize();
343
-			});
344
-		}
345
-
346
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
347
-			$propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
348
-				return $this->config->getSystemValue('data-fingerprint', '');
349
-			});
350
-		}
351
-
352
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
353
-			$propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
354
-				/** @var $node \OCA\DAV\Connector\Sabre\File */
355
-				try {
356
-					$directDownloadUrl = $node->getDirectDownload();
357
-					if (isset($directDownloadUrl['url'])) {
358
-						return $directDownloadUrl['url'];
359
-					}
360
-				} catch (StorageNotAvailableException $e) {
361
-					return false;
362
-				} catch (ForbiddenException $e) {
363
-					return false;
364
-				}
365
-				return false;
366
-			});
367
-
368
-			$propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
369
-				$checksum = $node->getChecksum();
370
-				if ($checksum === NULL || $checksum === '') {
371
-					return null;
372
-				}
373
-
374
-				return new ChecksumList($checksum);
375
-			});
376
-
377
-		}
378
-
379
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
380
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
381
-				return $node->getSize();
382
-			});
383
-		}
384
-	}
385
-
386
-	/**
387
-	 * Update ownCloud-specific properties
388
-	 *
389
-	 * @param string $path
390
-	 * @param PropPatch $propPatch
391
-	 *
392
-	 * @return void
393
-	 */
394
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
395
-		$node = $this->tree->getNodeForPath($path);
396
-		if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
397
-			return;
398
-		}
399
-
400
-		$propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($node) {
401
-			if (empty($time)) {
402
-				return false;
403
-			}
404
-			$node->touch($time);
405
-			return true;
406
-		});
407
-		$propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($node) {
408
-			if (empty($etag)) {
409
-				return false;
410
-			}
411
-			if ($node->setEtag($etag) !== -1) {
412
-				return true;
413
-			}
414
-			return false;
415
-		});
416
-	}
417
-
418
-	/**
419
-	 * @param string $filePath
420
-	 * @param \Sabre\DAV\INode $node
421
-	 * @throws \Sabre\DAV\Exception\BadRequest
422
-	 */
423
-	public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
424
-		// chunked upload handling
425
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
426
-			list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
427
-			$info = \OC_FileChunking::decodeName($name);
428
-			if (!empty($info)) {
429
-				$filePath = $path . '/' . $info['name'];
430
-			}
431
-		}
432
-
433
-		// we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
434
-		if (!$this->server->tree->nodeExists($filePath)) {
435
-			return;
436
-		}
437
-		$node = $this->server->tree->getNodeForPath($filePath);
438
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
439
-			$fileId = $node->getFileId();
440
-			if (!is_null($fileId)) {
441
-				$this->server->httpResponse->setHeader('OC-FileId', $fileId);
442
-			}
443
-		}
444
-	}
445
-
446
-	/**
447
-	 * Move handler for future file.
448
-	 *
449
-	 * This overrides the default move behavior to prevent Sabre
450
-	 * to delete the target file before moving. Because deleting would
451
-	 * lose the file id and metadata.
452
-	 *
453
-	 * @param string $path source path
454
-	 * @param string $destination destination path
455
-	 * @return bool|void false to stop handling, void to skip this handler
456
-	 */
457
-	public function beforeMoveFutureFile($path, $destination) {
458
-		$sourceNode = $this->tree->getNodeForPath($path);
459
-		if (!$sourceNode instanceof FutureFile) {
460
-			// skip handling as the source is not a chunked FutureFile
461
-			return;
462
-		}
463
-
464
-		if (!$this->tree->nodeExists($destination)) {
465
-			// skip and let the default handler do its work
466
-			return;
467
-		}
468
-
469
-		// do a move manually, skipping Sabre's default "delete" for existing nodes
470
-		$this->tree->move($path, $destination);
471
-
472
-		// trigger all default events (copied from CorePlugin::move)
473
-		$this->server->emit('afterMove', [$path, $destination]);
474
-		$this->server->emit('afterUnbind', [$path]);
475
-		$this->server->emit('afterBind', [$destination]);
476
-
477
-		$response = $this->server->httpResponse;
478
-		$response->setHeader('Content-Length', '0');
479
-		$response->setStatus(204);
480
-
481
-		return false;
482
-	}
52
+    // namespace
53
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
54
+    const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
55
+    const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
56
+    const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
57
+    const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
58
+    const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
59
+    const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
60
+    const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
61
+    const GETETAG_PROPERTYNAME = '{DAV:}getetag';
62
+    const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
63
+    const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
64
+    const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
65
+    const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
66
+    const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
67
+    const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
68
+
69
+    /**
70
+     * Reference to main server object
71
+     *
72
+     * @var \Sabre\DAV\Server
73
+     */
74
+    private $server;
75
+
76
+    /**
77
+     * @var Tree
78
+     */
79
+    private $tree;
80
+
81
+    /**
82
+     * Whether this is public webdav.
83
+     * If true, some returned information will be stripped off.
84
+     *
85
+     * @var bool
86
+     */
87
+    private $isPublic;
88
+
89
+    /**
90
+     * @var View
91
+     */
92
+    private $fileView;
93
+
94
+    /**
95
+     * @var bool
96
+     */
97
+    private $downloadAttachment;
98
+
99
+    /**
100
+     * @var IConfig
101
+     */
102
+    private $config;
103
+
104
+    /**
105
+     * @var IRequest
106
+     */
107
+    private $request;
108
+
109
+    /**
110
+     * @var IPreview
111
+     */
112
+    private $previewManager;
113
+
114
+    /**
115
+     * @param Tree $tree
116
+     * @param IConfig $config
117
+     * @param IRequest $request
118
+     * @param IPreview $previewManager
119
+     * @param bool $isPublic
120
+     * @param bool $downloadAttachment
121
+     */
122
+    public function __construct(Tree $tree,
123
+                                IConfig $config,
124
+                                IRequest $request,
125
+                                IPreview $previewManager,
126
+                                $isPublic = false,
127
+                                $downloadAttachment = true) {
128
+        $this->tree = $tree;
129
+        $this->config = $config;
130
+        $this->request = $request;
131
+        $this->isPublic = $isPublic;
132
+        $this->downloadAttachment = $downloadAttachment;
133
+        $this->previewManager = $previewManager;
134
+    }
135
+
136
+    /**
137
+     * This initializes the plugin.
138
+     *
139
+     * This function is called by \Sabre\DAV\Server, after
140
+     * addPlugin is called.
141
+     *
142
+     * This method should set up the required event subscriptions.
143
+     *
144
+     * @param \Sabre\DAV\Server $server
145
+     * @return void
146
+     */
147
+    public function initialize(\Sabre\DAV\Server $server) {
148
+
149
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
150
+        $server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
151
+        $server->protectedProperties[] = self::FILEID_PROPERTYNAME;
152
+        $server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
153
+        $server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
154
+        $server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
155
+        $server->protectedProperties[] = self::SIZE_PROPERTYNAME;
156
+        $server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
157
+        $server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
158
+        $server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
159
+        $server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
160
+        $server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
161
+        $server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
162
+
163
+        // normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
164
+        $allowedProperties = ['{DAV:}getetag'];
165
+        $server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
166
+
167
+        $this->server = $server;
168
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
169
+        $this->server->on('propPatch', array($this, 'handleUpdateProperties'));
170
+        $this->server->on('afterBind', array($this, 'sendFileIdHeader'));
171
+        $this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
172
+        $this->server->on('afterMethod:GET', [$this,'httpGet']);
173
+        $this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
174
+        $this->server->on('afterResponse', function($request, ResponseInterface $response) {
175
+            $body = $response->getBody();
176
+            if (is_resource($body)) {
177
+                fclose($body);
178
+            }
179
+        });
180
+        $this->server->on('beforeMove', [$this, 'checkMove']);
181
+        $this->server->on('beforeMove', [$this, 'beforeMoveFutureFile']);
182
+    }
183
+
184
+    /**
185
+     * Plugin that checks if a move can actually be performed.
186
+     *
187
+     * @param string $source source path
188
+     * @param string $destination destination path
189
+     * @throws Forbidden
190
+     * @throws NotFound
191
+     */
192
+    function checkMove($source, $destination) {
193
+        $sourceNode = $this->tree->getNodeForPath($source);
194
+        if (!$sourceNode instanceof Node) {
195
+            return;
196
+        }
197
+        list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($source);
198
+        list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
199
+
200
+        if ($sourceDir !== $destinationDir) {
201
+            $sourceNodeFileInfo = $sourceNode->getFileInfo();
202
+            if (is_null($sourceNodeFileInfo)) {
203
+                throw new NotFound($source . ' does not exist');
204
+            }
205
+
206
+            if (!$sourceNodeFileInfo->isDeletable()) {
207
+                throw new Forbidden($source . " cannot be deleted");
208
+            }
209
+        }
210
+    }
211
+
212
+    /**
213
+     * This sets a cookie to be able to recognize the start of the download
214
+     * the content must not be longer than 32 characters and must only contain
215
+     * alphanumeric characters
216
+     *
217
+     * @param RequestInterface $request
218
+     * @param ResponseInterface $response
219
+     */
220
+    function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
221
+        $queryParams = $request->getQueryParameters();
222
+
223
+        /**
224
+         * this sets a cookie to be able to recognize the start of the download
225
+         * the content must not be longer than 32 characters and must only contain
226
+         * alphanumeric characters
227
+         */
228
+        if (isset($queryParams['downloadStartSecret'])) {
229
+            $token = $queryParams['downloadStartSecret'];
230
+            if (!isset($token[32])
231
+                && preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
232
+                // FIXME: use $response->setHeader() instead
233
+                setcookie('ocDownloadStarted', $token, time() + 20, '/');
234
+            }
235
+        }
236
+    }
237
+
238
+    /**
239
+     * Add headers to file download
240
+     *
241
+     * @param RequestInterface $request
242
+     * @param ResponseInterface $response
243
+     */
244
+    function httpGet(RequestInterface $request, ResponseInterface $response) {
245
+        // Only handle valid files
246
+        $node = $this->tree->getNodeForPath($request->getPath());
247
+        if (!($node instanceof IFile)) return;
248
+
249
+        // adds a 'Content-Disposition: attachment' header in case no disposition
250
+        // header has been set before
251
+        if ($this->downloadAttachment &&
252
+            $response->getHeader('Content-Disposition') === null) {
253
+            $filename = $node->getName();
254
+            if ($this->request->isUserAgent(
255
+                [
256
+                    \OC\AppFramework\Http\Request::USER_AGENT_IE,
257
+                    \OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
258
+                    \OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
259
+                ])) {
260
+                $response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
261
+            } else {
262
+                $response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
263
+                                                        . '; filename="' . rawurlencode($filename) . '"');
264
+            }
265
+        }
266
+
267
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
268
+            //Add OC-Checksum header
269
+            /** @var $node File */
270
+            $checksum = $node->getChecksum();
271
+            if ($checksum !== null && $checksum !== '') {
272
+                $response->addHeader('OC-Checksum', $checksum);
273
+            }
274
+        }
275
+    }
276
+
277
+    /**
278
+     * Adds all ownCloud-specific properties
279
+     *
280
+     * @param PropFind $propFind
281
+     * @param \Sabre\DAV\INode $node
282
+     * @return void
283
+     */
284
+    public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
285
+
286
+        $httpRequest = $this->server->httpRequest;
287
+
288
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
289
+            if (!$node->getFileInfo()->isReadable()) {
290
+                // avoid detecting files through this means
291
+                throw new NotFound();
292
+            }
293
+
294
+            $propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
295
+                return $node->getFileId();
296
+            });
297
+
298
+            $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
299
+                return $node->getInternalFileId();
300
+            });
301
+
302
+            $propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
303
+                $perms = $node->getDavPermissions();
304
+                if ($this->isPublic) {
305
+                    // remove mount information
306
+                    $perms = str_replace(['S', 'M'], '', $perms);
307
+                }
308
+                return $perms;
309
+            });
310
+
311
+            $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
312
+                return $node->getSharePermissions(
313
+                    $httpRequest->getRawServerValue('PHP_AUTH_USER')
314
+                );
315
+            });
316
+
317
+            $propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
318
+                return $node->getETag();
319
+            });
320
+
321
+            $propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
322
+                $owner = $node->getOwner();
323
+                if (!$owner) {
324
+                    return null;
325
+                } else {
326
+                    return $owner->getUID();
327
+                }
328
+            });
329
+            $propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
330
+                $owner = $node->getOwner();
331
+                if (!$owner) {
332
+                    return null;
333
+                } else {
334
+                    return $owner->getDisplayName();
335
+                }
336
+            });
337
+
338
+            $propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
339
+                return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
340
+            });
341
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
342
+                return $node->getSize();
343
+            });
344
+        }
345
+
346
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
347
+            $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
348
+                return $this->config->getSystemValue('data-fingerprint', '');
349
+            });
350
+        }
351
+
352
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
353
+            $propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
354
+                /** @var $node \OCA\DAV\Connector\Sabre\File */
355
+                try {
356
+                    $directDownloadUrl = $node->getDirectDownload();
357
+                    if (isset($directDownloadUrl['url'])) {
358
+                        return $directDownloadUrl['url'];
359
+                    }
360
+                } catch (StorageNotAvailableException $e) {
361
+                    return false;
362
+                } catch (ForbiddenException $e) {
363
+                    return false;
364
+                }
365
+                return false;
366
+            });
367
+
368
+            $propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
369
+                $checksum = $node->getChecksum();
370
+                if ($checksum === NULL || $checksum === '') {
371
+                    return null;
372
+                }
373
+
374
+                return new ChecksumList($checksum);
375
+            });
376
+
377
+        }
378
+
379
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
380
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
381
+                return $node->getSize();
382
+            });
383
+        }
384
+    }
385
+
386
+    /**
387
+     * Update ownCloud-specific properties
388
+     *
389
+     * @param string $path
390
+     * @param PropPatch $propPatch
391
+     *
392
+     * @return void
393
+     */
394
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
395
+        $node = $this->tree->getNodeForPath($path);
396
+        if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
397
+            return;
398
+        }
399
+
400
+        $propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($node) {
401
+            if (empty($time)) {
402
+                return false;
403
+            }
404
+            $node->touch($time);
405
+            return true;
406
+        });
407
+        $propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($node) {
408
+            if (empty($etag)) {
409
+                return false;
410
+            }
411
+            if ($node->setEtag($etag) !== -1) {
412
+                return true;
413
+            }
414
+            return false;
415
+        });
416
+    }
417
+
418
+    /**
419
+     * @param string $filePath
420
+     * @param \Sabre\DAV\INode $node
421
+     * @throws \Sabre\DAV\Exception\BadRequest
422
+     */
423
+    public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
424
+        // chunked upload handling
425
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
426
+            list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
427
+            $info = \OC_FileChunking::decodeName($name);
428
+            if (!empty($info)) {
429
+                $filePath = $path . '/' . $info['name'];
430
+            }
431
+        }
432
+
433
+        // we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
434
+        if (!$this->server->tree->nodeExists($filePath)) {
435
+            return;
436
+        }
437
+        $node = $this->server->tree->getNodeForPath($filePath);
438
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
439
+            $fileId = $node->getFileId();
440
+            if (!is_null($fileId)) {
441
+                $this->server->httpResponse->setHeader('OC-FileId', $fileId);
442
+            }
443
+        }
444
+    }
445
+
446
+    /**
447
+     * Move handler for future file.
448
+     *
449
+     * This overrides the default move behavior to prevent Sabre
450
+     * to delete the target file before moving. Because deleting would
451
+     * lose the file id and metadata.
452
+     *
453
+     * @param string $path source path
454
+     * @param string $destination destination path
455
+     * @return bool|void false to stop handling, void to skip this handler
456
+     */
457
+    public function beforeMoveFutureFile($path, $destination) {
458
+        $sourceNode = $this->tree->getNodeForPath($path);
459
+        if (!$sourceNode instanceof FutureFile) {
460
+            // skip handling as the source is not a chunked FutureFile
461
+            return;
462
+        }
463
+
464
+        if (!$this->tree->nodeExists($destination)) {
465
+            // skip and let the default handler do its work
466
+            return;
467
+        }
468
+
469
+        // do a move manually, skipping Sabre's default "delete" for existing nodes
470
+        $this->tree->move($path, $destination);
471
+
472
+        // trigger all default events (copied from CorePlugin::move)
473
+        $this->server->emit('afterMove', [$path, $destination]);
474
+        $this->server->emit('afterUnbind', [$path]);
475
+        $this->server->emit('afterBind', [$destination]);
476
+
477
+        $response = $this->server->httpResponse;
478
+        $response->setHeader('Content-Length', '0');
479
+        $response->setStatus(204);
480
+
481
+        return false;
482
+    }
483 483
 
484 484
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ObjectTree.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -33,7 +33,6 @@
 block discarded – undo
33 33
 use OCA\DAV\Connector\Sabre\Exception\InvalidPath;
34 34
 use OCA\DAV\Connector\Sabre\Exception\FileLocked;
35 35
 use OC\Files\FileInfo;
36
-use OC\Files\Mount\MoveableMount;
37 36
 use OCP\Files\ForbiddenException;
38 37
 use OCP\Files\StorageInvalidException;
39 38
 use OCP\Files\StorageNotAvailableException;
Please login to merge, or discard this patch.
Indentation   +200 added lines, -200 removed lines patch added patch discarded remove patch
@@ -41,204 +41,204 @@
 block discarded – undo
41 41
 
42 42
 class ObjectTree extends \Sabre\DAV\Tree {
43 43
 
44
-	/**
45
-	 * @var \OC\Files\View
46
-	 */
47
-	protected $fileView;
48
-
49
-	/**
50
-	 * @var  \OCP\Files\Mount\IMountManager
51
-	 */
52
-	protected $mountManager;
53
-
54
-	/**
55
-	 * Creates the object
56
-	 */
57
-	public function __construct() {
58
-	}
59
-
60
-	/**
61
-	 * @param \Sabre\DAV\INode $rootNode
62
-	 * @param \OC\Files\View $view
63
-	 * @param  \OCP\Files\Mount\IMountManager $mountManager
64
-	 */
65
-	public function init(\Sabre\DAV\INode $rootNode, \OC\Files\View $view, \OCP\Files\Mount\IMountManager $mountManager) {
66
-		$this->rootNode = $rootNode;
67
-		$this->fileView = $view;
68
-		$this->mountManager = $mountManager;
69
-	}
70
-
71
-	/**
72
-	 * If the given path is a chunked file name, converts it
73
-	 * to the real file name. Only applies if the OC-CHUNKED header
74
-	 * is present.
75
-	 *
76
-	 * @param string $path chunk file path to convert
77
-	 *
78
-	 * @return string path to real file
79
-	 */
80
-	private function resolveChunkFile($path) {
81
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
82
-			// resolve to real file name to find the proper node
83
-			list($dir, $name) = \Sabre\HTTP\URLUtil::splitPath($path);
84
-			if ($dir == '/' || $dir == '.') {
85
-				$dir = '';
86
-			}
87
-
88
-			$info = \OC_FileChunking::decodeName($name);
89
-			// only replace path if it was really the chunked file
90
-			if (isset($info['transferid'])) {
91
-				// getNodePath is called for multiple nodes within a chunk
92
-				// upload call
93
-				$path = $dir . '/' . $info['name'];
94
-				$path = ltrim($path, '/');
95
-			}
96
-		}
97
-		return $path;
98
-	}
99
-
100
-	public function cacheNode(Node $node) {
101
-		$this->cache[trim($node->getPath(), '/')] = $node;
102
-	}
103
-
104
-	/**
105
-	 * Returns the INode object for the requested path
106
-	 *
107
-	 * @param string $path
108
-	 * @return \Sabre\DAV\INode
109
-	 * @throws InvalidPath
110
-	 * @throws \Sabre\DAV\Exception\Locked
111
-	 * @throws \Sabre\DAV\Exception\NotFound
112
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
113
-	 */
114
-	public function getNodeForPath($path) {
115
-		if (!$this->fileView) {
116
-			throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup');
117
-		}
118
-
119
-		$path = trim($path, '/');
120
-
121
-		if (isset($this->cache[$path])) {
122
-			return $this->cache[$path];
123
-		}
124
-
125
-		if ($path) {
126
-			try {
127
-				$this->fileView->verifyPath($path, basename($path));
128
-			} catch (\OCP\Files\InvalidPathException $ex) {
129
-				throw new InvalidPath($ex->getMessage());
130
-			}
131
-		}
132
-
133
-		// Is it the root node?
134
-		if (!strlen($path)) {
135
-			return $this->rootNode;
136
-		}
137
-
138
-		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
139
-			// read from storage
140
-			$absPath = $this->fileView->getAbsolutePath($path);
141
-			$mount = $this->fileView->getMount($path);
142
-			$storage = $mount->getStorage();
143
-			$internalPath = $mount->getInternalPath($absPath);
144
-			if ($storage && $storage->file_exists($internalPath)) {
145
-				/**
146
-				 * @var \OC\Files\Storage\Storage $storage
147
-				 */
148
-				// get data directly
149
-				$data = $storage->getMetaData($internalPath);
150
-				$info = new FileInfo($absPath, $storage, $internalPath, $data, $mount);
151
-			} else {
152
-				$info = null;
153
-			}
154
-		} else {
155
-			// resolve chunk file name to real name, if applicable
156
-			$path = $this->resolveChunkFile($path);
157
-
158
-			// read from cache
159
-			try {
160
-				$info = $this->fileView->getFileInfo($path);
161
-			} catch (StorageNotAvailableException $e) {
162
-				throw new \Sabre\DAV\Exception\ServiceUnavailable('Storage is temporarily not available');
163
-			} catch (StorageInvalidException $e) {
164
-				throw new \Sabre\DAV\Exception\NotFound('Storage ' . $path . ' is invalid');
165
-			} catch (LockedException $e) {
166
-				throw new \Sabre\DAV\Exception\Locked();
167
-			} catch (ForbiddenException $e) {
168
-				throw new \Sabre\DAV\Exception\Forbidden();
169
-			}
170
-		}
171
-
172
-		if (!$info) {
173
-			throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
174
-		}
175
-
176
-		if ($info->getType() === 'dir') {
177
-			$node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this);
178
-		} else {
179
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
180
-		}
181
-
182
-		$this->cache[$path] = $node;
183
-		return $node;
184
-
185
-	}
186
-
187
-	/**
188
-	 * Copies a file or directory.
189
-	 *
190
-	 * This method must work recursively and delete the destination
191
-	 * if it exists
192
-	 *
193
-	 * @param string $source
194
-	 * @param string $destination
195
-	 * @throws FileLocked
196
-	 * @throws Forbidden
197
-	 * @throws InvalidPath
198
-	 * @throws \Exception
199
-	 * @throws \Sabre\DAV\Exception\Forbidden
200
-	 * @throws \Sabre\DAV\Exception\Locked
201
-	 * @throws \Sabre\DAV\Exception\NotFound
202
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
203
-	 * @return void
204
-	 */
205
-	public function copy($source, $destination) {
206
-		if (!$this->fileView) {
207
-			throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup');
208
-		}
209
-
210
-
211
-		$info = $this->fileView->getFileInfo(dirname($destination));
212
-		if ($this->fileView->file_exists($destination)) {
213
-			$destinationPermission = $info && $info->isUpdateable();
214
-		} else {
215
-			$destinationPermission = $info && $info->isCreatable();
216
-		}
217
-		if (!$destinationPermission) {
218
-			throw new Forbidden('No permissions to copy object.');
219
-		}
220
-
221
-		// this will trigger existence check
222
-		$this->getNodeForPath($source);
223
-
224
-		list($destinationDir, $destinationName) = \Sabre\HTTP\URLUtil::splitPath($destination);
225
-		try {
226
-			$this->fileView->verifyPath($destinationDir, $destinationName);
227
-		} catch (\OCP\Files\InvalidPathException $ex) {
228
-			throw new InvalidPath($ex->getMessage());
229
-		}
230
-
231
-		try {
232
-			$this->fileView->copy($source, $destination);
233
-		} catch (StorageNotAvailableException $e) {
234
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
235
-		} catch (ForbiddenException $ex) {
236
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
237
-		} catch (LockedException $e) {
238
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
239
-		}
240
-
241
-		list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
242
-		$this->markDirty($destinationDir);
243
-	}
44
+    /**
45
+     * @var \OC\Files\View
46
+     */
47
+    protected $fileView;
48
+
49
+    /**
50
+     * @var  \OCP\Files\Mount\IMountManager
51
+     */
52
+    protected $mountManager;
53
+
54
+    /**
55
+     * Creates the object
56
+     */
57
+    public function __construct() {
58
+    }
59
+
60
+    /**
61
+     * @param \Sabre\DAV\INode $rootNode
62
+     * @param \OC\Files\View $view
63
+     * @param  \OCP\Files\Mount\IMountManager $mountManager
64
+     */
65
+    public function init(\Sabre\DAV\INode $rootNode, \OC\Files\View $view, \OCP\Files\Mount\IMountManager $mountManager) {
66
+        $this->rootNode = $rootNode;
67
+        $this->fileView = $view;
68
+        $this->mountManager = $mountManager;
69
+    }
70
+
71
+    /**
72
+     * If the given path is a chunked file name, converts it
73
+     * to the real file name. Only applies if the OC-CHUNKED header
74
+     * is present.
75
+     *
76
+     * @param string $path chunk file path to convert
77
+     *
78
+     * @return string path to real file
79
+     */
80
+    private function resolveChunkFile($path) {
81
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
82
+            // resolve to real file name to find the proper node
83
+            list($dir, $name) = \Sabre\HTTP\URLUtil::splitPath($path);
84
+            if ($dir == '/' || $dir == '.') {
85
+                $dir = '';
86
+            }
87
+
88
+            $info = \OC_FileChunking::decodeName($name);
89
+            // only replace path if it was really the chunked file
90
+            if (isset($info['transferid'])) {
91
+                // getNodePath is called for multiple nodes within a chunk
92
+                // upload call
93
+                $path = $dir . '/' . $info['name'];
94
+                $path = ltrim($path, '/');
95
+            }
96
+        }
97
+        return $path;
98
+    }
99
+
100
+    public function cacheNode(Node $node) {
101
+        $this->cache[trim($node->getPath(), '/')] = $node;
102
+    }
103
+
104
+    /**
105
+     * Returns the INode object for the requested path
106
+     *
107
+     * @param string $path
108
+     * @return \Sabre\DAV\INode
109
+     * @throws InvalidPath
110
+     * @throws \Sabre\DAV\Exception\Locked
111
+     * @throws \Sabre\DAV\Exception\NotFound
112
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
113
+     */
114
+    public function getNodeForPath($path) {
115
+        if (!$this->fileView) {
116
+            throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup');
117
+        }
118
+
119
+        $path = trim($path, '/');
120
+
121
+        if (isset($this->cache[$path])) {
122
+            return $this->cache[$path];
123
+        }
124
+
125
+        if ($path) {
126
+            try {
127
+                $this->fileView->verifyPath($path, basename($path));
128
+            } catch (\OCP\Files\InvalidPathException $ex) {
129
+                throw new InvalidPath($ex->getMessage());
130
+            }
131
+        }
132
+
133
+        // Is it the root node?
134
+        if (!strlen($path)) {
135
+            return $this->rootNode;
136
+        }
137
+
138
+        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
139
+            // read from storage
140
+            $absPath = $this->fileView->getAbsolutePath($path);
141
+            $mount = $this->fileView->getMount($path);
142
+            $storage = $mount->getStorage();
143
+            $internalPath = $mount->getInternalPath($absPath);
144
+            if ($storage && $storage->file_exists($internalPath)) {
145
+                /**
146
+                 * @var \OC\Files\Storage\Storage $storage
147
+                 */
148
+                // get data directly
149
+                $data = $storage->getMetaData($internalPath);
150
+                $info = new FileInfo($absPath, $storage, $internalPath, $data, $mount);
151
+            } else {
152
+                $info = null;
153
+            }
154
+        } else {
155
+            // resolve chunk file name to real name, if applicable
156
+            $path = $this->resolveChunkFile($path);
157
+
158
+            // read from cache
159
+            try {
160
+                $info = $this->fileView->getFileInfo($path);
161
+            } catch (StorageNotAvailableException $e) {
162
+                throw new \Sabre\DAV\Exception\ServiceUnavailable('Storage is temporarily not available');
163
+            } catch (StorageInvalidException $e) {
164
+                throw new \Sabre\DAV\Exception\NotFound('Storage ' . $path . ' is invalid');
165
+            } catch (LockedException $e) {
166
+                throw new \Sabre\DAV\Exception\Locked();
167
+            } catch (ForbiddenException $e) {
168
+                throw new \Sabre\DAV\Exception\Forbidden();
169
+            }
170
+        }
171
+
172
+        if (!$info) {
173
+            throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
174
+        }
175
+
176
+        if ($info->getType() === 'dir') {
177
+            $node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this);
178
+        } else {
179
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
180
+        }
181
+
182
+        $this->cache[$path] = $node;
183
+        return $node;
184
+
185
+    }
186
+
187
+    /**
188
+     * Copies a file or directory.
189
+     *
190
+     * This method must work recursively and delete the destination
191
+     * if it exists
192
+     *
193
+     * @param string $source
194
+     * @param string $destination
195
+     * @throws FileLocked
196
+     * @throws Forbidden
197
+     * @throws InvalidPath
198
+     * @throws \Exception
199
+     * @throws \Sabre\DAV\Exception\Forbidden
200
+     * @throws \Sabre\DAV\Exception\Locked
201
+     * @throws \Sabre\DAV\Exception\NotFound
202
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
203
+     * @return void
204
+     */
205
+    public function copy($source, $destination) {
206
+        if (!$this->fileView) {
207
+            throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup');
208
+        }
209
+
210
+
211
+        $info = $this->fileView->getFileInfo(dirname($destination));
212
+        if ($this->fileView->file_exists($destination)) {
213
+            $destinationPermission = $info && $info->isUpdateable();
214
+        } else {
215
+            $destinationPermission = $info && $info->isCreatable();
216
+        }
217
+        if (!$destinationPermission) {
218
+            throw new Forbidden('No permissions to copy object.');
219
+        }
220
+
221
+        // this will trigger existence check
222
+        $this->getNodeForPath($source);
223
+
224
+        list($destinationDir, $destinationName) = \Sabre\HTTP\URLUtil::splitPath($destination);
225
+        try {
226
+            $this->fileView->verifyPath($destinationDir, $destinationName);
227
+        } catch (\OCP\Files\InvalidPathException $ex) {
228
+            throw new InvalidPath($ex->getMessage());
229
+        }
230
+
231
+        try {
232
+            $this->fileView->copy($source, $destination);
233
+        } catch (StorageNotAvailableException $e) {
234
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
235
+        } catch (ForbiddenException $ex) {
236
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
237
+        } catch (LockedException $e) {
238
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
239
+        }
240
+
241
+        list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
242
+        $this->markDirty($destinationDir);
243
+    }
244 244
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			if (isset($info['transferid'])) {
91 91
 				// getNodePath is called for multiple nodes within a chunk
92 92
 				// upload call
93
-				$path = $dir . '/' . $info['name'];
93
+				$path = $dir.'/'.$info['name'];
94 94
 				$path = ltrim($path, '/');
95 95
 			}
96 96
 		}
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 			} catch (StorageNotAvailableException $e) {
162 162
 				throw new \Sabre\DAV\Exception\ServiceUnavailable('Storage is temporarily not available');
163 163
 			} catch (StorageInvalidException $e) {
164
-				throw new \Sabre\DAV\Exception\NotFound('Storage ' . $path . ' is invalid');
164
+				throw new \Sabre\DAV\Exception\NotFound('Storage '.$path.' is invalid');
165 165
 			} catch (LockedException $e) {
166 166
 				throw new \Sabre\DAV\Exception\Locked();
167 167
 			} catch (ForbiddenException $e) {
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 		}
171 171
 
172 172
 		if (!$info) {
173
-			throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
173
+			throw new \Sabre\DAV\Exception\NotFound('File with name '.$path.' could not be located');
174 174
 		}
175 175
 
176 176
 		if ($info->getType() === 'dir') {
Please login to merge, or discard this patch.
lib/private/Files/View.php 1 patch
Indentation   +2049 added lines, -2049 removed lines patch added patch discarded remove patch
@@ -82,2053 +82,2053 @@
 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, array('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
-				array(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
-					array(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, array('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, array('read'));
367
-	}
368
-
369
-	/**
370
-	 * @param $handle
371
-	 * @return mixed
372
-	 */
373
-	public function readdir($handle) {
374
-		$fsLocal = new Storage\Local(array('datadir' => '/'));
375
-		return $fsLocal->readdir($handle);
376
-	}
377
-
378
-	/**
379
-	 * @param string $path
380
-	 * @return bool|mixed
381
-	 */
382
-	public function is_dir($path) {
383
-		if ($path == '/') {
384
-			return true;
385
-		}
386
-		return $this->basicOperation('is_dir', $path);
387
-	}
388
-
389
-	/**
390
-	 * @param string $path
391
-	 * @return bool|mixed
392
-	 */
393
-	public function is_file($path) {
394
-		if ($path == '/') {
395
-			return false;
396
-		}
397
-		return $this->basicOperation('is_file', $path);
398
-	}
399
-
400
-	/**
401
-	 * @param string $path
402
-	 * @return mixed
403
-	 */
404
-	public function stat($path) {
405
-		return $this->basicOperation('stat', $path);
406
-	}
407
-
408
-	/**
409
-	 * @param string $path
410
-	 * @return mixed
411
-	 */
412
-	public function filetype($path) {
413
-		return $this->basicOperation('filetype', $path);
414
-	}
415
-
416
-	/**
417
-	 * @param string $path
418
-	 * @return mixed
419
-	 */
420
-	public function filesize($path) {
421
-		return $this->basicOperation('filesize', $path);
422
-	}
423
-
424
-	/**
425
-	 * @param string $path
426
-	 * @return bool|mixed
427
-	 * @throws \OCP\Files\InvalidPathException
428
-	 */
429
-	public function readfile($path) {
430
-		$this->assertPathLength($path);
431
-		@ob_end_clean();
432
-		$handle = $this->fopen($path, 'rb');
433
-		if ($handle) {
434
-			$chunkSize = 8192; // 8 kB chunks
435
-			while (!feof($handle)) {
436
-				echo fread($handle, $chunkSize);
437
-				flush();
438
-			}
439
-			fclose($handle);
440
-			$size = $this->filesize($path);
441
-			return $size;
442
-		}
443
-		return false;
444
-	}
445
-
446
-	/**
447
-	 * @param string $path
448
-	 * @param int $from
449
-	 * @param int $to
450
-	 * @return bool|mixed
451
-	 * @throws \OCP\Files\InvalidPathException
452
-	 * @throws \OCP\Files\UnseekableException
453
-	 */
454
-	public function readfilePart($path, $from, $to) {
455
-		$this->assertPathLength($path);
456
-		@ob_end_clean();
457
-		$handle = $this->fopen($path, 'rb');
458
-		if ($handle) {
459
-			if (fseek($handle, $from) === 0) {
460
-				$chunkSize = 8192; // 8 kB chunks
461
-				$end = $to + 1;
462
-				while (!feof($handle) && ftell($handle) < $end) {
463
-					$len = $end - ftell($handle);
464
-					if ($len > $chunkSize) {
465
-						$len = $chunkSize;
466
-					}
467
-					echo fread($handle, $len);
468
-					flush();
469
-				}
470
-				$size = ftell($handle) - $from;
471
-				return $size;
472
-			}
473
-
474
-			throw new \OCP\Files\UnseekableException('fseek error');
475
-		}
476
-		return false;
477
-	}
478
-
479
-	/**
480
-	 * @param string $path
481
-	 * @return mixed
482
-	 */
483
-	public function isCreatable($path) {
484
-		return $this->basicOperation('isCreatable', $path);
485
-	}
486
-
487
-	/**
488
-	 * @param string $path
489
-	 * @return mixed
490
-	 */
491
-	public function isReadable($path) {
492
-		return $this->basicOperation('isReadable', $path);
493
-	}
494
-
495
-	/**
496
-	 * @param string $path
497
-	 * @return mixed
498
-	 */
499
-	public function isUpdatable($path) {
500
-		return $this->basicOperation('isUpdatable', $path);
501
-	}
502
-
503
-	/**
504
-	 * @param string $path
505
-	 * @return bool|mixed
506
-	 */
507
-	public function isDeletable($path) {
508
-		$absolutePath = $this->getAbsolutePath($path);
509
-		$mount = Filesystem::getMountManager()->find($absolutePath);
510
-		if ($mount->getInternalPath($absolutePath) === '') {
511
-			return $mount instanceof MoveableMount;
512
-		}
513
-		return $this->basicOperation('isDeletable', $path);
514
-	}
515
-
516
-	/**
517
-	 * @param string $path
518
-	 * @return mixed
519
-	 */
520
-	public function isSharable($path) {
521
-		return $this->basicOperation('isSharable', $path);
522
-	}
523
-
524
-	/**
525
-	 * @param string $path
526
-	 * @return bool|mixed
527
-	 */
528
-	public function file_exists($path) {
529
-		if ($path == '/') {
530
-			return true;
531
-		}
532
-		return $this->basicOperation('file_exists', $path);
533
-	}
534
-
535
-	/**
536
-	 * @param string $path
537
-	 * @return mixed
538
-	 */
539
-	public function filemtime($path) {
540
-		return $this->basicOperation('filemtime', $path);
541
-	}
542
-
543
-	/**
544
-	 * @param string $path
545
-	 * @param int|string $mtime
546
-	 * @return bool
547
-	 */
548
-	public function touch($path, $mtime = null) {
549
-		if (!is_null($mtime) and !is_numeric($mtime)) {
550
-			$mtime = strtotime($mtime);
551
-		}
552
-
553
-		$hooks = array('touch');
554
-
555
-		if (!$this->file_exists($path)) {
556
-			$hooks[] = 'create';
557
-			$hooks[] = 'write';
558
-		}
559
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
560
-		if (!$result) {
561
-			// If create file fails because of permissions on external storage like SMB folders,
562
-			// check file exists and return false if not.
563
-			if (!$this->file_exists($path)) {
564
-				return false;
565
-			}
566
-			if (is_null($mtime)) {
567
-				$mtime = time();
568
-			}
569
-			//if native touch fails, we emulate it by changing the mtime in the cache
570
-			$this->putFileInfo($path, array('mtime' => floor($mtime)));
571
-		}
572
-		return true;
573
-	}
574
-
575
-	/**
576
-	 * @param string $path
577
-	 * @return mixed
578
-	 */
579
-	public function file_get_contents($path) {
580
-		return $this->basicOperation('file_get_contents', $path, array('read'));
581
-	}
582
-
583
-	/**
584
-	 * @param bool $exists
585
-	 * @param string $path
586
-	 * @param bool $run
587
-	 */
588
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
589
-		if (!$exists) {
590
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
591
-				Filesystem::signal_param_path => $this->getHookPath($path),
592
-				Filesystem::signal_param_run => &$run,
593
-			));
594
-		} else {
595
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
596
-				Filesystem::signal_param_path => $this->getHookPath($path),
597
-				Filesystem::signal_param_run => &$run,
598
-			));
599
-		}
600
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
601
-			Filesystem::signal_param_path => $this->getHookPath($path),
602
-			Filesystem::signal_param_run => &$run,
603
-		));
604
-	}
605
-
606
-	/**
607
-	 * @param bool $exists
608
-	 * @param string $path
609
-	 */
610
-	protected function emit_file_hooks_post($exists, $path) {
611
-		if (!$exists) {
612
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
613
-				Filesystem::signal_param_path => $this->getHookPath($path),
614
-			));
615
-		} else {
616
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
617
-				Filesystem::signal_param_path => $this->getHookPath($path),
618
-			));
619
-		}
620
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
621
-			Filesystem::signal_param_path => $this->getHookPath($path),
622
-		));
623
-	}
624
-
625
-	/**
626
-	 * @param string $path
627
-	 * @param mixed $data
628
-	 * @return bool|mixed
629
-	 * @throws \Exception
630
-	 */
631
-	public function file_put_contents($path, $data) {
632
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
633
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
634
-			if (Filesystem::isValidPath($path)
635
-				and !Filesystem::isFileBlacklisted($path)
636
-			) {
637
-				$path = $this->getRelativePath($absolutePath);
638
-
639
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
640
-
641
-				$exists = $this->file_exists($path);
642
-				$run = true;
643
-				if ($this->shouldEmitHooks($path)) {
644
-					$this->emit_file_hooks_pre($exists, $path, $run);
645
-				}
646
-				if (!$run) {
647
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
648
-					return false;
649
-				}
650
-
651
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
652
-
653
-				/** @var \OC\Files\Storage\Storage $storage */
654
-				list($storage, $internalPath) = $this->resolvePath($path);
655
-				$target = $storage->fopen($internalPath, 'w');
656
-				if ($target) {
657
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
658
-					fclose($target);
659
-					fclose($data);
660
-
661
-					$this->writeUpdate($storage, $internalPath);
662
-
663
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
664
-
665
-					if ($this->shouldEmitHooks($path) && $result !== false) {
666
-						$this->emit_file_hooks_post($exists, $path);
667
-					}
668
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
669
-					return $result;
670
-				} else {
671
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
672
-					return false;
673
-				}
674
-			} else {
675
-				return false;
676
-			}
677
-		} else {
678
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
679
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
680
-		}
681
-	}
682
-
683
-	/**
684
-	 * @param string $path
685
-	 * @return bool|mixed
686
-	 */
687
-	public function unlink($path) {
688
-		if ($path === '' || $path === '/') {
689
-			// do not allow deleting the root
690
-			return false;
691
-		}
692
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
693
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
694
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
695
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
696
-			return $this->removeMount($mount, $absolutePath);
697
-		}
698
-		if ($this->is_dir($path)) {
699
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
700
-		} else {
701
-			$result = $this->basicOperation('unlink', $path, ['delete']);
702
-		}
703
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
704
-			$storage = $mount->getStorage();
705
-			$internalPath = $mount->getInternalPath($absolutePath);
706
-			$storage->getUpdater()->remove($internalPath);
707
-			return true;
708
-		} else {
709
-			return $result;
710
-		}
711
-	}
712
-
713
-	/**
714
-	 * @param string $directory
715
-	 * @return bool|mixed
716
-	 */
717
-	public function deleteAll($directory) {
718
-		return $this->rmdir($directory);
719
-	}
720
-
721
-	/**
722
-	 * Rename/move a file or folder from the source path to target path.
723
-	 *
724
-	 * @param string $path1 source path
725
-	 * @param string $path2 target path
726
-	 *
727
-	 * @return bool|mixed
728
-	 */
729
-	public function rename($path1, $path2) {
730
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
731
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
732
-		$result = false;
733
-		if (
734
-			Filesystem::isValidPath($path2)
735
-			and Filesystem::isValidPath($path1)
736
-			and !Filesystem::isFileBlacklisted($path2)
737
-		) {
738
-			$path1 = $this->getRelativePath($absolutePath1);
739
-			$path2 = $this->getRelativePath($absolutePath2);
740
-			$exists = $this->file_exists($path2);
741
-
742
-			if ($path1 == null or $path2 == null) {
743
-				return false;
744
-			}
745
-
746
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
747
-			try {
748
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
749
-			} catch (LockedException $e) {
750
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
751
-				throw $e;
752
-			}
753
-
754
-			$run = true;
755
-			if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
756
-				// if it was a rename from a part file to a regular file it was a write and not a rename operation
757
-				$this->emit_file_hooks_pre($exists, $path2, $run);
758
-			} elseif ($this->shouldEmitHooks($path1)) {
759
-				\OC_Hook::emit(
760
-					Filesystem::CLASSNAME, Filesystem::signal_rename,
761
-					array(
762
-						Filesystem::signal_param_oldpath => $this->getHookPath($path1),
763
-						Filesystem::signal_param_newpath => $this->getHookPath($path2),
764
-						Filesystem::signal_param_run => &$run
765
-					)
766
-				);
767
-			}
768
-			if ($run) {
769
-				$this->verifyPath(dirname($path2), basename($path2));
770
-
771
-				$manager = Filesystem::getMountManager();
772
-				$mount1 = $this->getMount($path1);
773
-				$mount2 = $this->getMount($path2);
774
-				$storage1 = $mount1->getStorage();
775
-				$storage2 = $mount2->getStorage();
776
-				$internalPath1 = $mount1->getInternalPath($absolutePath1);
777
-				$internalPath2 = $mount2->getInternalPath($absolutePath2);
778
-
779
-				$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
780
-				$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
781
-
782
-				if ($internalPath1 === '' and $mount1 instanceof MoveableMount) {
783
-					if ($this->isTargetAllowed($absolutePath2)) {
784
-						/**
785
-						 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
786
-						 */
787
-						$sourceMountPoint = $mount1->getMountPoint();
788
-						$result = $mount1->moveMount($absolutePath2);
789
-						$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
790
-					} else {
791
-						$result = false;
792
-					}
793
-					// moving a file/folder within the same mount point
794
-				} elseif ($storage1 === $storage2) {
795
-					if ($storage1) {
796
-						$result = $storage1->rename($internalPath1, $internalPath2);
797
-					} else {
798
-						$result = false;
799
-					}
800
-					// moving a file/folder between storages (from $storage1 to $storage2)
801
-				} else {
802
-					$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
803
-				}
804
-
805
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
806
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
807
-
808
-					$this->writeUpdate($storage2, $internalPath2);
809
-				} else if ($result) {
810
-					if ($internalPath1 !== '') { // don't do a cache update for moved mounts
811
-						$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
812
-					}
813
-				}
814
-
815
-				$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
816
-				$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
817
-
818
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
819
-					if ($this->shouldEmitHooks()) {
820
-						$this->emit_file_hooks_post($exists, $path2);
821
-					}
822
-				} elseif ($result) {
823
-					if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
824
-						\OC_Hook::emit(
825
-							Filesystem::CLASSNAME,
826
-							Filesystem::signal_post_rename,
827
-							array(
828
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
829
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
830
-							)
831
-						);
832
-					}
833
-				}
834
-			}
835
-			$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
836
-			$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
837
-		}
838
-		return $result;
839
-	}
840
-
841
-	/**
842
-	 * Copy a file/folder from the source path to target path
843
-	 *
844
-	 * @param string $path1 source path
845
-	 * @param string $path2 target path
846
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
847
-	 *
848
-	 * @return bool|mixed
849
-	 */
850
-	public function copy($path1, $path2, $preserveMtime = false) {
851
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
852
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
853
-		$result = false;
854
-		if (
855
-			Filesystem::isValidPath($path2)
856
-			and Filesystem::isValidPath($path1)
857
-			and !Filesystem::isFileBlacklisted($path2)
858
-		) {
859
-			$path1 = $this->getRelativePath($absolutePath1);
860
-			$path2 = $this->getRelativePath($absolutePath2);
861
-
862
-			if ($path1 == null or $path2 == null) {
863
-				return false;
864
-			}
865
-			$run = true;
866
-
867
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
868
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
869
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
870
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
871
-
872
-			try {
873
-
874
-				$exists = $this->file_exists($path2);
875
-				if ($this->shouldEmitHooks()) {
876
-					\OC_Hook::emit(
877
-						Filesystem::CLASSNAME,
878
-						Filesystem::signal_copy,
879
-						array(
880
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
881
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
882
-							Filesystem::signal_param_run => &$run
883
-						)
884
-					);
885
-					$this->emit_file_hooks_pre($exists, $path2, $run);
886
-				}
887
-				if ($run) {
888
-					$mount1 = $this->getMount($path1);
889
-					$mount2 = $this->getMount($path2);
890
-					$storage1 = $mount1->getStorage();
891
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
892
-					$storage2 = $mount2->getStorage();
893
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
894
-
895
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
896
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
897
-
898
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
899
-						if ($storage1) {
900
-							$result = $storage1->copy($internalPath1, $internalPath2);
901
-						} else {
902
-							$result = false;
903
-						}
904
-					} else {
905
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
906
-					}
907
-
908
-					$this->writeUpdate($storage2, $internalPath2);
909
-
910
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
911
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
912
-
913
-					if ($this->shouldEmitHooks() && $result !== false) {
914
-						\OC_Hook::emit(
915
-							Filesystem::CLASSNAME,
916
-							Filesystem::signal_post_copy,
917
-							array(
918
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
919
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
920
-							)
921
-						);
922
-						$this->emit_file_hooks_post($exists, $path2);
923
-					}
924
-
925
-				}
926
-			} catch (\Exception $e) {
927
-				$this->unlockFile($path2, $lockTypePath2);
928
-				$this->unlockFile($path1, $lockTypePath1);
929
-				throw $e;
930
-			}
931
-
932
-			$this->unlockFile($path2, $lockTypePath2);
933
-			$this->unlockFile($path1, $lockTypePath1);
934
-
935
-		}
936
-		return $result;
937
-	}
938
-
939
-	/**
940
-	 * @param string $path
941
-	 * @param string $mode 'r' or 'w'
942
-	 * @return resource
943
-	 */
944
-	public function fopen($path, $mode) {
945
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
946
-		$hooks = array();
947
-		switch ($mode) {
948
-			case 'r':
949
-				$hooks[] = 'read';
950
-				break;
951
-			case 'r+':
952
-			case 'w+':
953
-			case 'x+':
954
-			case 'a+':
955
-				$hooks[] = 'read';
956
-				$hooks[] = 'write';
957
-				break;
958
-			case 'w':
959
-			case 'x':
960
-			case 'a':
961
-				$hooks[] = 'write';
962
-				break;
963
-			default:
964
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
965
-		}
966
-
967
-		if ($mode !== 'r' && $mode !== 'w') {
968
-			\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');
969
-		}
970
-
971
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
972
-	}
973
-
974
-	/**
975
-	 * @param string $path
976
-	 * @return bool|string
977
-	 * @throws \OCP\Files\InvalidPathException
978
-	 */
979
-	public function toTmpFile($path) {
980
-		$this->assertPathLength($path);
981
-		if (Filesystem::isValidPath($path)) {
982
-			$source = $this->fopen($path, 'r');
983
-			if ($source) {
984
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
985
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
986
-				file_put_contents($tmpFile, $source);
987
-				return $tmpFile;
988
-			} else {
989
-				return false;
990
-			}
991
-		} else {
992
-			return false;
993
-		}
994
-	}
995
-
996
-	/**
997
-	 * @param string $tmpFile
998
-	 * @param string $path
999
-	 * @return bool|mixed
1000
-	 * @throws \OCP\Files\InvalidPathException
1001
-	 */
1002
-	public function fromTmpFile($tmpFile, $path) {
1003
-		$this->assertPathLength($path);
1004
-		if (Filesystem::isValidPath($path)) {
1005
-
1006
-			// Get directory that the file is going into
1007
-			$filePath = dirname($path);
1008
-
1009
-			// Create the directories if any
1010
-			if (!$this->file_exists($filePath)) {
1011
-				$result = $this->createParentDirectories($filePath);
1012
-				if ($result === false) {
1013
-					return false;
1014
-				}
1015
-			}
1016
-
1017
-			$source = fopen($tmpFile, 'r');
1018
-			if ($source) {
1019
-				$result = $this->file_put_contents($path, $source);
1020
-				// $this->file_put_contents() might have already closed
1021
-				// the resource, so we check it, before trying to close it
1022
-				// to avoid messages in the error log.
1023
-				if (is_resource($source)) {
1024
-					fclose($source);
1025
-				}
1026
-				unlink($tmpFile);
1027
-				return $result;
1028
-			} else {
1029
-				return false;
1030
-			}
1031
-		} else {
1032
-			return false;
1033
-		}
1034
-	}
1035
-
1036
-
1037
-	/**
1038
-	 * @param string $path
1039
-	 * @return mixed
1040
-	 * @throws \OCP\Files\InvalidPathException
1041
-	 */
1042
-	public function getMimeType($path) {
1043
-		$this->assertPathLength($path);
1044
-		return $this->basicOperation('getMimeType', $path);
1045
-	}
1046
-
1047
-	/**
1048
-	 * @param string $type
1049
-	 * @param string $path
1050
-	 * @param bool $raw
1051
-	 * @return bool|null|string
1052
-	 */
1053
-	public function hash($type, $path, $raw = false) {
1054
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1055
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1056
-		if (Filesystem::isValidPath($path)) {
1057
-			$path = $this->getRelativePath($absolutePath);
1058
-			if ($path == null) {
1059
-				return false;
1060
-			}
1061
-			if ($this->shouldEmitHooks($path)) {
1062
-				\OC_Hook::emit(
1063
-					Filesystem::CLASSNAME,
1064
-					Filesystem::signal_read,
1065
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1066
-				);
1067
-			}
1068
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1069
-			if ($storage) {
1070
-				$result = $storage->hash($type, $internalPath, $raw);
1071
-				return $result;
1072
-			}
1073
-		}
1074
-		return null;
1075
-	}
1076
-
1077
-	/**
1078
-	 * @param string $path
1079
-	 * @return mixed
1080
-	 * @throws \OCP\Files\InvalidPathException
1081
-	 */
1082
-	public function free_space($path = '/') {
1083
-		$this->assertPathLength($path);
1084
-		return $this->basicOperation('free_space', $path);
1085
-	}
1086
-
1087
-	/**
1088
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1089
-	 *
1090
-	 * @param string $operation
1091
-	 * @param string $path
1092
-	 * @param array $hooks (optional)
1093
-	 * @param mixed $extraParam (optional)
1094
-	 * @return mixed
1095
-	 * @throws \Exception
1096
-	 *
1097
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1098
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1099
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1100
-	 */
1101
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1102
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1103
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1104
-		if (Filesystem::isValidPath($path)
1105
-			and !Filesystem::isFileBlacklisted($path)
1106
-		) {
1107
-			$path = $this->getRelativePath($absolutePath);
1108
-			if ($path == null) {
1109
-				return false;
1110
-			}
1111
-
1112
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1113
-				// always a shared lock during pre-hooks so the hook can read the file
1114
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1115
-			}
1116
-
1117
-			$run = $this->runHooks($hooks, $path);
1118
-			/** @var \OC\Files\Storage\Storage $storage */
1119
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1120
-			if ($run and $storage) {
1121
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1122
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1123
-				}
1124
-				try {
1125
-					if (!is_null($extraParam)) {
1126
-						$result = $storage->$operation($internalPath, $extraParam);
1127
-					} else {
1128
-						$result = $storage->$operation($internalPath);
1129
-					}
1130
-				} catch (\Exception $e) {
1131
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1132
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1133
-					} else if (in_array('read', $hooks)) {
1134
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1135
-					}
1136
-					throw $e;
1137
-				}
1138
-
1139
-				if ($result && in_array('delete', $hooks) and $result) {
1140
-					$this->removeUpdate($storage, $internalPath);
1141
-				}
1142
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1143
-					$this->writeUpdate($storage, $internalPath);
1144
-				}
1145
-				if ($result && in_array('touch', $hooks)) {
1146
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1147
-				}
1148
-
1149
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1150
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1151
-				}
1152
-
1153
-				$unlockLater = false;
1154
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1155
-					$unlockLater = true;
1156
-					// make sure our unlocking callback will still be called if connection is aborted
1157
-					ignore_user_abort(true);
1158
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1159
-						if (in_array('write', $hooks)) {
1160
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1161
-						} else if (in_array('read', $hooks)) {
1162
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1163
-						}
1164
-					});
1165
-				}
1166
-
1167
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1168
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1169
-						$this->runHooks($hooks, $path, true);
1170
-					}
1171
-				}
1172
-
1173
-				if (!$unlockLater
1174
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1175
-				) {
1176
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1177
-				}
1178
-				return $result;
1179
-			} else {
1180
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1181
-			}
1182
-		}
1183
-		return null;
1184
-	}
1185
-
1186
-	/**
1187
-	 * get the path relative to the default root for hook usage
1188
-	 *
1189
-	 * @param string $path
1190
-	 * @return string
1191
-	 */
1192
-	private function getHookPath($path) {
1193
-		if (!Filesystem::getView()) {
1194
-			return $path;
1195
-		}
1196
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1197
-	}
1198
-
1199
-	private function shouldEmitHooks($path = '') {
1200
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1201
-			return false;
1202
-		}
1203
-		if (!Filesystem::$loaded) {
1204
-			return false;
1205
-		}
1206
-		$defaultRoot = Filesystem::getRoot();
1207
-		if ($defaultRoot === null) {
1208
-			return false;
1209
-		}
1210
-		if ($this->fakeRoot === $defaultRoot) {
1211
-			return true;
1212
-		}
1213
-		$fullPath = $this->getAbsolutePath($path);
1214
-
1215
-		if ($fullPath === $defaultRoot) {
1216
-			return true;
1217
-		}
1218
-
1219
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1220
-	}
1221
-
1222
-	/**
1223
-	 * @param string[] $hooks
1224
-	 * @param string $path
1225
-	 * @param bool $post
1226
-	 * @return bool
1227
-	 */
1228
-	private function runHooks($hooks, $path, $post = false) {
1229
-		$relativePath = $path;
1230
-		$path = $this->getHookPath($path);
1231
-		$prefix = ($post) ? 'post_' : '';
1232
-		$run = true;
1233
-		if ($this->shouldEmitHooks($relativePath)) {
1234
-			foreach ($hooks as $hook) {
1235
-				if ($hook != 'read') {
1236
-					\OC_Hook::emit(
1237
-						Filesystem::CLASSNAME,
1238
-						$prefix . $hook,
1239
-						array(
1240
-							Filesystem::signal_param_run => &$run,
1241
-							Filesystem::signal_param_path => $path
1242
-						)
1243
-					);
1244
-				} elseif (!$post) {
1245
-					\OC_Hook::emit(
1246
-						Filesystem::CLASSNAME,
1247
-						$prefix . $hook,
1248
-						array(
1249
-							Filesystem::signal_param_path => $path
1250
-						)
1251
-					);
1252
-				}
1253
-			}
1254
-		}
1255
-		return $run;
1256
-	}
1257
-
1258
-	/**
1259
-	 * check if a file or folder has been updated since $time
1260
-	 *
1261
-	 * @param string $path
1262
-	 * @param int $time
1263
-	 * @return bool
1264
-	 */
1265
-	public function hasUpdated($path, $time) {
1266
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1267
-	}
1268
-
1269
-	/**
1270
-	 * @param string $ownerId
1271
-	 * @return \OC\User\User
1272
-	 */
1273
-	private function getUserObjectForOwner($ownerId) {
1274
-		$owner = $this->userManager->get($ownerId);
1275
-		if ($owner instanceof IUser) {
1276
-			return $owner;
1277
-		} else {
1278
-			return new User($ownerId, null);
1279
-		}
1280
-	}
1281
-
1282
-	/**
1283
-	 * Get file info from cache
1284
-	 *
1285
-	 * If the file is not in cached it will be scanned
1286
-	 * If the file has changed on storage the cache will be updated
1287
-	 *
1288
-	 * @param \OC\Files\Storage\Storage $storage
1289
-	 * @param string $internalPath
1290
-	 * @param string $relativePath
1291
-	 * @return array|bool
1292
-	 */
1293
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1294
-		$cache = $storage->getCache($internalPath);
1295
-		$data = $cache->get($internalPath);
1296
-		$watcher = $storage->getWatcher($internalPath);
1297
-
1298
-		try {
1299
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1300
-			if (!$data || $data['size'] === -1) {
1301
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1302
-				if (!$storage->file_exists($internalPath)) {
1303
-					$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1304
-					return false;
1305
-				}
1306
-				$scanner = $storage->getScanner($internalPath);
1307
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1308
-				$data = $cache->get($internalPath);
1309
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1310
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1311
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1312
-				$watcher->update($internalPath, $data);
1313
-				$storage->getPropagator()->propagateChange($internalPath, time());
1314
-				$data = $cache->get($internalPath);
1315
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1316
-			}
1317
-		} catch (LockedException $e) {
1318
-			// if the file is locked we just use the old cache info
1319
-		}
1320
-
1321
-		return $data;
1322
-	}
1323
-
1324
-	/**
1325
-	 * get the filesystem info
1326
-	 *
1327
-	 * @param string $path
1328
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1329
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1330
-	 * defaults to true
1331
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1332
-	 */
1333
-	public function getFileInfo($path, $includeMountPoints = true) {
1334
-		$this->assertPathLength($path);
1335
-		if (!Filesystem::isValidPath($path)) {
1336
-			return false;
1337
-		}
1338
-		if (Cache\Scanner::isPartialFile($path)) {
1339
-			return $this->getPartFileInfo($path);
1340
-		}
1341
-		$relativePath = $path;
1342
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1343
-
1344
-		$mount = Filesystem::getMountManager()->find($path);
1345
-		$storage = $mount->getStorage();
1346
-		$internalPath = $mount->getInternalPath($path);
1347
-		if ($storage) {
1348
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1349
-
1350
-			if (!$data instanceof ICacheEntry) {
1351
-				return false;
1352
-			}
1353
-
1354
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1355
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1356
-			}
1357
-
1358
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1359
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1360
-
1361
-			if ($data and isset($data['fileid'])) {
1362
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1363
-					//add the sizes of other mount points to the folder
1364
-					$extOnly = ($includeMountPoints === 'ext');
1365
-					$mounts = Filesystem::getMountManager()->findIn($path);
1366
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1367
-						$subStorage = $mount->getStorage();
1368
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1369
-					}));
1370
-				}
1371
-			}
1372
-
1373
-			return $info;
1374
-		}
1375
-
1376
-		return false;
1377
-	}
1378
-
1379
-	/**
1380
-	 * get the content of a directory
1381
-	 *
1382
-	 * @param string $directory path under datadirectory
1383
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1384
-	 * @return FileInfo[]
1385
-	 */
1386
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1387
-		$this->assertPathLength($directory);
1388
-		if (!Filesystem::isValidPath($directory)) {
1389
-			return [];
1390
-		}
1391
-		$path = $this->getAbsolutePath($directory);
1392
-		$path = Filesystem::normalizePath($path);
1393
-		$mount = $this->getMount($directory);
1394
-		$storage = $mount->getStorage();
1395
-		$internalPath = $mount->getInternalPath($path);
1396
-		if ($storage) {
1397
-			$cache = $storage->getCache($internalPath);
1398
-			$user = \OC_User::getUser();
1399
-
1400
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1401
-
1402
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1403
-				return [];
1404
-			}
1405
-
1406
-			$folderId = $data['fileid'];
1407
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1408
-
1409
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1410
-			/**
1411
-			 * @var \OC\Files\FileInfo[] $files
1412
-			 */
1413
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1414
-				if ($sharingDisabled) {
1415
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1416
-				}
1417
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1418
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1419
-			}, $contents);
1420
-
1421
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1422
-			$mounts = Filesystem::getMountManager()->findIn($path);
1423
-			$dirLength = strlen($path);
1424
-			foreach ($mounts as $mount) {
1425
-				$mountPoint = $mount->getMountPoint();
1426
-				$subStorage = $mount->getStorage();
1427
-				if ($subStorage) {
1428
-					$subCache = $subStorage->getCache('');
1429
-
1430
-					$rootEntry = $subCache->get('');
1431
-					if (!$rootEntry) {
1432
-						$subScanner = $subStorage->getScanner('');
1433
-						try {
1434
-							$subScanner->scanFile('');
1435
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1436
-							continue;
1437
-						} catch (\OCP\Files\StorageInvalidException $e) {
1438
-							continue;
1439
-						} catch (\Exception $e) {
1440
-							// sometimes when the storage is not available it can be any exception
1441
-							\OCP\Util::writeLog(
1442
-								'core',
1443
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1444
-								get_class($e) . ': ' . $e->getMessage(),
1445
-								\OCP\Util::ERROR
1446
-							);
1447
-							continue;
1448
-						}
1449
-						$rootEntry = $subCache->get('');
1450
-					}
1451
-
1452
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1453
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1454
-						if ($pos = strpos($relativePath, '/')) {
1455
-							//mountpoint inside subfolder add size to the correct folder
1456
-							$entryName = substr($relativePath, 0, $pos);
1457
-							foreach ($files as &$entry) {
1458
-								if ($entry->getName() === $entryName) {
1459
-									$entry->addSubEntry($rootEntry, $mountPoint);
1460
-								}
1461
-							}
1462
-						} else { //mountpoint in this folder, add an entry for it
1463
-							$rootEntry['name'] = $relativePath;
1464
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1465
-							$permissions = $rootEntry['permissions'];
1466
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1467
-							// for shared files/folders we use the permissions given by the owner
1468
-							if ($mount instanceof MoveableMount) {
1469
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1470
-							} else {
1471
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1472
-							}
1473
-
1474
-							//remove any existing entry with the same name
1475
-							foreach ($files as $i => $file) {
1476
-								if ($file['name'] === $rootEntry['name']) {
1477
-									unset($files[$i]);
1478
-									break;
1479
-								}
1480
-							}
1481
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1482
-
1483
-							// if sharing was disabled for the user we remove the share permissions
1484
-							if (\OCP\Util::isSharingDisabledForUser()) {
1485
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1486
-							}
1487
-
1488
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1489
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1490
-						}
1491
-					}
1492
-				}
1493
-			}
1494
-
1495
-			if ($mimetype_filter) {
1496
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1497
-					if (strpos($mimetype_filter, '/')) {
1498
-						return $file->getMimetype() === $mimetype_filter;
1499
-					} else {
1500
-						return $file->getMimePart() === $mimetype_filter;
1501
-					}
1502
-				});
1503
-			}
1504
-
1505
-			return $files;
1506
-		} else {
1507
-			return [];
1508
-		}
1509
-	}
1510
-
1511
-	/**
1512
-	 * change file metadata
1513
-	 *
1514
-	 * @param string $path
1515
-	 * @param array|\OCP\Files\FileInfo $data
1516
-	 * @return int
1517
-	 *
1518
-	 * returns the fileid of the updated file
1519
-	 */
1520
-	public function putFileInfo($path, $data) {
1521
-		$this->assertPathLength($path);
1522
-		if ($data instanceof FileInfo) {
1523
-			$data = $data->getData();
1524
-		}
1525
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1526
-		/**
1527
-		 * @var \OC\Files\Storage\Storage $storage
1528
-		 * @var string $internalPath
1529
-		 */
1530
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1531
-		if ($storage) {
1532
-			$cache = $storage->getCache($path);
1533
-
1534
-			if (!$cache->inCache($internalPath)) {
1535
-				$scanner = $storage->getScanner($internalPath);
1536
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1537
-			}
1538
-
1539
-			return $cache->put($internalPath, $data);
1540
-		} else {
1541
-			return -1;
1542
-		}
1543
-	}
1544
-
1545
-	/**
1546
-	 * search for files with the name matching $query
1547
-	 *
1548
-	 * @param string $query
1549
-	 * @return FileInfo[]
1550
-	 */
1551
-	public function search($query) {
1552
-		return $this->searchCommon('search', array('%' . $query . '%'));
1553
-	}
1554
-
1555
-	/**
1556
-	 * search for files with the name matching $query
1557
-	 *
1558
-	 * @param string $query
1559
-	 * @return FileInfo[]
1560
-	 */
1561
-	public function searchRaw($query) {
1562
-		return $this->searchCommon('search', array($query));
1563
-	}
1564
-
1565
-	/**
1566
-	 * search for files by mimetype
1567
-	 *
1568
-	 * @param string $mimetype
1569
-	 * @return FileInfo[]
1570
-	 */
1571
-	public function searchByMime($mimetype) {
1572
-		return $this->searchCommon('searchByMime', array($mimetype));
1573
-	}
1574
-
1575
-	/**
1576
-	 * search for files by tag
1577
-	 *
1578
-	 * @param string|int $tag name or tag id
1579
-	 * @param string $userId owner of the tags
1580
-	 * @return FileInfo[]
1581
-	 */
1582
-	public function searchByTag($tag, $userId) {
1583
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1584
-	}
1585
-
1586
-	/**
1587
-	 * @param string $method cache method
1588
-	 * @param array $args
1589
-	 * @return FileInfo[]
1590
-	 */
1591
-	private function searchCommon($method, $args) {
1592
-		$files = array();
1593
-		$rootLength = strlen($this->fakeRoot);
1594
-
1595
-		$mount = $this->getMount('');
1596
-		$mountPoint = $mount->getMountPoint();
1597
-		$storage = $mount->getStorage();
1598
-		if ($storage) {
1599
-			$cache = $storage->getCache('');
1600
-
1601
-			$results = call_user_func_array(array($cache, $method), $args);
1602
-			foreach ($results as $result) {
1603
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1604
-					$internalPath = $result['path'];
1605
-					$path = $mountPoint . $result['path'];
1606
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1607
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1608
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1609
-				}
1610
-			}
1611
-
1612
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1613
-			foreach ($mounts as $mount) {
1614
-				$mountPoint = $mount->getMountPoint();
1615
-				$storage = $mount->getStorage();
1616
-				if ($storage) {
1617
-					$cache = $storage->getCache('');
1618
-
1619
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1620
-					$results = call_user_func_array(array($cache, $method), $args);
1621
-					if ($results) {
1622
-						foreach ($results as $result) {
1623
-							$internalPath = $result['path'];
1624
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1625
-							$path = rtrim($mountPoint . $internalPath, '/');
1626
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1627
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1628
-						}
1629
-					}
1630
-				}
1631
-			}
1632
-		}
1633
-		return $files;
1634
-	}
1635
-
1636
-	/**
1637
-	 * Get the owner for a file or folder
1638
-	 *
1639
-	 * @param string $path
1640
-	 * @return string the user id of the owner
1641
-	 * @throws NotFoundException
1642
-	 */
1643
-	public function getOwner($path) {
1644
-		$info = $this->getFileInfo($path);
1645
-		if (!$info) {
1646
-			throw new NotFoundException($path . ' not found while trying to get owner');
1647
-		}
1648
-		return $info->getOwner()->getUID();
1649
-	}
1650
-
1651
-	/**
1652
-	 * get the ETag for a file or folder
1653
-	 *
1654
-	 * @param string $path
1655
-	 * @return string
1656
-	 */
1657
-	public function getETag($path) {
1658
-		/**
1659
-		 * @var Storage\Storage $storage
1660
-		 * @var string $internalPath
1661
-		 */
1662
-		list($storage, $internalPath) = $this->resolvePath($path);
1663
-		if ($storage) {
1664
-			return $storage->getETag($internalPath);
1665
-		} else {
1666
-			return null;
1667
-		}
1668
-	}
1669
-
1670
-	/**
1671
-	 * Get the path of a file by id, relative to the view
1672
-	 *
1673
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1674
-	 *
1675
-	 * @param int $id
1676
-	 * @throws NotFoundException
1677
-	 * @return string
1678
-	 */
1679
-	public function getPath($id) {
1680
-		$id = (int)$id;
1681
-		$manager = Filesystem::getMountManager();
1682
-		$mounts = $manager->findIn($this->fakeRoot);
1683
-		$mounts[] = $manager->find($this->fakeRoot);
1684
-		// reverse the array so we start with the storage this view is in
1685
-		// which is the most likely to contain the file we're looking for
1686
-		$mounts = array_reverse($mounts);
1687
-		foreach ($mounts as $mount) {
1688
-			/**
1689
-			 * @var \OC\Files\Mount\MountPoint $mount
1690
-			 */
1691
-			if ($mount->getStorage()) {
1692
-				$cache = $mount->getStorage()->getCache();
1693
-				$internalPath = $cache->getPathById($id);
1694
-				if (is_string($internalPath)) {
1695
-					$fullPath = $mount->getMountPoint() . $internalPath;
1696
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1697
-						return $path;
1698
-					}
1699
-				}
1700
-			}
1701
-		}
1702
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1703
-	}
1704
-
1705
-	/**
1706
-	 * @param string $path
1707
-	 * @throws InvalidPathException
1708
-	 */
1709
-	private function assertPathLength($path) {
1710
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1711
-		// Check for the string length - performed using isset() instead of strlen()
1712
-		// because isset() is about 5x-40x faster.
1713
-		if (isset($path[$maxLen])) {
1714
-			$pathLen = strlen($path);
1715
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1716
-		}
1717
-	}
1718
-
1719
-	/**
1720
-	 * check if it is allowed to move a mount point to a given target.
1721
-	 * It is not allowed to move a mount point into a different mount point or
1722
-	 * into an already shared folder
1723
-	 *
1724
-	 * @param string $target path
1725
-	 * @return boolean
1726
-	 */
1727
-	private function isTargetAllowed($target) {
1728
-
1729
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1730
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1731
-			\OCP\Util::writeLog('files',
1732
-				'It is not allowed to move one mount point into another one',
1733
-				\OCP\Util::DEBUG);
1734
-			return false;
1735
-		}
1736
-
1737
-		// note: cannot use the view because the target is already locked
1738
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1739
-		if ($fileId === -1) {
1740
-			// target might not exist, need to check parent instead
1741
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1742
-		}
1743
-
1744
-		// check if any of the parents were shared by the current owner (include collections)
1745
-		$shares = \OCP\Share::getItemShared(
1746
-			'folder',
1747
-			$fileId,
1748
-			\OCP\Share::FORMAT_NONE,
1749
-			null,
1750
-			true
1751
-		);
1752
-
1753
-		if (count($shares) > 0) {
1754
-			\OCP\Util::writeLog('files',
1755
-				'It is not allowed to move one mount point into a shared folder',
1756
-				\OCP\Util::DEBUG);
1757
-			return false;
1758
-		}
1759
-
1760
-		return true;
1761
-	}
1762
-
1763
-	/**
1764
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1765
-	 *
1766
-	 * @param string $path
1767
-	 * @return \OCP\Files\FileInfo
1768
-	 */
1769
-	private function getPartFileInfo($path) {
1770
-		$mount = $this->getMount($path);
1771
-		$storage = $mount->getStorage();
1772
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1773
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1774
-		return new FileInfo(
1775
-			$this->getAbsolutePath($path),
1776
-			$storage,
1777
-			$internalPath,
1778
-			[
1779
-				'fileid' => null,
1780
-				'mimetype' => $storage->getMimeType($internalPath),
1781
-				'name' => basename($path),
1782
-				'etag' => null,
1783
-				'size' => $storage->filesize($internalPath),
1784
-				'mtime' => $storage->filemtime($internalPath),
1785
-				'encrypted' => false,
1786
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1787
-			],
1788
-			$mount,
1789
-			$owner
1790
-		);
1791
-	}
1792
-
1793
-	/**
1794
-	 * @param string $path
1795
-	 * @param string $fileName
1796
-	 * @throws InvalidPathException
1797
-	 */
1798
-	public function verifyPath($path, $fileName) {
1799
-		try {
1800
-			/** @type \OCP\Files\Storage $storage */
1801
-			list($storage, $internalPath) = $this->resolvePath($path);
1802
-			$storage->verifyPath($internalPath, $fileName);
1803
-		} catch (ReservedWordException $ex) {
1804
-			$l = \OC::$server->getL10N('lib');
1805
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1806
-		} catch (InvalidCharacterInPathException $ex) {
1807
-			$l = \OC::$server->getL10N('lib');
1808
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1809
-		} catch (FileNameTooLongException $ex) {
1810
-			$l = \OC::$server->getL10N('lib');
1811
-			throw new InvalidPathException($l->t('File name is too long'));
1812
-		} catch (InvalidDirectoryException $ex) {
1813
-			$l = \OC::$server->getL10N('lib');
1814
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1815
-		} catch (EmptyFileNameException $ex) {
1816
-			$l = \OC::$server->getL10N('lib');
1817
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1818
-		}
1819
-	}
1820
-
1821
-	/**
1822
-	 * get all parent folders of $path
1823
-	 *
1824
-	 * @param string $path
1825
-	 * @return string[]
1826
-	 */
1827
-	private function getParents($path) {
1828
-		$path = trim($path, '/');
1829
-		if (!$path) {
1830
-			return [];
1831
-		}
1832
-
1833
-		$parts = explode('/', $path);
1834
-
1835
-		// remove the single file
1836
-		array_pop($parts);
1837
-		$result = array('/');
1838
-		$resultPath = '';
1839
-		foreach ($parts as $part) {
1840
-			if ($part) {
1841
-				$resultPath .= '/' . $part;
1842
-				$result[] = $resultPath;
1843
-			}
1844
-		}
1845
-		return $result;
1846
-	}
1847
-
1848
-	/**
1849
-	 * Returns the mount point for which to lock
1850
-	 *
1851
-	 * @param string $absolutePath absolute path
1852
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1853
-	 * is mounted directly on the given path, false otherwise
1854
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1855
-	 */
1856
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1857
-		$results = [];
1858
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1859
-		if (!$mount) {
1860
-			return $results;
1861
-		}
1862
-
1863
-		if ($useParentMount) {
1864
-			// find out if something is mounted directly on the path
1865
-			$internalPath = $mount->getInternalPath($absolutePath);
1866
-			if ($internalPath === '') {
1867
-				// resolve the parent mount instead
1868
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1869
-			}
1870
-		}
1871
-
1872
-		return $mount;
1873
-	}
1874
-
1875
-	/**
1876
-	 * Lock the given path
1877
-	 *
1878
-	 * @param string $path the path of the file to lock, relative to the view
1879
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1880
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1881
-	 *
1882
-	 * @return bool False if the path is excluded from locking, true otherwise
1883
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1884
-	 */
1885
-	private function lockPath($path, $type, $lockMountPoint = false) {
1886
-		$absolutePath = $this->getAbsolutePath($path);
1887
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1888
-		if (!$this->shouldLockFile($absolutePath)) {
1889
-			return false;
1890
-		}
1891
-
1892
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1893
-		if ($mount) {
1894
-			try {
1895
-				$storage = $mount->getStorage();
1896
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1897
-					$storage->acquireLock(
1898
-						$mount->getInternalPath($absolutePath),
1899
-						$type,
1900
-						$this->lockingProvider
1901
-					);
1902
-				}
1903
-			} catch (\OCP\Lock\LockedException $e) {
1904
-				// rethrow with the a human-readable path
1905
-				throw new \OCP\Lock\LockedException(
1906
-					$this->getPathRelativeToFiles($absolutePath),
1907
-					$e
1908
-				);
1909
-			}
1910
-		}
1911
-
1912
-		return true;
1913
-	}
1914
-
1915
-	/**
1916
-	 * Change the lock type
1917
-	 *
1918
-	 * @param string $path the path of the file to lock, relative to the view
1919
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1920
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1921
-	 *
1922
-	 * @return bool False if the path is excluded from locking, true otherwise
1923
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1924
-	 */
1925
-	public function changeLock($path, $type, $lockMountPoint = false) {
1926
-		$path = Filesystem::normalizePath($path);
1927
-		$absolutePath = $this->getAbsolutePath($path);
1928
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1929
-		if (!$this->shouldLockFile($absolutePath)) {
1930
-			return false;
1931
-		}
1932
-
1933
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1934
-		if ($mount) {
1935
-			try {
1936
-				$storage = $mount->getStorage();
1937
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1938
-					$storage->changeLock(
1939
-						$mount->getInternalPath($absolutePath),
1940
-						$type,
1941
-						$this->lockingProvider
1942
-					);
1943
-				}
1944
-			} catch (\OCP\Lock\LockedException $e) {
1945
-				// rethrow with the a human-readable path
1946
-				throw new \OCP\Lock\LockedException(
1947
-					$this->getPathRelativeToFiles($absolutePath),
1948
-					$e
1949
-				);
1950
-			}
1951
-		}
1952
-
1953
-		return true;
1954
-	}
1955
-
1956
-	/**
1957
-	 * Unlock the given path
1958
-	 *
1959
-	 * @param string $path the path of the file to unlock, relative to the view
1960
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1961
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1962
-	 *
1963
-	 * @return bool False if the path is excluded from locking, true otherwise
1964
-	 */
1965
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1966
-		$absolutePath = $this->getAbsolutePath($path);
1967
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1968
-		if (!$this->shouldLockFile($absolutePath)) {
1969
-			return false;
1970
-		}
1971
-
1972
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1973
-		if ($mount) {
1974
-			$storage = $mount->getStorage();
1975
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1976
-				$storage->releaseLock(
1977
-					$mount->getInternalPath($absolutePath),
1978
-					$type,
1979
-					$this->lockingProvider
1980
-				);
1981
-			}
1982
-		}
1983
-
1984
-		return true;
1985
-	}
1986
-
1987
-	/**
1988
-	 * Lock a path and all its parents up to the root of the view
1989
-	 *
1990
-	 * @param string $path the path of the file to lock relative to the view
1991
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1992
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1993
-	 *
1994
-	 * @return bool False if the path is excluded from locking, true otherwise
1995
-	 */
1996
-	public function lockFile($path, $type, $lockMountPoint = false) {
1997
-		$absolutePath = $this->getAbsolutePath($path);
1998
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1999
-		if (!$this->shouldLockFile($absolutePath)) {
2000
-			return false;
2001
-		}
2002
-
2003
-		$this->lockPath($path, $type, $lockMountPoint);
2004
-
2005
-		$parents = $this->getParents($path);
2006
-		foreach ($parents as $parent) {
2007
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2008
-		}
2009
-
2010
-		return true;
2011
-	}
2012
-
2013
-	/**
2014
-	 * Unlock a path and all its parents up to the root of the view
2015
-	 *
2016
-	 * @param string $path the path of the file to lock 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
-	 */
2022
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2023
-		$absolutePath = $this->getAbsolutePath($path);
2024
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2025
-		if (!$this->shouldLockFile($absolutePath)) {
2026
-			return false;
2027
-		}
2028
-
2029
-		$this->unlockPath($path, $type, $lockMountPoint);
2030
-
2031
-		$parents = $this->getParents($path);
2032
-		foreach ($parents as $parent) {
2033
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2034
-		}
2035
-
2036
-		return true;
2037
-	}
2038
-
2039
-	/**
2040
-	 * Only lock files in data/user/files/
2041
-	 *
2042
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2043
-	 * @return bool
2044
-	 */
2045
-	protected function shouldLockFile($path) {
2046
-		$path = Filesystem::normalizePath($path);
2047
-
2048
-		$pathSegments = explode('/', $path);
2049
-		if (isset($pathSegments[2])) {
2050
-			// E.g.: /username/files/path-to-file
2051
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2052
-		}
2053
-
2054
-		return true;
2055
-	}
2056
-
2057
-	/**
2058
-	 * Shortens the given absolute path to be relative to
2059
-	 * "$user/files".
2060
-	 *
2061
-	 * @param string $absolutePath absolute path which is under "files"
2062
-	 *
2063
-	 * @return string path relative to "files" with trimmed slashes or null
2064
-	 * if the path was NOT relative to files
2065
-	 *
2066
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2067
-	 * @since 8.1.0
2068
-	 */
2069
-	public function getPathRelativeToFiles($absolutePath) {
2070
-		$path = Filesystem::normalizePath($absolutePath);
2071
-		$parts = explode('/', trim($path, '/'), 3);
2072
-		// "$user", "files", "path/to/dir"
2073
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2074
-			$this->logger->error(
2075
-				'$absolutePath must be relative to "files", value is "%s"',
2076
-				[
2077
-					$absolutePath
2078
-				]
2079
-			);
2080
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2081
-		}
2082
-		if (isset($parts[2])) {
2083
-			return $parts[2];
2084
-		}
2085
-		return '';
2086
-	}
2087
-
2088
-	/**
2089
-	 * @param string $filename
2090
-	 * @return array
2091
-	 * @throws \OC\User\NoUserException
2092
-	 * @throws NotFoundException
2093
-	 */
2094
-	public function getUidAndFilename($filename) {
2095
-		$info = $this->getFileInfo($filename);
2096
-		if (!$info instanceof \OCP\Files\FileInfo) {
2097
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2098
-		}
2099
-		$uid = $info->getOwner()->getUID();
2100
-		if ($uid != \OCP\User::getUser()) {
2101
-			Filesystem::initMountPoints($uid);
2102
-			$ownerView = new View('/' . $uid . '/files');
2103
-			try {
2104
-				$filename = $ownerView->getPath($info['fileid']);
2105
-			} catch (NotFoundException $e) {
2106
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2107
-			}
2108
-		}
2109
-		return [$uid, $filename];
2110
-	}
2111
-
2112
-	/**
2113
-	 * Creates parent non-existing folders
2114
-	 *
2115
-	 * @param string $filePath
2116
-	 * @return bool
2117
-	 */
2118
-	private function createParentDirectories($filePath) {
2119
-		$directoryParts = explode('/', $filePath);
2120
-		$directoryParts = array_filter($directoryParts);
2121
-		foreach ($directoryParts as $key => $part) {
2122
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2123
-			$currentPath = '/' . implode('/', $currentPathElements);
2124
-			if ($this->is_file($currentPath)) {
2125
-				return false;
2126
-			}
2127
-			if (!$this->file_exists($currentPath)) {
2128
-				$this->mkdir($currentPath);
2129
-			}
2130
-		}
2131
-
2132
-		return true;
2133
-	}
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, array('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
+                array(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
+                    array(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, array('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, array('read'));
367
+    }
368
+
369
+    /**
370
+     * @param $handle
371
+     * @return mixed
372
+     */
373
+    public function readdir($handle) {
374
+        $fsLocal = new Storage\Local(array('datadir' => '/'));
375
+        return $fsLocal->readdir($handle);
376
+    }
377
+
378
+    /**
379
+     * @param string $path
380
+     * @return bool|mixed
381
+     */
382
+    public function is_dir($path) {
383
+        if ($path == '/') {
384
+            return true;
385
+        }
386
+        return $this->basicOperation('is_dir', $path);
387
+    }
388
+
389
+    /**
390
+     * @param string $path
391
+     * @return bool|mixed
392
+     */
393
+    public function is_file($path) {
394
+        if ($path == '/') {
395
+            return false;
396
+        }
397
+        return $this->basicOperation('is_file', $path);
398
+    }
399
+
400
+    /**
401
+     * @param string $path
402
+     * @return mixed
403
+     */
404
+    public function stat($path) {
405
+        return $this->basicOperation('stat', $path);
406
+    }
407
+
408
+    /**
409
+     * @param string $path
410
+     * @return mixed
411
+     */
412
+    public function filetype($path) {
413
+        return $this->basicOperation('filetype', $path);
414
+    }
415
+
416
+    /**
417
+     * @param string $path
418
+     * @return mixed
419
+     */
420
+    public function filesize($path) {
421
+        return $this->basicOperation('filesize', $path);
422
+    }
423
+
424
+    /**
425
+     * @param string $path
426
+     * @return bool|mixed
427
+     * @throws \OCP\Files\InvalidPathException
428
+     */
429
+    public function readfile($path) {
430
+        $this->assertPathLength($path);
431
+        @ob_end_clean();
432
+        $handle = $this->fopen($path, 'rb');
433
+        if ($handle) {
434
+            $chunkSize = 8192; // 8 kB chunks
435
+            while (!feof($handle)) {
436
+                echo fread($handle, $chunkSize);
437
+                flush();
438
+            }
439
+            fclose($handle);
440
+            $size = $this->filesize($path);
441
+            return $size;
442
+        }
443
+        return false;
444
+    }
445
+
446
+    /**
447
+     * @param string $path
448
+     * @param int $from
449
+     * @param int $to
450
+     * @return bool|mixed
451
+     * @throws \OCP\Files\InvalidPathException
452
+     * @throws \OCP\Files\UnseekableException
453
+     */
454
+    public function readfilePart($path, $from, $to) {
455
+        $this->assertPathLength($path);
456
+        @ob_end_clean();
457
+        $handle = $this->fopen($path, 'rb');
458
+        if ($handle) {
459
+            if (fseek($handle, $from) === 0) {
460
+                $chunkSize = 8192; // 8 kB chunks
461
+                $end = $to + 1;
462
+                while (!feof($handle) && ftell($handle) < $end) {
463
+                    $len = $end - ftell($handle);
464
+                    if ($len > $chunkSize) {
465
+                        $len = $chunkSize;
466
+                    }
467
+                    echo fread($handle, $len);
468
+                    flush();
469
+                }
470
+                $size = ftell($handle) - $from;
471
+                return $size;
472
+            }
473
+
474
+            throw new \OCP\Files\UnseekableException('fseek error');
475
+        }
476
+        return false;
477
+    }
478
+
479
+    /**
480
+     * @param string $path
481
+     * @return mixed
482
+     */
483
+    public function isCreatable($path) {
484
+        return $this->basicOperation('isCreatable', $path);
485
+    }
486
+
487
+    /**
488
+     * @param string $path
489
+     * @return mixed
490
+     */
491
+    public function isReadable($path) {
492
+        return $this->basicOperation('isReadable', $path);
493
+    }
494
+
495
+    /**
496
+     * @param string $path
497
+     * @return mixed
498
+     */
499
+    public function isUpdatable($path) {
500
+        return $this->basicOperation('isUpdatable', $path);
501
+    }
502
+
503
+    /**
504
+     * @param string $path
505
+     * @return bool|mixed
506
+     */
507
+    public function isDeletable($path) {
508
+        $absolutePath = $this->getAbsolutePath($path);
509
+        $mount = Filesystem::getMountManager()->find($absolutePath);
510
+        if ($mount->getInternalPath($absolutePath) === '') {
511
+            return $mount instanceof MoveableMount;
512
+        }
513
+        return $this->basicOperation('isDeletable', $path);
514
+    }
515
+
516
+    /**
517
+     * @param string $path
518
+     * @return mixed
519
+     */
520
+    public function isSharable($path) {
521
+        return $this->basicOperation('isSharable', $path);
522
+    }
523
+
524
+    /**
525
+     * @param string $path
526
+     * @return bool|mixed
527
+     */
528
+    public function file_exists($path) {
529
+        if ($path == '/') {
530
+            return true;
531
+        }
532
+        return $this->basicOperation('file_exists', $path);
533
+    }
534
+
535
+    /**
536
+     * @param string $path
537
+     * @return mixed
538
+     */
539
+    public function filemtime($path) {
540
+        return $this->basicOperation('filemtime', $path);
541
+    }
542
+
543
+    /**
544
+     * @param string $path
545
+     * @param int|string $mtime
546
+     * @return bool
547
+     */
548
+    public function touch($path, $mtime = null) {
549
+        if (!is_null($mtime) and !is_numeric($mtime)) {
550
+            $mtime = strtotime($mtime);
551
+        }
552
+
553
+        $hooks = array('touch');
554
+
555
+        if (!$this->file_exists($path)) {
556
+            $hooks[] = 'create';
557
+            $hooks[] = 'write';
558
+        }
559
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
560
+        if (!$result) {
561
+            // If create file fails because of permissions on external storage like SMB folders,
562
+            // check file exists and return false if not.
563
+            if (!$this->file_exists($path)) {
564
+                return false;
565
+            }
566
+            if (is_null($mtime)) {
567
+                $mtime = time();
568
+            }
569
+            //if native touch fails, we emulate it by changing the mtime in the cache
570
+            $this->putFileInfo($path, array('mtime' => floor($mtime)));
571
+        }
572
+        return true;
573
+    }
574
+
575
+    /**
576
+     * @param string $path
577
+     * @return mixed
578
+     */
579
+    public function file_get_contents($path) {
580
+        return $this->basicOperation('file_get_contents', $path, array('read'));
581
+    }
582
+
583
+    /**
584
+     * @param bool $exists
585
+     * @param string $path
586
+     * @param bool $run
587
+     */
588
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
589
+        if (!$exists) {
590
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
591
+                Filesystem::signal_param_path => $this->getHookPath($path),
592
+                Filesystem::signal_param_run => &$run,
593
+            ));
594
+        } else {
595
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
596
+                Filesystem::signal_param_path => $this->getHookPath($path),
597
+                Filesystem::signal_param_run => &$run,
598
+            ));
599
+        }
600
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
601
+            Filesystem::signal_param_path => $this->getHookPath($path),
602
+            Filesystem::signal_param_run => &$run,
603
+        ));
604
+    }
605
+
606
+    /**
607
+     * @param bool $exists
608
+     * @param string $path
609
+     */
610
+    protected function emit_file_hooks_post($exists, $path) {
611
+        if (!$exists) {
612
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
613
+                Filesystem::signal_param_path => $this->getHookPath($path),
614
+            ));
615
+        } else {
616
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
617
+                Filesystem::signal_param_path => $this->getHookPath($path),
618
+            ));
619
+        }
620
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
621
+            Filesystem::signal_param_path => $this->getHookPath($path),
622
+        ));
623
+    }
624
+
625
+    /**
626
+     * @param string $path
627
+     * @param mixed $data
628
+     * @return bool|mixed
629
+     * @throws \Exception
630
+     */
631
+    public function file_put_contents($path, $data) {
632
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
633
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
634
+            if (Filesystem::isValidPath($path)
635
+                and !Filesystem::isFileBlacklisted($path)
636
+            ) {
637
+                $path = $this->getRelativePath($absolutePath);
638
+
639
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
640
+
641
+                $exists = $this->file_exists($path);
642
+                $run = true;
643
+                if ($this->shouldEmitHooks($path)) {
644
+                    $this->emit_file_hooks_pre($exists, $path, $run);
645
+                }
646
+                if (!$run) {
647
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
648
+                    return false;
649
+                }
650
+
651
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
652
+
653
+                /** @var \OC\Files\Storage\Storage $storage */
654
+                list($storage, $internalPath) = $this->resolvePath($path);
655
+                $target = $storage->fopen($internalPath, 'w');
656
+                if ($target) {
657
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
658
+                    fclose($target);
659
+                    fclose($data);
660
+
661
+                    $this->writeUpdate($storage, $internalPath);
662
+
663
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
664
+
665
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
666
+                        $this->emit_file_hooks_post($exists, $path);
667
+                    }
668
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
669
+                    return $result;
670
+                } else {
671
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
672
+                    return false;
673
+                }
674
+            } else {
675
+                return false;
676
+            }
677
+        } else {
678
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
679
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
680
+        }
681
+    }
682
+
683
+    /**
684
+     * @param string $path
685
+     * @return bool|mixed
686
+     */
687
+    public function unlink($path) {
688
+        if ($path === '' || $path === '/') {
689
+            // do not allow deleting the root
690
+            return false;
691
+        }
692
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
693
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
694
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
695
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
696
+            return $this->removeMount($mount, $absolutePath);
697
+        }
698
+        if ($this->is_dir($path)) {
699
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
700
+        } else {
701
+            $result = $this->basicOperation('unlink', $path, ['delete']);
702
+        }
703
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
704
+            $storage = $mount->getStorage();
705
+            $internalPath = $mount->getInternalPath($absolutePath);
706
+            $storage->getUpdater()->remove($internalPath);
707
+            return true;
708
+        } else {
709
+            return $result;
710
+        }
711
+    }
712
+
713
+    /**
714
+     * @param string $directory
715
+     * @return bool|mixed
716
+     */
717
+    public function deleteAll($directory) {
718
+        return $this->rmdir($directory);
719
+    }
720
+
721
+    /**
722
+     * Rename/move a file or folder from the source path to target path.
723
+     *
724
+     * @param string $path1 source path
725
+     * @param string $path2 target path
726
+     *
727
+     * @return bool|mixed
728
+     */
729
+    public function rename($path1, $path2) {
730
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
731
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
732
+        $result = false;
733
+        if (
734
+            Filesystem::isValidPath($path2)
735
+            and Filesystem::isValidPath($path1)
736
+            and !Filesystem::isFileBlacklisted($path2)
737
+        ) {
738
+            $path1 = $this->getRelativePath($absolutePath1);
739
+            $path2 = $this->getRelativePath($absolutePath2);
740
+            $exists = $this->file_exists($path2);
741
+
742
+            if ($path1 == null or $path2 == null) {
743
+                return false;
744
+            }
745
+
746
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
747
+            try {
748
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
749
+            } catch (LockedException $e) {
750
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
751
+                throw $e;
752
+            }
753
+
754
+            $run = true;
755
+            if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
756
+                // if it was a rename from a part file to a regular file it was a write and not a rename operation
757
+                $this->emit_file_hooks_pre($exists, $path2, $run);
758
+            } elseif ($this->shouldEmitHooks($path1)) {
759
+                \OC_Hook::emit(
760
+                    Filesystem::CLASSNAME, Filesystem::signal_rename,
761
+                    array(
762
+                        Filesystem::signal_param_oldpath => $this->getHookPath($path1),
763
+                        Filesystem::signal_param_newpath => $this->getHookPath($path2),
764
+                        Filesystem::signal_param_run => &$run
765
+                    )
766
+                );
767
+            }
768
+            if ($run) {
769
+                $this->verifyPath(dirname($path2), basename($path2));
770
+
771
+                $manager = Filesystem::getMountManager();
772
+                $mount1 = $this->getMount($path1);
773
+                $mount2 = $this->getMount($path2);
774
+                $storage1 = $mount1->getStorage();
775
+                $storage2 = $mount2->getStorage();
776
+                $internalPath1 = $mount1->getInternalPath($absolutePath1);
777
+                $internalPath2 = $mount2->getInternalPath($absolutePath2);
778
+
779
+                $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
780
+                $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
781
+
782
+                if ($internalPath1 === '' and $mount1 instanceof MoveableMount) {
783
+                    if ($this->isTargetAllowed($absolutePath2)) {
784
+                        /**
785
+                         * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
786
+                         */
787
+                        $sourceMountPoint = $mount1->getMountPoint();
788
+                        $result = $mount1->moveMount($absolutePath2);
789
+                        $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
790
+                    } else {
791
+                        $result = false;
792
+                    }
793
+                    // moving a file/folder within the same mount point
794
+                } elseif ($storage1 === $storage2) {
795
+                    if ($storage1) {
796
+                        $result = $storage1->rename($internalPath1, $internalPath2);
797
+                    } else {
798
+                        $result = false;
799
+                    }
800
+                    // moving a file/folder between storages (from $storage1 to $storage2)
801
+                } else {
802
+                    $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
803
+                }
804
+
805
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
806
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
807
+
808
+                    $this->writeUpdate($storage2, $internalPath2);
809
+                } else if ($result) {
810
+                    if ($internalPath1 !== '') { // don't do a cache update for moved mounts
811
+                        $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
812
+                    }
813
+                }
814
+
815
+                $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
816
+                $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
817
+
818
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
819
+                    if ($this->shouldEmitHooks()) {
820
+                        $this->emit_file_hooks_post($exists, $path2);
821
+                    }
822
+                } elseif ($result) {
823
+                    if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
824
+                        \OC_Hook::emit(
825
+                            Filesystem::CLASSNAME,
826
+                            Filesystem::signal_post_rename,
827
+                            array(
828
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
829
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
830
+                            )
831
+                        );
832
+                    }
833
+                }
834
+            }
835
+            $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
836
+            $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
837
+        }
838
+        return $result;
839
+    }
840
+
841
+    /**
842
+     * Copy a file/folder from the source path to target path
843
+     *
844
+     * @param string $path1 source path
845
+     * @param string $path2 target path
846
+     * @param bool $preserveMtime whether to preserve mtime on the copy
847
+     *
848
+     * @return bool|mixed
849
+     */
850
+    public function copy($path1, $path2, $preserveMtime = false) {
851
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
852
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
853
+        $result = false;
854
+        if (
855
+            Filesystem::isValidPath($path2)
856
+            and Filesystem::isValidPath($path1)
857
+            and !Filesystem::isFileBlacklisted($path2)
858
+        ) {
859
+            $path1 = $this->getRelativePath($absolutePath1);
860
+            $path2 = $this->getRelativePath($absolutePath2);
861
+
862
+            if ($path1 == null or $path2 == null) {
863
+                return false;
864
+            }
865
+            $run = true;
866
+
867
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
868
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
869
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
870
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
871
+
872
+            try {
873
+
874
+                $exists = $this->file_exists($path2);
875
+                if ($this->shouldEmitHooks()) {
876
+                    \OC_Hook::emit(
877
+                        Filesystem::CLASSNAME,
878
+                        Filesystem::signal_copy,
879
+                        array(
880
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
881
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
882
+                            Filesystem::signal_param_run => &$run
883
+                        )
884
+                    );
885
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
886
+                }
887
+                if ($run) {
888
+                    $mount1 = $this->getMount($path1);
889
+                    $mount2 = $this->getMount($path2);
890
+                    $storage1 = $mount1->getStorage();
891
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
892
+                    $storage2 = $mount2->getStorage();
893
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
894
+
895
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
896
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
897
+
898
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
899
+                        if ($storage1) {
900
+                            $result = $storage1->copy($internalPath1, $internalPath2);
901
+                        } else {
902
+                            $result = false;
903
+                        }
904
+                    } else {
905
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
906
+                    }
907
+
908
+                    $this->writeUpdate($storage2, $internalPath2);
909
+
910
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
911
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
912
+
913
+                    if ($this->shouldEmitHooks() && $result !== false) {
914
+                        \OC_Hook::emit(
915
+                            Filesystem::CLASSNAME,
916
+                            Filesystem::signal_post_copy,
917
+                            array(
918
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
919
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
920
+                            )
921
+                        );
922
+                        $this->emit_file_hooks_post($exists, $path2);
923
+                    }
924
+
925
+                }
926
+            } catch (\Exception $e) {
927
+                $this->unlockFile($path2, $lockTypePath2);
928
+                $this->unlockFile($path1, $lockTypePath1);
929
+                throw $e;
930
+            }
931
+
932
+            $this->unlockFile($path2, $lockTypePath2);
933
+            $this->unlockFile($path1, $lockTypePath1);
934
+
935
+        }
936
+        return $result;
937
+    }
938
+
939
+    /**
940
+     * @param string $path
941
+     * @param string $mode 'r' or 'w'
942
+     * @return resource
943
+     */
944
+    public function fopen($path, $mode) {
945
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
946
+        $hooks = array();
947
+        switch ($mode) {
948
+            case 'r':
949
+                $hooks[] = 'read';
950
+                break;
951
+            case 'r+':
952
+            case 'w+':
953
+            case 'x+':
954
+            case 'a+':
955
+                $hooks[] = 'read';
956
+                $hooks[] = 'write';
957
+                break;
958
+            case 'w':
959
+            case 'x':
960
+            case 'a':
961
+                $hooks[] = 'write';
962
+                break;
963
+            default:
964
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
965
+        }
966
+
967
+        if ($mode !== 'r' && $mode !== 'w') {
968
+            \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');
969
+        }
970
+
971
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
972
+    }
973
+
974
+    /**
975
+     * @param string $path
976
+     * @return bool|string
977
+     * @throws \OCP\Files\InvalidPathException
978
+     */
979
+    public function toTmpFile($path) {
980
+        $this->assertPathLength($path);
981
+        if (Filesystem::isValidPath($path)) {
982
+            $source = $this->fopen($path, 'r');
983
+            if ($source) {
984
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
985
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
986
+                file_put_contents($tmpFile, $source);
987
+                return $tmpFile;
988
+            } else {
989
+                return false;
990
+            }
991
+        } else {
992
+            return false;
993
+        }
994
+    }
995
+
996
+    /**
997
+     * @param string $tmpFile
998
+     * @param string $path
999
+     * @return bool|mixed
1000
+     * @throws \OCP\Files\InvalidPathException
1001
+     */
1002
+    public function fromTmpFile($tmpFile, $path) {
1003
+        $this->assertPathLength($path);
1004
+        if (Filesystem::isValidPath($path)) {
1005
+
1006
+            // Get directory that the file is going into
1007
+            $filePath = dirname($path);
1008
+
1009
+            // Create the directories if any
1010
+            if (!$this->file_exists($filePath)) {
1011
+                $result = $this->createParentDirectories($filePath);
1012
+                if ($result === false) {
1013
+                    return false;
1014
+                }
1015
+            }
1016
+
1017
+            $source = fopen($tmpFile, 'r');
1018
+            if ($source) {
1019
+                $result = $this->file_put_contents($path, $source);
1020
+                // $this->file_put_contents() might have already closed
1021
+                // the resource, so we check it, before trying to close it
1022
+                // to avoid messages in the error log.
1023
+                if (is_resource($source)) {
1024
+                    fclose($source);
1025
+                }
1026
+                unlink($tmpFile);
1027
+                return $result;
1028
+            } else {
1029
+                return false;
1030
+            }
1031
+        } else {
1032
+            return false;
1033
+        }
1034
+    }
1035
+
1036
+
1037
+    /**
1038
+     * @param string $path
1039
+     * @return mixed
1040
+     * @throws \OCP\Files\InvalidPathException
1041
+     */
1042
+    public function getMimeType($path) {
1043
+        $this->assertPathLength($path);
1044
+        return $this->basicOperation('getMimeType', $path);
1045
+    }
1046
+
1047
+    /**
1048
+     * @param string $type
1049
+     * @param string $path
1050
+     * @param bool $raw
1051
+     * @return bool|null|string
1052
+     */
1053
+    public function hash($type, $path, $raw = false) {
1054
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1055
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1056
+        if (Filesystem::isValidPath($path)) {
1057
+            $path = $this->getRelativePath($absolutePath);
1058
+            if ($path == null) {
1059
+                return false;
1060
+            }
1061
+            if ($this->shouldEmitHooks($path)) {
1062
+                \OC_Hook::emit(
1063
+                    Filesystem::CLASSNAME,
1064
+                    Filesystem::signal_read,
1065
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1066
+                );
1067
+            }
1068
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1069
+            if ($storage) {
1070
+                $result = $storage->hash($type, $internalPath, $raw);
1071
+                return $result;
1072
+            }
1073
+        }
1074
+        return null;
1075
+    }
1076
+
1077
+    /**
1078
+     * @param string $path
1079
+     * @return mixed
1080
+     * @throws \OCP\Files\InvalidPathException
1081
+     */
1082
+    public function free_space($path = '/') {
1083
+        $this->assertPathLength($path);
1084
+        return $this->basicOperation('free_space', $path);
1085
+    }
1086
+
1087
+    /**
1088
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1089
+     *
1090
+     * @param string $operation
1091
+     * @param string $path
1092
+     * @param array $hooks (optional)
1093
+     * @param mixed $extraParam (optional)
1094
+     * @return mixed
1095
+     * @throws \Exception
1096
+     *
1097
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1098
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1099
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1100
+     */
1101
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1102
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1103
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1104
+        if (Filesystem::isValidPath($path)
1105
+            and !Filesystem::isFileBlacklisted($path)
1106
+        ) {
1107
+            $path = $this->getRelativePath($absolutePath);
1108
+            if ($path == null) {
1109
+                return false;
1110
+            }
1111
+
1112
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1113
+                // always a shared lock during pre-hooks so the hook can read the file
1114
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1115
+            }
1116
+
1117
+            $run = $this->runHooks($hooks, $path);
1118
+            /** @var \OC\Files\Storage\Storage $storage */
1119
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1120
+            if ($run and $storage) {
1121
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1122
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1123
+                }
1124
+                try {
1125
+                    if (!is_null($extraParam)) {
1126
+                        $result = $storage->$operation($internalPath, $extraParam);
1127
+                    } else {
1128
+                        $result = $storage->$operation($internalPath);
1129
+                    }
1130
+                } catch (\Exception $e) {
1131
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1132
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1133
+                    } else if (in_array('read', $hooks)) {
1134
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1135
+                    }
1136
+                    throw $e;
1137
+                }
1138
+
1139
+                if ($result && in_array('delete', $hooks) and $result) {
1140
+                    $this->removeUpdate($storage, $internalPath);
1141
+                }
1142
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1143
+                    $this->writeUpdate($storage, $internalPath);
1144
+                }
1145
+                if ($result && in_array('touch', $hooks)) {
1146
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1147
+                }
1148
+
1149
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1150
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1151
+                }
1152
+
1153
+                $unlockLater = false;
1154
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1155
+                    $unlockLater = true;
1156
+                    // make sure our unlocking callback will still be called if connection is aborted
1157
+                    ignore_user_abort(true);
1158
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1159
+                        if (in_array('write', $hooks)) {
1160
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1161
+                        } else if (in_array('read', $hooks)) {
1162
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1163
+                        }
1164
+                    });
1165
+                }
1166
+
1167
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1168
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1169
+                        $this->runHooks($hooks, $path, true);
1170
+                    }
1171
+                }
1172
+
1173
+                if (!$unlockLater
1174
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1175
+                ) {
1176
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1177
+                }
1178
+                return $result;
1179
+            } else {
1180
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1181
+            }
1182
+        }
1183
+        return null;
1184
+    }
1185
+
1186
+    /**
1187
+     * get the path relative to the default root for hook usage
1188
+     *
1189
+     * @param string $path
1190
+     * @return string
1191
+     */
1192
+    private function getHookPath($path) {
1193
+        if (!Filesystem::getView()) {
1194
+            return $path;
1195
+        }
1196
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1197
+    }
1198
+
1199
+    private function shouldEmitHooks($path = '') {
1200
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1201
+            return false;
1202
+        }
1203
+        if (!Filesystem::$loaded) {
1204
+            return false;
1205
+        }
1206
+        $defaultRoot = Filesystem::getRoot();
1207
+        if ($defaultRoot === null) {
1208
+            return false;
1209
+        }
1210
+        if ($this->fakeRoot === $defaultRoot) {
1211
+            return true;
1212
+        }
1213
+        $fullPath = $this->getAbsolutePath($path);
1214
+
1215
+        if ($fullPath === $defaultRoot) {
1216
+            return true;
1217
+        }
1218
+
1219
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1220
+    }
1221
+
1222
+    /**
1223
+     * @param string[] $hooks
1224
+     * @param string $path
1225
+     * @param bool $post
1226
+     * @return bool
1227
+     */
1228
+    private function runHooks($hooks, $path, $post = false) {
1229
+        $relativePath = $path;
1230
+        $path = $this->getHookPath($path);
1231
+        $prefix = ($post) ? 'post_' : '';
1232
+        $run = true;
1233
+        if ($this->shouldEmitHooks($relativePath)) {
1234
+            foreach ($hooks as $hook) {
1235
+                if ($hook != 'read') {
1236
+                    \OC_Hook::emit(
1237
+                        Filesystem::CLASSNAME,
1238
+                        $prefix . $hook,
1239
+                        array(
1240
+                            Filesystem::signal_param_run => &$run,
1241
+                            Filesystem::signal_param_path => $path
1242
+                        )
1243
+                    );
1244
+                } elseif (!$post) {
1245
+                    \OC_Hook::emit(
1246
+                        Filesystem::CLASSNAME,
1247
+                        $prefix . $hook,
1248
+                        array(
1249
+                            Filesystem::signal_param_path => $path
1250
+                        )
1251
+                    );
1252
+                }
1253
+            }
1254
+        }
1255
+        return $run;
1256
+    }
1257
+
1258
+    /**
1259
+     * check if a file or folder has been updated since $time
1260
+     *
1261
+     * @param string $path
1262
+     * @param int $time
1263
+     * @return bool
1264
+     */
1265
+    public function hasUpdated($path, $time) {
1266
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1267
+    }
1268
+
1269
+    /**
1270
+     * @param string $ownerId
1271
+     * @return \OC\User\User
1272
+     */
1273
+    private function getUserObjectForOwner($ownerId) {
1274
+        $owner = $this->userManager->get($ownerId);
1275
+        if ($owner instanceof IUser) {
1276
+            return $owner;
1277
+        } else {
1278
+            return new User($ownerId, null);
1279
+        }
1280
+    }
1281
+
1282
+    /**
1283
+     * Get file info from cache
1284
+     *
1285
+     * If the file is not in cached it will be scanned
1286
+     * If the file has changed on storage the cache will be updated
1287
+     *
1288
+     * @param \OC\Files\Storage\Storage $storage
1289
+     * @param string $internalPath
1290
+     * @param string $relativePath
1291
+     * @return array|bool
1292
+     */
1293
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1294
+        $cache = $storage->getCache($internalPath);
1295
+        $data = $cache->get($internalPath);
1296
+        $watcher = $storage->getWatcher($internalPath);
1297
+
1298
+        try {
1299
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1300
+            if (!$data || $data['size'] === -1) {
1301
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1302
+                if (!$storage->file_exists($internalPath)) {
1303
+                    $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1304
+                    return false;
1305
+                }
1306
+                $scanner = $storage->getScanner($internalPath);
1307
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1308
+                $data = $cache->get($internalPath);
1309
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1310
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1311
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1312
+                $watcher->update($internalPath, $data);
1313
+                $storage->getPropagator()->propagateChange($internalPath, time());
1314
+                $data = $cache->get($internalPath);
1315
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1316
+            }
1317
+        } catch (LockedException $e) {
1318
+            // if the file is locked we just use the old cache info
1319
+        }
1320
+
1321
+        return $data;
1322
+    }
1323
+
1324
+    /**
1325
+     * get the filesystem info
1326
+     *
1327
+     * @param string $path
1328
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1329
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1330
+     * defaults to true
1331
+     * @return \OC\Files\FileInfo|false False if file does not exist
1332
+     */
1333
+    public function getFileInfo($path, $includeMountPoints = true) {
1334
+        $this->assertPathLength($path);
1335
+        if (!Filesystem::isValidPath($path)) {
1336
+            return false;
1337
+        }
1338
+        if (Cache\Scanner::isPartialFile($path)) {
1339
+            return $this->getPartFileInfo($path);
1340
+        }
1341
+        $relativePath = $path;
1342
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1343
+
1344
+        $mount = Filesystem::getMountManager()->find($path);
1345
+        $storage = $mount->getStorage();
1346
+        $internalPath = $mount->getInternalPath($path);
1347
+        if ($storage) {
1348
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1349
+
1350
+            if (!$data instanceof ICacheEntry) {
1351
+                return false;
1352
+            }
1353
+
1354
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1355
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1356
+            }
1357
+
1358
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1359
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1360
+
1361
+            if ($data and isset($data['fileid'])) {
1362
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1363
+                    //add the sizes of other mount points to the folder
1364
+                    $extOnly = ($includeMountPoints === 'ext');
1365
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1366
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1367
+                        $subStorage = $mount->getStorage();
1368
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1369
+                    }));
1370
+                }
1371
+            }
1372
+
1373
+            return $info;
1374
+        }
1375
+
1376
+        return false;
1377
+    }
1378
+
1379
+    /**
1380
+     * get the content of a directory
1381
+     *
1382
+     * @param string $directory path under datadirectory
1383
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1384
+     * @return FileInfo[]
1385
+     */
1386
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1387
+        $this->assertPathLength($directory);
1388
+        if (!Filesystem::isValidPath($directory)) {
1389
+            return [];
1390
+        }
1391
+        $path = $this->getAbsolutePath($directory);
1392
+        $path = Filesystem::normalizePath($path);
1393
+        $mount = $this->getMount($directory);
1394
+        $storage = $mount->getStorage();
1395
+        $internalPath = $mount->getInternalPath($path);
1396
+        if ($storage) {
1397
+            $cache = $storage->getCache($internalPath);
1398
+            $user = \OC_User::getUser();
1399
+
1400
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1401
+
1402
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1403
+                return [];
1404
+            }
1405
+
1406
+            $folderId = $data['fileid'];
1407
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1408
+
1409
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1410
+            /**
1411
+             * @var \OC\Files\FileInfo[] $files
1412
+             */
1413
+            $files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1414
+                if ($sharingDisabled) {
1415
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1416
+                }
1417
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1418
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1419
+            }, $contents);
1420
+
1421
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1422
+            $mounts = Filesystem::getMountManager()->findIn($path);
1423
+            $dirLength = strlen($path);
1424
+            foreach ($mounts as $mount) {
1425
+                $mountPoint = $mount->getMountPoint();
1426
+                $subStorage = $mount->getStorage();
1427
+                if ($subStorage) {
1428
+                    $subCache = $subStorage->getCache('');
1429
+
1430
+                    $rootEntry = $subCache->get('');
1431
+                    if (!$rootEntry) {
1432
+                        $subScanner = $subStorage->getScanner('');
1433
+                        try {
1434
+                            $subScanner->scanFile('');
1435
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1436
+                            continue;
1437
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1438
+                            continue;
1439
+                        } catch (\Exception $e) {
1440
+                            // sometimes when the storage is not available it can be any exception
1441
+                            \OCP\Util::writeLog(
1442
+                                'core',
1443
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1444
+                                get_class($e) . ': ' . $e->getMessage(),
1445
+                                \OCP\Util::ERROR
1446
+                            );
1447
+                            continue;
1448
+                        }
1449
+                        $rootEntry = $subCache->get('');
1450
+                    }
1451
+
1452
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1453
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1454
+                        if ($pos = strpos($relativePath, '/')) {
1455
+                            //mountpoint inside subfolder add size to the correct folder
1456
+                            $entryName = substr($relativePath, 0, $pos);
1457
+                            foreach ($files as &$entry) {
1458
+                                if ($entry->getName() === $entryName) {
1459
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1460
+                                }
1461
+                            }
1462
+                        } else { //mountpoint in this folder, add an entry for it
1463
+                            $rootEntry['name'] = $relativePath;
1464
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1465
+                            $permissions = $rootEntry['permissions'];
1466
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1467
+                            // for shared files/folders we use the permissions given by the owner
1468
+                            if ($mount instanceof MoveableMount) {
1469
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1470
+                            } else {
1471
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1472
+                            }
1473
+
1474
+                            //remove any existing entry with the same name
1475
+                            foreach ($files as $i => $file) {
1476
+                                if ($file['name'] === $rootEntry['name']) {
1477
+                                    unset($files[$i]);
1478
+                                    break;
1479
+                                }
1480
+                            }
1481
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1482
+
1483
+                            // if sharing was disabled for the user we remove the share permissions
1484
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1485
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1486
+                            }
1487
+
1488
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1489
+                            $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1490
+                        }
1491
+                    }
1492
+                }
1493
+            }
1494
+
1495
+            if ($mimetype_filter) {
1496
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1497
+                    if (strpos($mimetype_filter, '/')) {
1498
+                        return $file->getMimetype() === $mimetype_filter;
1499
+                    } else {
1500
+                        return $file->getMimePart() === $mimetype_filter;
1501
+                    }
1502
+                });
1503
+            }
1504
+
1505
+            return $files;
1506
+        } else {
1507
+            return [];
1508
+        }
1509
+    }
1510
+
1511
+    /**
1512
+     * change file metadata
1513
+     *
1514
+     * @param string $path
1515
+     * @param array|\OCP\Files\FileInfo $data
1516
+     * @return int
1517
+     *
1518
+     * returns the fileid of the updated file
1519
+     */
1520
+    public function putFileInfo($path, $data) {
1521
+        $this->assertPathLength($path);
1522
+        if ($data instanceof FileInfo) {
1523
+            $data = $data->getData();
1524
+        }
1525
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1526
+        /**
1527
+         * @var \OC\Files\Storage\Storage $storage
1528
+         * @var string $internalPath
1529
+         */
1530
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1531
+        if ($storage) {
1532
+            $cache = $storage->getCache($path);
1533
+
1534
+            if (!$cache->inCache($internalPath)) {
1535
+                $scanner = $storage->getScanner($internalPath);
1536
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1537
+            }
1538
+
1539
+            return $cache->put($internalPath, $data);
1540
+        } else {
1541
+            return -1;
1542
+        }
1543
+    }
1544
+
1545
+    /**
1546
+     * search for files with the name matching $query
1547
+     *
1548
+     * @param string $query
1549
+     * @return FileInfo[]
1550
+     */
1551
+    public function search($query) {
1552
+        return $this->searchCommon('search', array('%' . $query . '%'));
1553
+    }
1554
+
1555
+    /**
1556
+     * search for files with the name matching $query
1557
+     *
1558
+     * @param string $query
1559
+     * @return FileInfo[]
1560
+     */
1561
+    public function searchRaw($query) {
1562
+        return $this->searchCommon('search', array($query));
1563
+    }
1564
+
1565
+    /**
1566
+     * search for files by mimetype
1567
+     *
1568
+     * @param string $mimetype
1569
+     * @return FileInfo[]
1570
+     */
1571
+    public function searchByMime($mimetype) {
1572
+        return $this->searchCommon('searchByMime', array($mimetype));
1573
+    }
1574
+
1575
+    /**
1576
+     * search for files by tag
1577
+     *
1578
+     * @param string|int $tag name or tag id
1579
+     * @param string $userId owner of the tags
1580
+     * @return FileInfo[]
1581
+     */
1582
+    public function searchByTag($tag, $userId) {
1583
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1584
+    }
1585
+
1586
+    /**
1587
+     * @param string $method cache method
1588
+     * @param array $args
1589
+     * @return FileInfo[]
1590
+     */
1591
+    private function searchCommon($method, $args) {
1592
+        $files = array();
1593
+        $rootLength = strlen($this->fakeRoot);
1594
+
1595
+        $mount = $this->getMount('');
1596
+        $mountPoint = $mount->getMountPoint();
1597
+        $storage = $mount->getStorage();
1598
+        if ($storage) {
1599
+            $cache = $storage->getCache('');
1600
+
1601
+            $results = call_user_func_array(array($cache, $method), $args);
1602
+            foreach ($results as $result) {
1603
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1604
+                    $internalPath = $result['path'];
1605
+                    $path = $mountPoint . $result['path'];
1606
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1607
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1608
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1609
+                }
1610
+            }
1611
+
1612
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1613
+            foreach ($mounts as $mount) {
1614
+                $mountPoint = $mount->getMountPoint();
1615
+                $storage = $mount->getStorage();
1616
+                if ($storage) {
1617
+                    $cache = $storage->getCache('');
1618
+
1619
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1620
+                    $results = call_user_func_array(array($cache, $method), $args);
1621
+                    if ($results) {
1622
+                        foreach ($results as $result) {
1623
+                            $internalPath = $result['path'];
1624
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1625
+                            $path = rtrim($mountPoint . $internalPath, '/');
1626
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1627
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1628
+                        }
1629
+                    }
1630
+                }
1631
+            }
1632
+        }
1633
+        return $files;
1634
+    }
1635
+
1636
+    /**
1637
+     * Get the owner for a file or folder
1638
+     *
1639
+     * @param string $path
1640
+     * @return string the user id of the owner
1641
+     * @throws NotFoundException
1642
+     */
1643
+    public function getOwner($path) {
1644
+        $info = $this->getFileInfo($path);
1645
+        if (!$info) {
1646
+            throw new NotFoundException($path . ' not found while trying to get owner');
1647
+        }
1648
+        return $info->getOwner()->getUID();
1649
+    }
1650
+
1651
+    /**
1652
+     * get the ETag for a file or folder
1653
+     *
1654
+     * @param string $path
1655
+     * @return string
1656
+     */
1657
+    public function getETag($path) {
1658
+        /**
1659
+         * @var Storage\Storage $storage
1660
+         * @var string $internalPath
1661
+         */
1662
+        list($storage, $internalPath) = $this->resolvePath($path);
1663
+        if ($storage) {
1664
+            return $storage->getETag($internalPath);
1665
+        } else {
1666
+            return null;
1667
+        }
1668
+    }
1669
+
1670
+    /**
1671
+     * Get the path of a file by id, relative to the view
1672
+     *
1673
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1674
+     *
1675
+     * @param int $id
1676
+     * @throws NotFoundException
1677
+     * @return string
1678
+     */
1679
+    public function getPath($id) {
1680
+        $id = (int)$id;
1681
+        $manager = Filesystem::getMountManager();
1682
+        $mounts = $manager->findIn($this->fakeRoot);
1683
+        $mounts[] = $manager->find($this->fakeRoot);
1684
+        // reverse the array so we start with the storage this view is in
1685
+        // which is the most likely to contain the file we're looking for
1686
+        $mounts = array_reverse($mounts);
1687
+        foreach ($mounts as $mount) {
1688
+            /**
1689
+             * @var \OC\Files\Mount\MountPoint $mount
1690
+             */
1691
+            if ($mount->getStorage()) {
1692
+                $cache = $mount->getStorage()->getCache();
1693
+                $internalPath = $cache->getPathById($id);
1694
+                if (is_string($internalPath)) {
1695
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1696
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1697
+                        return $path;
1698
+                    }
1699
+                }
1700
+            }
1701
+        }
1702
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1703
+    }
1704
+
1705
+    /**
1706
+     * @param string $path
1707
+     * @throws InvalidPathException
1708
+     */
1709
+    private function assertPathLength($path) {
1710
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1711
+        // Check for the string length - performed using isset() instead of strlen()
1712
+        // because isset() is about 5x-40x faster.
1713
+        if (isset($path[$maxLen])) {
1714
+            $pathLen = strlen($path);
1715
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1716
+        }
1717
+    }
1718
+
1719
+    /**
1720
+     * check if it is allowed to move a mount point to a given target.
1721
+     * It is not allowed to move a mount point into a different mount point or
1722
+     * into an already shared folder
1723
+     *
1724
+     * @param string $target path
1725
+     * @return boolean
1726
+     */
1727
+    private function isTargetAllowed($target) {
1728
+
1729
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1730
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1731
+            \OCP\Util::writeLog('files',
1732
+                'It is not allowed to move one mount point into another one',
1733
+                \OCP\Util::DEBUG);
1734
+            return false;
1735
+        }
1736
+
1737
+        // note: cannot use the view because the target is already locked
1738
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1739
+        if ($fileId === -1) {
1740
+            // target might not exist, need to check parent instead
1741
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1742
+        }
1743
+
1744
+        // check if any of the parents were shared by the current owner (include collections)
1745
+        $shares = \OCP\Share::getItemShared(
1746
+            'folder',
1747
+            $fileId,
1748
+            \OCP\Share::FORMAT_NONE,
1749
+            null,
1750
+            true
1751
+        );
1752
+
1753
+        if (count($shares) > 0) {
1754
+            \OCP\Util::writeLog('files',
1755
+                'It is not allowed to move one mount point into a shared folder',
1756
+                \OCP\Util::DEBUG);
1757
+            return false;
1758
+        }
1759
+
1760
+        return true;
1761
+    }
1762
+
1763
+    /**
1764
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1765
+     *
1766
+     * @param string $path
1767
+     * @return \OCP\Files\FileInfo
1768
+     */
1769
+    private function getPartFileInfo($path) {
1770
+        $mount = $this->getMount($path);
1771
+        $storage = $mount->getStorage();
1772
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1773
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1774
+        return new FileInfo(
1775
+            $this->getAbsolutePath($path),
1776
+            $storage,
1777
+            $internalPath,
1778
+            [
1779
+                'fileid' => null,
1780
+                'mimetype' => $storage->getMimeType($internalPath),
1781
+                'name' => basename($path),
1782
+                'etag' => null,
1783
+                'size' => $storage->filesize($internalPath),
1784
+                'mtime' => $storage->filemtime($internalPath),
1785
+                'encrypted' => false,
1786
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1787
+            ],
1788
+            $mount,
1789
+            $owner
1790
+        );
1791
+    }
1792
+
1793
+    /**
1794
+     * @param string $path
1795
+     * @param string $fileName
1796
+     * @throws InvalidPathException
1797
+     */
1798
+    public function verifyPath($path, $fileName) {
1799
+        try {
1800
+            /** @type \OCP\Files\Storage $storage */
1801
+            list($storage, $internalPath) = $this->resolvePath($path);
1802
+            $storage->verifyPath($internalPath, $fileName);
1803
+        } catch (ReservedWordException $ex) {
1804
+            $l = \OC::$server->getL10N('lib');
1805
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1806
+        } catch (InvalidCharacterInPathException $ex) {
1807
+            $l = \OC::$server->getL10N('lib');
1808
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1809
+        } catch (FileNameTooLongException $ex) {
1810
+            $l = \OC::$server->getL10N('lib');
1811
+            throw new InvalidPathException($l->t('File name is too long'));
1812
+        } catch (InvalidDirectoryException $ex) {
1813
+            $l = \OC::$server->getL10N('lib');
1814
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1815
+        } catch (EmptyFileNameException $ex) {
1816
+            $l = \OC::$server->getL10N('lib');
1817
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1818
+        }
1819
+    }
1820
+
1821
+    /**
1822
+     * get all parent folders of $path
1823
+     *
1824
+     * @param string $path
1825
+     * @return string[]
1826
+     */
1827
+    private function getParents($path) {
1828
+        $path = trim($path, '/');
1829
+        if (!$path) {
1830
+            return [];
1831
+        }
1832
+
1833
+        $parts = explode('/', $path);
1834
+
1835
+        // remove the single file
1836
+        array_pop($parts);
1837
+        $result = array('/');
1838
+        $resultPath = '';
1839
+        foreach ($parts as $part) {
1840
+            if ($part) {
1841
+                $resultPath .= '/' . $part;
1842
+                $result[] = $resultPath;
1843
+            }
1844
+        }
1845
+        return $result;
1846
+    }
1847
+
1848
+    /**
1849
+     * Returns the mount point for which to lock
1850
+     *
1851
+     * @param string $absolutePath absolute path
1852
+     * @param bool $useParentMount true to return parent mount instead of whatever
1853
+     * is mounted directly on the given path, false otherwise
1854
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1855
+     */
1856
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1857
+        $results = [];
1858
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1859
+        if (!$mount) {
1860
+            return $results;
1861
+        }
1862
+
1863
+        if ($useParentMount) {
1864
+            // find out if something is mounted directly on the path
1865
+            $internalPath = $mount->getInternalPath($absolutePath);
1866
+            if ($internalPath === '') {
1867
+                // resolve the parent mount instead
1868
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1869
+            }
1870
+        }
1871
+
1872
+        return $mount;
1873
+    }
1874
+
1875
+    /**
1876
+     * Lock the given path
1877
+     *
1878
+     * @param string $path the path of the file to lock, relative to the view
1879
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1880
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1881
+     *
1882
+     * @return bool False if the path is excluded from locking, true otherwise
1883
+     * @throws \OCP\Lock\LockedException if the path is already locked
1884
+     */
1885
+    private function lockPath($path, $type, $lockMountPoint = false) {
1886
+        $absolutePath = $this->getAbsolutePath($path);
1887
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1888
+        if (!$this->shouldLockFile($absolutePath)) {
1889
+            return false;
1890
+        }
1891
+
1892
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1893
+        if ($mount) {
1894
+            try {
1895
+                $storage = $mount->getStorage();
1896
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1897
+                    $storage->acquireLock(
1898
+                        $mount->getInternalPath($absolutePath),
1899
+                        $type,
1900
+                        $this->lockingProvider
1901
+                    );
1902
+                }
1903
+            } catch (\OCP\Lock\LockedException $e) {
1904
+                // rethrow with the a human-readable path
1905
+                throw new \OCP\Lock\LockedException(
1906
+                    $this->getPathRelativeToFiles($absolutePath),
1907
+                    $e
1908
+                );
1909
+            }
1910
+        }
1911
+
1912
+        return true;
1913
+    }
1914
+
1915
+    /**
1916
+     * Change the lock type
1917
+     *
1918
+     * @param string $path the path of the file to lock, relative to the view
1919
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1920
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1921
+     *
1922
+     * @return bool False if the path is excluded from locking, true otherwise
1923
+     * @throws \OCP\Lock\LockedException if the path is already locked
1924
+     */
1925
+    public function changeLock($path, $type, $lockMountPoint = false) {
1926
+        $path = Filesystem::normalizePath($path);
1927
+        $absolutePath = $this->getAbsolutePath($path);
1928
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1929
+        if (!$this->shouldLockFile($absolutePath)) {
1930
+            return false;
1931
+        }
1932
+
1933
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1934
+        if ($mount) {
1935
+            try {
1936
+                $storage = $mount->getStorage();
1937
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1938
+                    $storage->changeLock(
1939
+                        $mount->getInternalPath($absolutePath),
1940
+                        $type,
1941
+                        $this->lockingProvider
1942
+                    );
1943
+                }
1944
+            } catch (\OCP\Lock\LockedException $e) {
1945
+                // rethrow with the a human-readable path
1946
+                throw new \OCP\Lock\LockedException(
1947
+                    $this->getPathRelativeToFiles($absolutePath),
1948
+                    $e
1949
+                );
1950
+            }
1951
+        }
1952
+
1953
+        return true;
1954
+    }
1955
+
1956
+    /**
1957
+     * Unlock the given path
1958
+     *
1959
+     * @param string $path the path of the file to unlock, relative to the view
1960
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1961
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1962
+     *
1963
+     * @return bool False if the path is excluded from locking, true otherwise
1964
+     */
1965
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1966
+        $absolutePath = $this->getAbsolutePath($path);
1967
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1968
+        if (!$this->shouldLockFile($absolutePath)) {
1969
+            return false;
1970
+        }
1971
+
1972
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1973
+        if ($mount) {
1974
+            $storage = $mount->getStorage();
1975
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1976
+                $storage->releaseLock(
1977
+                    $mount->getInternalPath($absolutePath),
1978
+                    $type,
1979
+                    $this->lockingProvider
1980
+                );
1981
+            }
1982
+        }
1983
+
1984
+        return true;
1985
+    }
1986
+
1987
+    /**
1988
+     * Lock a path and all its parents up to the root of the view
1989
+     *
1990
+     * @param string $path the path of the file to lock relative to the view
1991
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1992
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1993
+     *
1994
+     * @return bool False if the path is excluded from locking, true otherwise
1995
+     */
1996
+    public function lockFile($path, $type, $lockMountPoint = false) {
1997
+        $absolutePath = $this->getAbsolutePath($path);
1998
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1999
+        if (!$this->shouldLockFile($absolutePath)) {
2000
+            return false;
2001
+        }
2002
+
2003
+        $this->lockPath($path, $type, $lockMountPoint);
2004
+
2005
+        $parents = $this->getParents($path);
2006
+        foreach ($parents as $parent) {
2007
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2008
+        }
2009
+
2010
+        return true;
2011
+    }
2012
+
2013
+    /**
2014
+     * Unlock a path and all its parents up to the root of the view
2015
+     *
2016
+     * @param string $path the path of the file to lock 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
+     */
2022
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2023
+        $absolutePath = $this->getAbsolutePath($path);
2024
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2025
+        if (!$this->shouldLockFile($absolutePath)) {
2026
+            return false;
2027
+        }
2028
+
2029
+        $this->unlockPath($path, $type, $lockMountPoint);
2030
+
2031
+        $parents = $this->getParents($path);
2032
+        foreach ($parents as $parent) {
2033
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2034
+        }
2035
+
2036
+        return true;
2037
+    }
2038
+
2039
+    /**
2040
+     * Only lock files in data/user/files/
2041
+     *
2042
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2043
+     * @return bool
2044
+     */
2045
+    protected function shouldLockFile($path) {
2046
+        $path = Filesystem::normalizePath($path);
2047
+
2048
+        $pathSegments = explode('/', $path);
2049
+        if (isset($pathSegments[2])) {
2050
+            // E.g.: /username/files/path-to-file
2051
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2052
+        }
2053
+
2054
+        return true;
2055
+    }
2056
+
2057
+    /**
2058
+     * Shortens the given absolute path to be relative to
2059
+     * "$user/files".
2060
+     *
2061
+     * @param string $absolutePath absolute path which is under "files"
2062
+     *
2063
+     * @return string path relative to "files" with trimmed slashes or null
2064
+     * if the path was NOT relative to files
2065
+     *
2066
+     * @throws \InvalidArgumentException if the given path was not under "files"
2067
+     * @since 8.1.0
2068
+     */
2069
+    public function getPathRelativeToFiles($absolutePath) {
2070
+        $path = Filesystem::normalizePath($absolutePath);
2071
+        $parts = explode('/', trim($path, '/'), 3);
2072
+        // "$user", "files", "path/to/dir"
2073
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2074
+            $this->logger->error(
2075
+                '$absolutePath must be relative to "files", value is "%s"',
2076
+                [
2077
+                    $absolutePath
2078
+                ]
2079
+            );
2080
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2081
+        }
2082
+        if (isset($parts[2])) {
2083
+            return $parts[2];
2084
+        }
2085
+        return '';
2086
+    }
2087
+
2088
+    /**
2089
+     * @param string $filename
2090
+     * @return array
2091
+     * @throws \OC\User\NoUserException
2092
+     * @throws NotFoundException
2093
+     */
2094
+    public function getUidAndFilename($filename) {
2095
+        $info = $this->getFileInfo($filename);
2096
+        if (!$info instanceof \OCP\Files\FileInfo) {
2097
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2098
+        }
2099
+        $uid = $info->getOwner()->getUID();
2100
+        if ($uid != \OCP\User::getUser()) {
2101
+            Filesystem::initMountPoints($uid);
2102
+            $ownerView = new View('/' . $uid . '/files');
2103
+            try {
2104
+                $filename = $ownerView->getPath($info['fileid']);
2105
+            } catch (NotFoundException $e) {
2106
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2107
+            }
2108
+        }
2109
+        return [$uid, $filename];
2110
+    }
2111
+
2112
+    /**
2113
+     * Creates parent non-existing folders
2114
+     *
2115
+     * @param string $filePath
2116
+     * @return bool
2117
+     */
2118
+    private function createParentDirectories($filePath) {
2119
+        $directoryParts = explode('/', $filePath);
2120
+        $directoryParts = array_filter($directoryParts);
2121
+        foreach ($directoryParts as $key => $part) {
2122
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2123
+            $currentPath = '/' . implode('/', $currentPathElements);
2124
+            if ($this->is_file($currentPath)) {
2125
+                return false;
2126
+            }
2127
+            if (!$this->file_exists($currentPath)) {
2128
+                $this->mkdir($currentPath);
2129
+            }
2130
+        }
2131
+
2132
+        return true;
2133
+    }
2134 2134
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/Directory.php 2 patches
Indentation   +393 added lines, -393 removed lines patch added patch discarded remove patch
@@ -47,397 +47,397 @@
 block discarded – undo
47 47
 use Sabre\DAV\Exception\NotFound;
48 48
 
49 49
 class Directory extends \OCA\DAV\Connector\Sabre\Node
50
-	implements \Sabre\DAV\ICollection, \Sabre\DAV\IQuota, \Sabre\DAV\IMoveTarget {
51
-
52
-	/**
53
-	 * Cached directory content
54
-	 *
55
-	 * @var \OCP\Files\FileInfo[]
56
-	 */
57
-	private $dirContent;
58
-
59
-	/**
60
-	 * Cached quota info
61
-	 *
62
-	 * @var array
63
-	 */
64
-	private $quotaInfo;
65
-
66
-	/**
67
-	 * @var ObjectTree|null
68
-	 */
69
-	private $tree;
70
-
71
-	/**
72
-	 * Sets up the node, expects a full path name
73
-	 *
74
-	 * @param \OC\Files\View $view
75
-	 * @param \OCP\Files\FileInfo $info
76
-	 * @param ObjectTree|null $tree
77
-	 * @param \OCP\Share\IManager $shareManager
78
-	 */
79
-	public function __construct($view, $info, $tree = null, $shareManager = null) {
80
-		parent::__construct($view, $info, $shareManager);
81
-		$this->tree = $tree;
82
-	}
83
-
84
-	/**
85
-	 * Creates a new file in the directory
86
-	 *
87
-	 * Data will either be supplied as a stream resource, or in certain cases
88
-	 * as a string. Keep in mind that you may have to support either.
89
-	 *
90
-	 * After successful creation of the file, you may choose to return the ETag
91
-	 * of the new file here.
92
-	 *
93
-	 * The returned ETag must be surrounded by double-quotes (The quotes should
94
-	 * be part of the actual string).
95
-	 *
96
-	 * If you cannot accurately determine the ETag, you should not return it.
97
-	 * If you don't store the file exactly as-is (you're transforming it
98
-	 * somehow) you should also not return an ETag.
99
-	 *
100
-	 * This means that if a subsequent GET to this new file does not exactly
101
-	 * return the same contents of what was submitted here, you are strongly
102
-	 * recommended to omit the ETag.
103
-	 *
104
-	 * @param string $name Name of the file
105
-	 * @param resource|string $data Initial payload
106
-	 * @return null|string
107
-	 * @throws Exception\EntityTooLarge
108
-	 * @throws Exception\UnsupportedMediaType
109
-	 * @throws FileLocked
110
-	 * @throws InvalidPath
111
-	 * @throws \Sabre\DAV\Exception
112
-	 * @throws \Sabre\DAV\Exception\BadRequest
113
-	 * @throws \Sabre\DAV\Exception\Forbidden
114
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
115
-	 */
116
-	public function createFile($name, $data = null) {
117
-
118
-		try {
119
-			// for chunked upload also updating a existing file is a "createFile"
120
-			// because we create all the chunks before re-assemble them to the existing file.
121
-			if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
122
-
123
-				// exit if we can't create a new file and we don't updatable existing file
124
-				$chunkInfo = \OC_FileChunking::decodeName($name);
125
-				if (!$this->fileView->isCreatable($this->path) &&
126
-					!$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
127
-				) {
128
-					throw new \Sabre\DAV\Exception\Forbidden();
129
-				}
130
-
131
-			} else {
132
-				// For non-chunked upload it is enough to check if we can create a new file
133
-				if (!$this->fileView->isCreatable($this->path)) {
134
-					throw new \Sabre\DAV\Exception\Forbidden();
135
-				}
136
-			}
137
-
138
-			$this->fileView->verifyPath($this->path, $name);
139
-
140
-			$path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
141
-			// in case the file already exists/overwriting
142
-			$info = $this->fileView->getFileInfo($this->path . '/' . $name);
143
-			if (!$info) {
144
-				// use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
145
-				$info = new \OC\Files\FileInfo($path, null, null, [], null);
146
-			}
147
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
148
-			$node->acquireLock(ILockingProvider::LOCK_SHARED);
149
-			return $node->put($data);
150
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
151
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
152
-		} catch (InvalidPathException $ex) {
153
-			throw new InvalidPath($ex->getMessage());
154
-		} catch (ForbiddenException $ex) {
155
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
156
-		} catch (LockedException $e) {
157
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
158
-		}
159
-	}
160
-
161
-	/**
162
-	 * Creates a new subdirectory
163
-	 *
164
-	 * @param string $name
165
-	 * @throws FileLocked
166
-	 * @throws InvalidPath
167
-	 * @throws \Sabre\DAV\Exception\Forbidden
168
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
169
-	 */
170
-	public function createDirectory($name) {
171
-		try {
172
-			if (!$this->info->isCreatable()) {
173
-				throw new \Sabre\DAV\Exception\Forbidden();
174
-			}
175
-
176
-			$this->fileView->verifyPath($this->path, $name);
177
-			$newPath = $this->path . '/' . $name;
178
-			if (!$this->fileView->mkdir($newPath)) {
179
-				throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
180
-			}
181
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
182
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
183
-		} catch (InvalidPathException $ex) {
184
-			throw new InvalidPath($ex->getMessage());
185
-		} catch (ForbiddenException $ex) {
186
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
187
-		} catch (LockedException $e) {
188
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
189
-		}
190
-	}
191
-
192
-	/**
193
-	 * Returns a specific child node, referenced by its name
194
-	 *
195
-	 * @param string $name
196
-	 * @param \OCP\Files\FileInfo $info
197
-	 * @return \Sabre\DAV\INode
198
-	 * @throws InvalidPath
199
-	 * @throws \Sabre\DAV\Exception\NotFound
200
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
201
-	 */
202
-	public function getChild($name, $info = null) {
203
-		if (!$this->info->isReadable()) {
204
-			// avoid detecting files through this way
205
-			throw new NotFound();
206
-		}
207
-
208
-		$path = $this->path . '/' . $name;
209
-		if (is_null($info)) {
210
-			try {
211
-				$this->fileView->verifyPath($this->path, $name);
212
-				$info = $this->fileView->getFileInfo($path);
213
-			} catch (\OCP\Files\StorageNotAvailableException $e) {
214
-				throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
215
-			} catch (InvalidPathException $ex) {
216
-				throw new InvalidPath($ex->getMessage());
217
-			} catch (ForbiddenException $e) {
218
-				throw new \Sabre\DAV\Exception\Forbidden();
219
-			}
220
-		}
221
-
222
-		if (!$info) {
223
-			throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
224
-		}
225
-
226
-		if ($info['mimetype'] == 'httpd/unix-directory') {
227
-			$node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager);
228
-		} else {
229
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager);
230
-		}
231
-		if ($this->tree) {
232
-			$this->tree->cacheNode($node);
233
-		}
234
-		return $node;
235
-	}
236
-
237
-	/**
238
-	 * Returns an array with all the child nodes
239
-	 *
240
-	 * @return \Sabre\DAV\INode[]
241
-	 * @throws \Sabre\DAV\Exception\Locked
242
-	 * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden
243
-	 */
244
-	public function getChildren() {
245
-		if (!is_null($this->dirContent)) {
246
-			return $this->dirContent;
247
-		}
248
-		try {
249
-			if (!$this->info->isReadable()) {
250
-				// return 403 instead of 404 because a 404 would make
251
-				// the caller believe that the collection itself does not exist
252
-				throw new Forbidden('No read permissions');
253
-			}
254
-			$folderContent = $this->fileView->getDirectoryContent($this->path);
255
-		} catch (LockedException $e) {
256
-			throw new Locked();
257
-		}
258
-
259
-		$nodes = array();
260
-		foreach ($folderContent as $info) {
261
-			$node = $this->getChild($info->getName(), $info);
262
-			$nodes[] = $node;
263
-		}
264
-		$this->dirContent = $nodes;
265
-		return $this->dirContent;
266
-	}
267
-
268
-	/**
269
-	 * Checks if a child exists.
270
-	 *
271
-	 * @param string $name
272
-	 * @return bool
273
-	 */
274
-	public function childExists($name) {
275
-		// note: here we do NOT resolve the chunk file name to the real file name
276
-		// to make sure we return false when checking for file existence with a chunk
277
-		// file name.
278
-		// This is to make sure that "createFile" is still triggered
279
-		// (required old code) instead of "updateFile".
280
-		//
281
-		// TODO: resolve chunk file name here and implement "updateFile"
282
-		$path = $this->path . '/' . $name;
283
-		return $this->fileView->file_exists($path);
284
-
285
-	}
286
-
287
-	/**
288
-	 * Deletes all files in this directory, and then itself
289
-	 *
290
-	 * @return void
291
-	 * @throws FileLocked
292
-	 * @throws \Sabre\DAV\Exception\Forbidden
293
-	 */
294
-	public function delete() {
295
-
296
-		if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
297
-			throw new \Sabre\DAV\Exception\Forbidden();
298
-		}
299
-
300
-		try {
301
-			if (!$this->fileView->rmdir($this->path)) {
302
-				// assume it wasn't possible to remove due to permission issue
303
-				throw new \Sabre\DAV\Exception\Forbidden();
304
-			}
305
-		} catch (ForbiddenException $ex) {
306
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
307
-		} catch (LockedException $e) {
308
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
309
-		}
310
-	}
311
-
312
-	/**
313
-	 * Returns available diskspace information
314
-	 *
315
-	 * @return array
316
-	 */
317
-	public function getQuotaInfo() {
318
-		if ($this->quotaInfo) {
319
-			return $this->quotaInfo;
320
-		}
321
-		try {
322
-			$storageInfo = \OC_Helper::getStorageInfo($this->info->getPath(), $this->info);
323
-			if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
324
-				$free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
325
-			} else {
326
-				$free = $storageInfo['free'];
327
-			}
328
-			$this->quotaInfo = array(
329
-				$storageInfo['used'],
330
-				$free
331
-			);
332
-			return $this->quotaInfo;
333
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
334
-			return array(0, 0);
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * Moves a node into this collection.
340
-	 *
341
-	 * It is up to the implementors to:
342
-	 *   1. Create the new resource.
343
-	 *   2. Remove the old resource.
344
-	 *   3. Transfer any properties or other data.
345
-	 *
346
-	 * Generally you should make very sure that your collection can easily move
347
-	 * the move.
348
-	 *
349
-	 * If you don't, just return false, which will trigger sabre/dav to handle
350
-	 * the move itself. If you return true from this function, the assumption
351
-	 * is that the move was successful.
352
-	 *
353
-	 * @param string $targetName New local file/collection name.
354
-	 * @param string $fullSourcePath Full path to source node
355
-	 * @param INode $sourceNode Source node itself
356
-	 * @return bool
357
-	 * @throws BadRequest
358
-	 * @throws ServiceUnavailable
359
-	 * @throws Forbidden
360
-	 * @throws FileLocked
361
-	 * @throws \Sabre\DAV\Exception\Forbidden
362
-	 */
363
-	public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
364
-		if (!$sourceNode instanceof Node) {
365
-			// it's a file of another kind, like FutureFile
366
-			if ($sourceNode instanceof IFile) {
367
-				// fallback to default copy+delete handling
368
-				return false;
369
-			}
370
-			throw new BadRequest('Incompatible node types');
371
-		}
372
-
373
-		if (!$this->fileView) {
374
-			throw new ServiceUnavailable('filesystem not setup');
375
-		}
376
-
377
-		$destinationPath = $this->getPath() . '/' . $targetName;
378
-
379
-
380
-		$targetNodeExists = $this->childExists($targetName);
381
-
382
-		// at getNodeForPath we also check the path for isForbiddenFileOrDir
383
-		// with that we have covered both source and destination
384
-		if ($sourceNode instanceof Directory && $targetNodeExists) {
385
-			throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
386
-		}
387
-
388
-		list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($sourceNode->getPath());
389
-		$destinationDir = $this->getPath();
390
-
391
-		$sourcePath = $sourceNode->getPath();
392
-
393
-		$isMovableMount = false;
394
-		$sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
395
-		$internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
396
-		if ($sourceMount instanceof MoveableMount && $internalPath === '') {
397
-			$isMovableMount = true;
398
-		}
399
-
400
-		try {
401
-			$sameFolder = ($sourceDir === $destinationDir);
402
-			// if we're overwriting or same folder
403
-			if ($targetNodeExists || $sameFolder) {
404
-				// note that renaming a share mount point is always allowed
405
-				if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
406
-					throw new \Sabre\DAV\Exception\Forbidden();
407
-				}
408
-			} else {
409
-				if (!$this->fileView->isCreatable($destinationDir)) {
410
-					throw new \Sabre\DAV\Exception\Forbidden();
411
-				}
412
-			}
413
-
414
-			if (!$sameFolder) {
415
-				// moving to a different folder, source will be gone, like a deletion
416
-				// note that moving a share mount point is always allowed
417
-				if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
418
-					throw new \Sabre\DAV\Exception\Forbidden();
419
-				}
420
-			}
421
-
422
-			$fileName = basename($destinationPath);
423
-			try {
424
-				$this->fileView->verifyPath($destinationDir, $fileName);
425
-			} catch (InvalidPathException $ex) {
426
-				throw new InvalidPath($ex->getMessage());
427
-			}
428
-
429
-			$renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
430
-			if (!$renameOkay) {
431
-				throw new \Sabre\DAV\Exception\Forbidden('');
432
-			}
433
-		} catch (StorageNotAvailableException $e) {
434
-			throw new ServiceUnavailable($e->getMessage());
435
-		} catch (ForbiddenException $ex) {
436
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
437
-		} catch (LockedException $e) {
438
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
439
-		}
440
-
441
-		return true;
442
-	}
50
+    implements \Sabre\DAV\ICollection, \Sabre\DAV\IQuota, \Sabre\DAV\IMoveTarget {
51
+
52
+    /**
53
+     * Cached directory content
54
+     *
55
+     * @var \OCP\Files\FileInfo[]
56
+     */
57
+    private $dirContent;
58
+
59
+    /**
60
+     * Cached quota info
61
+     *
62
+     * @var array
63
+     */
64
+    private $quotaInfo;
65
+
66
+    /**
67
+     * @var ObjectTree|null
68
+     */
69
+    private $tree;
70
+
71
+    /**
72
+     * Sets up the node, expects a full path name
73
+     *
74
+     * @param \OC\Files\View $view
75
+     * @param \OCP\Files\FileInfo $info
76
+     * @param ObjectTree|null $tree
77
+     * @param \OCP\Share\IManager $shareManager
78
+     */
79
+    public function __construct($view, $info, $tree = null, $shareManager = null) {
80
+        parent::__construct($view, $info, $shareManager);
81
+        $this->tree = $tree;
82
+    }
83
+
84
+    /**
85
+     * Creates a new file in the directory
86
+     *
87
+     * Data will either be supplied as a stream resource, or in certain cases
88
+     * as a string. Keep in mind that you may have to support either.
89
+     *
90
+     * After successful creation of the file, you may choose to return the ETag
91
+     * of the new file here.
92
+     *
93
+     * The returned ETag must be surrounded by double-quotes (The quotes should
94
+     * be part of the actual string).
95
+     *
96
+     * If you cannot accurately determine the ETag, you should not return it.
97
+     * If you don't store the file exactly as-is (you're transforming it
98
+     * somehow) you should also not return an ETag.
99
+     *
100
+     * This means that if a subsequent GET to this new file does not exactly
101
+     * return the same contents of what was submitted here, you are strongly
102
+     * recommended to omit the ETag.
103
+     *
104
+     * @param string $name Name of the file
105
+     * @param resource|string $data Initial payload
106
+     * @return null|string
107
+     * @throws Exception\EntityTooLarge
108
+     * @throws Exception\UnsupportedMediaType
109
+     * @throws FileLocked
110
+     * @throws InvalidPath
111
+     * @throws \Sabre\DAV\Exception
112
+     * @throws \Sabre\DAV\Exception\BadRequest
113
+     * @throws \Sabre\DAV\Exception\Forbidden
114
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
115
+     */
116
+    public function createFile($name, $data = null) {
117
+
118
+        try {
119
+            // for chunked upload also updating a existing file is a "createFile"
120
+            // because we create all the chunks before re-assemble them to the existing file.
121
+            if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
122
+
123
+                // exit if we can't create a new file and we don't updatable existing file
124
+                $chunkInfo = \OC_FileChunking::decodeName($name);
125
+                if (!$this->fileView->isCreatable($this->path) &&
126
+                    !$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
127
+                ) {
128
+                    throw new \Sabre\DAV\Exception\Forbidden();
129
+                }
130
+
131
+            } else {
132
+                // For non-chunked upload it is enough to check if we can create a new file
133
+                if (!$this->fileView->isCreatable($this->path)) {
134
+                    throw new \Sabre\DAV\Exception\Forbidden();
135
+                }
136
+            }
137
+
138
+            $this->fileView->verifyPath($this->path, $name);
139
+
140
+            $path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
141
+            // in case the file already exists/overwriting
142
+            $info = $this->fileView->getFileInfo($this->path . '/' . $name);
143
+            if (!$info) {
144
+                // use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
145
+                $info = new \OC\Files\FileInfo($path, null, null, [], null);
146
+            }
147
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
148
+            $node->acquireLock(ILockingProvider::LOCK_SHARED);
149
+            return $node->put($data);
150
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
151
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
152
+        } catch (InvalidPathException $ex) {
153
+            throw new InvalidPath($ex->getMessage());
154
+        } catch (ForbiddenException $ex) {
155
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
156
+        } catch (LockedException $e) {
157
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
158
+        }
159
+    }
160
+
161
+    /**
162
+     * Creates a new subdirectory
163
+     *
164
+     * @param string $name
165
+     * @throws FileLocked
166
+     * @throws InvalidPath
167
+     * @throws \Sabre\DAV\Exception\Forbidden
168
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
169
+     */
170
+    public function createDirectory($name) {
171
+        try {
172
+            if (!$this->info->isCreatable()) {
173
+                throw new \Sabre\DAV\Exception\Forbidden();
174
+            }
175
+
176
+            $this->fileView->verifyPath($this->path, $name);
177
+            $newPath = $this->path . '/' . $name;
178
+            if (!$this->fileView->mkdir($newPath)) {
179
+                throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
180
+            }
181
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
182
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
183
+        } catch (InvalidPathException $ex) {
184
+            throw new InvalidPath($ex->getMessage());
185
+        } catch (ForbiddenException $ex) {
186
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
187
+        } catch (LockedException $e) {
188
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
189
+        }
190
+    }
191
+
192
+    /**
193
+     * Returns a specific child node, referenced by its name
194
+     *
195
+     * @param string $name
196
+     * @param \OCP\Files\FileInfo $info
197
+     * @return \Sabre\DAV\INode
198
+     * @throws InvalidPath
199
+     * @throws \Sabre\DAV\Exception\NotFound
200
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
201
+     */
202
+    public function getChild($name, $info = null) {
203
+        if (!$this->info->isReadable()) {
204
+            // avoid detecting files through this way
205
+            throw new NotFound();
206
+        }
207
+
208
+        $path = $this->path . '/' . $name;
209
+        if (is_null($info)) {
210
+            try {
211
+                $this->fileView->verifyPath($this->path, $name);
212
+                $info = $this->fileView->getFileInfo($path);
213
+            } catch (\OCP\Files\StorageNotAvailableException $e) {
214
+                throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
215
+            } catch (InvalidPathException $ex) {
216
+                throw new InvalidPath($ex->getMessage());
217
+            } catch (ForbiddenException $e) {
218
+                throw new \Sabre\DAV\Exception\Forbidden();
219
+            }
220
+        }
221
+
222
+        if (!$info) {
223
+            throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
224
+        }
225
+
226
+        if ($info['mimetype'] == 'httpd/unix-directory') {
227
+            $node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager);
228
+        } else {
229
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager);
230
+        }
231
+        if ($this->tree) {
232
+            $this->tree->cacheNode($node);
233
+        }
234
+        return $node;
235
+    }
236
+
237
+    /**
238
+     * Returns an array with all the child nodes
239
+     *
240
+     * @return \Sabre\DAV\INode[]
241
+     * @throws \Sabre\DAV\Exception\Locked
242
+     * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden
243
+     */
244
+    public function getChildren() {
245
+        if (!is_null($this->dirContent)) {
246
+            return $this->dirContent;
247
+        }
248
+        try {
249
+            if (!$this->info->isReadable()) {
250
+                // return 403 instead of 404 because a 404 would make
251
+                // the caller believe that the collection itself does not exist
252
+                throw new Forbidden('No read permissions');
253
+            }
254
+            $folderContent = $this->fileView->getDirectoryContent($this->path);
255
+        } catch (LockedException $e) {
256
+            throw new Locked();
257
+        }
258
+
259
+        $nodes = array();
260
+        foreach ($folderContent as $info) {
261
+            $node = $this->getChild($info->getName(), $info);
262
+            $nodes[] = $node;
263
+        }
264
+        $this->dirContent = $nodes;
265
+        return $this->dirContent;
266
+    }
267
+
268
+    /**
269
+     * Checks if a child exists.
270
+     *
271
+     * @param string $name
272
+     * @return bool
273
+     */
274
+    public function childExists($name) {
275
+        // note: here we do NOT resolve the chunk file name to the real file name
276
+        // to make sure we return false when checking for file existence with a chunk
277
+        // file name.
278
+        // This is to make sure that "createFile" is still triggered
279
+        // (required old code) instead of "updateFile".
280
+        //
281
+        // TODO: resolve chunk file name here and implement "updateFile"
282
+        $path = $this->path . '/' . $name;
283
+        return $this->fileView->file_exists($path);
284
+
285
+    }
286
+
287
+    /**
288
+     * Deletes all files in this directory, and then itself
289
+     *
290
+     * @return void
291
+     * @throws FileLocked
292
+     * @throws \Sabre\DAV\Exception\Forbidden
293
+     */
294
+    public function delete() {
295
+
296
+        if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
297
+            throw new \Sabre\DAV\Exception\Forbidden();
298
+        }
299
+
300
+        try {
301
+            if (!$this->fileView->rmdir($this->path)) {
302
+                // assume it wasn't possible to remove due to permission issue
303
+                throw new \Sabre\DAV\Exception\Forbidden();
304
+            }
305
+        } catch (ForbiddenException $ex) {
306
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
307
+        } catch (LockedException $e) {
308
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
309
+        }
310
+    }
311
+
312
+    /**
313
+     * Returns available diskspace information
314
+     *
315
+     * @return array
316
+     */
317
+    public function getQuotaInfo() {
318
+        if ($this->quotaInfo) {
319
+            return $this->quotaInfo;
320
+        }
321
+        try {
322
+            $storageInfo = \OC_Helper::getStorageInfo($this->info->getPath(), $this->info);
323
+            if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
324
+                $free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
325
+            } else {
326
+                $free = $storageInfo['free'];
327
+            }
328
+            $this->quotaInfo = array(
329
+                $storageInfo['used'],
330
+                $free
331
+            );
332
+            return $this->quotaInfo;
333
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
334
+            return array(0, 0);
335
+        }
336
+    }
337
+
338
+    /**
339
+     * Moves a node into this collection.
340
+     *
341
+     * It is up to the implementors to:
342
+     *   1. Create the new resource.
343
+     *   2. Remove the old resource.
344
+     *   3. Transfer any properties or other data.
345
+     *
346
+     * Generally you should make very sure that your collection can easily move
347
+     * the move.
348
+     *
349
+     * If you don't, just return false, which will trigger sabre/dav to handle
350
+     * the move itself. If you return true from this function, the assumption
351
+     * is that the move was successful.
352
+     *
353
+     * @param string $targetName New local file/collection name.
354
+     * @param string $fullSourcePath Full path to source node
355
+     * @param INode $sourceNode Source node itself
356
+     * @return bool
357
+     * @throws BadRequest
358
+     * @throws ServiceUnavailable
359
+     * @throws Forbidden
360
+     * @throws FileLocked
361
+     * @throws \Sabre\DAV\Exception\Forbidden
362
+     */
363
+    public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
364
+        if (!$sourceNode instanceof Node) {
365
+            // it's a file of another kind, like FutureFile
366
+            if ($sourceNode instanceof IFile) {
367
+                // fallback to default copy+delete handling
368
+                return false;
369
+            }
370
+            throw new BadRequest('Incompatible node types');
371
+        }
372
+
373
+        if (!$this->fileView) {
374
+            throw new ServiceUnavailable('filesystem not setup');
375
+        }
376
+
377
+        $destinationPath = $this->getPath() . '/' . $targetName;
378
+
379
+
380
+        $targetNodeExists = $this->childExists($targetName);
381
+
382
+        // at getNodeForPath we also check the path for isForbiddenFileOrDir
383
+        // with that we have covered both source and destination
384
+        if ($sourceNode instanceof Directory && $targetNodeExists) {
385
+            throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
386
+        }
387
+
388
+        list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($sourceNode->getPath());
389
+        $destinationDir = $this->getPath();
390
+
391
+        $sourcePath = $sourceNode->getPath();
392
+
393
+        $isMovableMount = false;
394
+        $sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
395
+        $internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
396
+        if ($sourceMount instanceof MoveableMount && $internalPath === '') {
397
+            $isMovableMount = true;
398
+        }
399
+
400
+        try {
401
+            $sameFolder = ($sourceDir === $destinationDir);
402
+            // if we're overwriting or same folder
403
+            if ($targetNodeExists || $sameFolder) {
404
+                // note that renaming a share mount point is always allowed
405
+                if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
406
+                    throw new \Sabre\DAV\Exception\Forbidden();
407
+                }
408
+            } else {
409
+                if (!$this->fileView->isCreatable($destinationDir)) {
410
+                    throw new \Sabre\DAV\Exception\Forbidden();
411
+                }
412
+            }
413
+
414
+            if (!$sameFolder) {
415
+                // moving to a different folder, source will be gone, like a deletion
416
+                // note that moving a share mount point is always allowed
417
+                if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
418
+                    throw new \Sabre\DAV\Exception\Forbidden();
419
+                }
420
+            }
421
+
422
+            $fileName = basename($destinationPath);
423
+            try {
424
+                $this->fileView->verifyPath($destinationDir, $fileName);
425
+            } catch (InvalidPathException $ex) {
426
+                throw new InvalidPath($ex->getMessage());
427
+            }
428
+
429
+            $renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
430
+            if (!$renameOkay) {
431
+                throw new \Sabre\DAV\Exception\Forbidden('');
432
+            }
433
+        } catch (StorageNotAvailableException $e) {
434
+            throw new ServiceUnavailable($e->getMessage());
435
+        } catch (ForbiddenException $ex) {
436
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
437
+        } catch (LockedException $e) {
438
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
439
+        }
440
+
441
+        return true;
442
+    }
443 443
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 				// exit if we can't create a new file and we don't updatable existing file
124 124
 				$chunkInfo = \OC_FileChunking::decodeName($name);
125 125
 				if (!$this->fileView->isCreatable($this->path) &&
126
-					!$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
126
+					!$this->fileView->isUpdatable($this->path.'/'.$chunkInfo['name'])
127 127
 				) {
128 128
 					throw new \Sabre\DAV\Exception\Forbidden();
129 129
 				}
@@ -137,9 +137,9 @@  discard block
 block discarded – undo
137 137
 
138 138
 			$this->fileView->verifyPath($this->path, $name);
139 139
 
140
-			$path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
140
+			$path = $this->fileView->getAbsolutePath($this->path).'/'.$name;
141 141
 			// in case the file already exists/overwriting
142
-			$info = $this->fileView->getFileInfo($this->path . '/' . $name);
142
+			$info = $this->fileView->getFileInfo($this->path.'/'.$name);
143 143
 			if (!$info) {
144 144
 				// use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
145 145
 				$info = new \OC\Files\FileInfo($path, null, null, [], null);
@@ -174,9 +174,9 @@  discard block
 block discarded – undo
174 174
 			}
175 175
 
176 176
 			$this->fileView->verifyPath($this->path, $name);
177
-			$newPath = $this->path . '/' . $name;
177
+			$newPath = $this->path.'/'.$name;
178 178
 			if (!$this->fileView->mkdir($newPath)) {
179
-				throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
179
+				throw new \Sabre\DAV\Exception\Forbidden('Could not create directory '.$newPath);
180 180
 			}
181 181
 		} catch (\OCP\Files\StorageNotAvailableException $e) {
182 182
 			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 			throw new NotFound();
206 206
 		}
207 207
 
208
-		$path = $this->path . '/' . $name;
208
+		$path = $this->path.'/'.$name;
209 209
 		if (is_null($info)) {
210 210
 			try {
211 211
 				$this->fileView->verifyPath($this->path, $name);
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 		}
221 221
 
222 222
 		if (!$info) {
223
-			throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
223
+			throw new \Sabre\DAV\Exception\NotFound('File with name '.$path.' could not be located');
224 224
 		}
225 225
 
226 226
 		if ($info['mimetype'] == 'httpd/unix-directory') {
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 		// (required old code) instead of "updateFile".
280 280
 		//
281 281
 		// TODO: resolve chunk file name here and implement "updateFile"
282
-		$path = $this->path . '/' . $name;
282
+		$path = $this->path.'/'.$name;
283 283
 		return $this->fileView->file_exists($path);
284 284
 
285 285
 	}
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 			throw new ServiceUnavailable('filesystem not setup');
375 375
 		}
376 376
 
377
-		$destinationPath = $this->getPath() . '/' . $targetName;
377
+		$destinationPath = $this->getPath().'/'.$targetName;
378 378
 
379 379
 
380 380
 		$targetNodeExists = $this->childExists($targetName);
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
 		// at getNodeForPath we also check the path for isForbiddenFileOrDir
383 383
 		// with that we have covered both source and destination
384 384
 		if ($sourceNode instanceof Directory && $targetNodeExists) {
385
-			throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
385
+			throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory '.$sourceNode->getName().', target exists');
386 386
 		}
387 387
 
388 388
 		list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($sourceNode->getPath());
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/File.php 1 patch
Indentation   +517 added lines, -517 removed lines patch added patch discarded remove patch
@@ -58,522 +58,522 @@
 block discarded – undo
58 58
 
59 59
 class File extends Node implements IFile {
60 60
 
61
-	/**
62
-	 * Updates the data
63
-	 *
64
-	 * The data argument is a readable stream resource.
65
-	 *
66
-	 * After a successful put operation, you may choose to return an ETag. The
67
-	 * etag must always be surrounded by double-quotes. These quotes must
68
-	 * appear in the actual string you're returning.
69
-	 *
70
-	 * Clients may use the ETag from a PUT request to later on make sure that
71
-	 * when they update the file, the contents haven't changed in the mean
72
-	 * time.
73
-	 *
74
-	 * If you don't plan to store the file byte-by-byte, and you return a
75
-	 * different object on a subsequent GET you are strongly recommended to not
76
-	 * return an ETag, and just return null.
77
-	 *
78
-	 * @param resource $data
79
-	 *
80
-	 * @throws Forbidden
81
-	 * @throws UnsupportedMediaType
82
-	 * @throws BadRequest
83
-	 * @throws Exception
84
-	 * @throws EntityTooLarge
85
-	 * @throws ServiceUnavailable
86
-	 * @throws FileLocked
87
-	 * @return string|null
88
-	 */
89
-	public function put($data) {
90
-		try {
91
-			$exists = $this->fileView->file_exists($this->path);
92
-			if ($this->info && $exists && !$this->info->isUpdateable()) {
93
-				throw new Forbidden();
94
-			}
95
-		} catch (StorageNotAvailableException $e) {
96
-			throw new ServiceUnavailable("File is not updatable: " . $e->getMessage());
97
-		}
98
-
99
-		// verify path of the target
100
-		$this->verifyPath();
101
-
102
-		// chunked handling
103
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
104
-			try {
105
-				return $this->createFileChunked($data);
106
-			} catch (\Exception $e) {
107
-				$this->convertToSabreException($e);
108
-			}
109
-		}
110
-
111
-		list($partStorage) = $this->fileView->resolvePath($this->path);
112
-		$needsPartFile = $this->needsPartFile($partStorage) && (strlen($this->path) > 1);
113
-
114
-		if ($needsPartFile) {
115
-			// mark file as partial while uploading (ignored by the scanner)
116
-			$partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part';
117
-		} else {
118
-			// upload file directly as the final path
119
-			$partFilePath = $this->path;
120
-		}
121
-
122
-		// the part file and target file might be on a different storage in case of a single file storage (e.g. single file share)
123
-		/** @var \OC\Files\Storage\Storage $partStorage */
124
-		list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath);
125
-		/** @var \OC\Files\Storage\Storage $storage */
126
-		list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
127
-		try {
128
-			$target = $partStorage->fopen($internalPartPath, 'wb');
129
-			if ($target === false) {
130
-				\OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::fopen() failed', \OCP\Util::ERROR);
131
-				// because we have no clue about the cause we can only throw back a 500/Internal Server Error
132
-				throw new Exception('Could not write file contents');
133
-			}
134
-			list($count, $result) = \OC_Helper::streamCopy($data, $target);
135
-			fclose($target);
136
-
137
-			if ($result === false) {
138
-				$expected = -1;
139
-				if (isset($_SERVER['CONTENT_LENGTH'])) {
140
-					$expected = $_SERVER['CONTENT_LENGTH'];
141
-				}
142
-				throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: ' . $expected . ' )');
143
-			}
144
-
145
-			// if content length is sent by client:
146
-			// double check if the file was fully received
147
-			// compare expected and actual size
148
-			if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
149
-				$expected = $_SERVER['CONTENT_LENGTH'];
150
-				if ($count != $expected) {
151
-					throw new BadRequest('expected filesize ' . $expected . ' got ' . $count);
152
-				}
153
-			}
154
-
155
-		} catch (\Exception $e) {
156
-			if ($needsPartFile) {
157
-				$partStorage->unlink($internalPartPath);
158
-			}
159
-			$this->convertToSabreException($e);
160
-		}
161
-
162
-		try {
163
-			$view = \OC\Files\Filesystem::getView();
164
-			if ($view) {
165
-				$run = $this->emitPreHooks($exists);
166
-			} else {
167
-				$run = true;
168
-			}
169
-
170
-			try {
171
-				$this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
172
-			} catch (LockedException $e) {
173
-				if ($needsPartFile) {
174
-					$partStorage->unlink($internalPartPath);
175
-				}
176
-				throw new FileLocked($e->getMessage(), $e->getCode(), $e);
177
-			}
178
-
179
-			if ($needsPartFile) {
180
-				// rename to correct path
181
-				try {
182
-					if ($run) {
183
-						$renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath);
184
-						$fileExists = $storage->file_exists($internalPath);
185
-					}
186
-					if (!$run || $renameOkay === false || $fileExists === false) {
187
-						\OCP\Util::writeLog('webdav', 'renaming part file to final file failed', \OCP\Util::ERROR);
188
-						throw new Exception('Could not rename part file to final file');
189
-					}
190
-				} catch (ForbiddenException $ex) {
191
-					throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
192
-				} catch (\Exception $e) {
193
-					$partStorage->unlink($internalPartPath);
194
-					$this->convertToSabreException($e);
195
-				}
196
-			}
197
-
198
-			// since we skipped the view we need to scan and emit the hooks ourselves
199
-			$storage->getUpdater()->update($internalPath);
200
-
201
-			try {
202
-				$this->changeLock(ILockingProvider::LOCK_SHARED);
203
-			} catch (LockedException $e) {
204
-				throw new FileLocked($e->getMessage(), $e->getCode(), $e);
205
-			}
206
-
207
-			// allow sync clients to send the mtime along in a header
208
-			$request = \OC::$server->getRequest();
209
-			if (isset($request->server['HTTP_X_OC_MTIME'])) {
210
-				$mtimeStr = $request->server['HTTP_X_OC_MTIME'];
211
-				if (!is_numeric($mtimeStr)) {
212
-					throw new \InvalidArgumentException('X-OC-Mtime header must be an integer (unix timestamp).');
213
-				}
214
-				$mtime = intval($mtimeStr);
215
-				if ($this->fileView->touch($this->path, $mtime)) {
216
-					header('X-OC-MTime: accepted');
217
-				}
218
-			}
61
+    /**
62
+     * Updates the data
63
+     *
64
+     * The data argument is a readable stream resource.
65
+     *
66
+     * After a successful put operation, you may choose to return an ETag. The
67
+     * etag must always be surrounded by double-quotes. These quotes must
68
+     * appear in the actual string you're returning.
69
+     *
70
+     * Clients may use the ETag from a PUT request to later on make sure that
71
+     * when they update the file, the contents haven't changed in the mean
72
+     * time.
73
+     *
74
+     * If you don't plan to store the file byte-by-byte, and you return a
75
+     * different object on a subsequent GET you are strongly recommended to not
76
+     * return an ETag, and just return null.
77
+     *
78
+     * @param resource $data
79
+     *
80
+     * @throws Forbidden
81
+     * @throws UnsupportedMediaType
82
+     * @throws BadRequest
83
+     * @throws Exception
84
+     * @throws EntityTooLarge
85
+     * @throws ServiceUnavailable
86
+     * @throws FileLocked
87
+     * @return string|null
88
+     */
89
+    public function put($data) {
90
+        try {
91
+            $exists = $this->fileView->file_exists($this->path);
92
+            if ($this->info && $exists && !$this->info->isUpdateable()) {
93
+                throw new Forbidden();
94
+            }
95
+        } catch (StorageNotAvailableException $e) {
96
+            throw new ServiceUnavailable("File is not updatable: " . $e->getMessage());
97
+        }
98
+
99
+        // verify path of the target
100
+        $this->verifyPath();
101
+
102
+        // chunked handling
103
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
104
+            try {
105
+                return $this->createFileChunked($data);
106
+            } catch (\Exception $e) {
107
+                $this->convertToSabreException($e);
108
+            }
109
+        }
110
+
111
+        list($partStorage) = $this->fileView->resolvePath($this->path);
112
+        $needsPartFile = $this->needsPartFile($partStorage) && (strlen($this->path) > 1);
113
+
114
+        if ($needsPartFile) {
115
+            // mark file as partial while uploading (ignored by the scanner)
116
+            $partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part';
117
+        } else {
118
+            // upload file directly as the final path
119
+            $partFilePath = $this->path;
120
+        }
121
+
122
+        // the part file and target file might be on a different storage in case of a single file storage (e.g. single file share)
123
+        /** @var \OC\Files\Storage\Storage $partStorage */
124
+        list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath);
125
+        /** @var \OC\Files\Storage\Storage $storage */
126
+        list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
127
+        try {
128
+            $target = $partStorage->fopen($internalPartPath, 'wb');
129
+            if ($target === false) {
130
+                \OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::fopen() failed', \OCP\Util::ERROR);
131
+                // because we have no clue about the cause we can only throw back a 500/Internal Server Error
132
+                throw new Exception('Could not write file contents');
133
+            }
134
+            list($count, $result) = \OC_Helper::streamCopy($data, $target);
135
+            fclose($target);
136
+
137
+            if ($result === false) {
138
+                $expected = -1;
139
+                if (isset($_SERVER['CONTENT_LENGTH'])) {
140
+                    $expected = $_SERVER['CONTENT_LENGTH'];
141
+                }
142
+                throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: ' . $expected . ' )');
143
+            }
144
+
145
+            // if content length is sent by client:
146
+            // double check if the file was fully received
147
+            // compare expected and actual size
148
+            if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
149
+                $expected = $_SERVER['CONTENT_LENGTH'];
150
+                if ($count != $expected) {
151
+                    throw new BadRequest('expected filesize ' . $expected . ' got ' . $count);
152
+                }
153
+            }
154
+
155
+        } catch (\Exception $e) {
156
+            if ($needsPartFile) {
157
+                $partStorage->unlink($internalPartPath);
158
+            }
159
+            $this->convertToSabreException($e);
160
+        }
161
+
162
+        try {
163
+            $view = \OC\Files\Filesystem::getView();
164
+            if ($view) {
165
+                $run = $this->emitPreHooks($exists);
166
+            } else {
167
+                $run = true;
168
+            }
169
+
170
+            try {
171
+                $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
172
+            } catch (LockedException $e) {
173
+                if ($needsPartFile) {
174
+                    $partStorage->unlink($internalPartPath);
175
+                }
176
+                throw new FileLocked($e->getMessage(), $e->getCode(), $e);
177
+            }
178
+
179
+            if ($needsPartFile) {
180
+                // rename to correct path
181
+                try {
182
+                    if ($run) {
183
+                        $renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath);
184
+                        $fileExists = $storage->file_exists($internalPath);
185
+                    }
186
+                    if (!$run || $renameOkay === false || $fileExists === false) {
187
+                        \OCP\Util::writeLog('webdav', 'renaming part file to final file failed', \OCP\Util::ERROR);
188
+                        throw new Exception('Could not rename part file to final file');
189
+                    }
190
+                } catch (ForbiddenException $ex) {
191
+                    throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
192
+                } catch (\Exception $e) {
193
+                    $partStorage->unlink($internalPartPath);
194
+                    $this->convertToSabreException($e);
195
+                }
196
+            }
197
+
198
+            // since we skipped the view we need to scan and emit the hooks ourselves
199
+            $storage->getUpdater()->update($internalPath);
200
+
201
+            try {
202
+                $this->changeLock(ILockingProvider::LOCK_SHARED);
203
+            } catch (LockedException $e) {
204
+                throw new FileLocked($e->getMessage(), $e->getCode(), $e);
205
+            }
206
+
207
+            // allow sync clients to send the mtime along in a header
208
+            $request = \OC::$server->getRequest();
209
+            if (isset($request->server['HTTP_X_OC_MTIME'])) {
210
+                $mtimeStr = $request->server['HTTP_X_OC_MTIME'];
211
+                if (!is_numeric($mtimeStr)) {
212
+                    throw new \InvalidArgumentException('X-OC-Mtime header must be an integer (unix timestamp).');
213
+                }
214
+                $mtime = intval($mtimeStr);
215
+                if ($this->fileView->touch($this->path, $mtime)) {
216
+                    header('X-OC-MTime: accepted');
217
+                }
218
+            }
219 219
 					
220
-			if ($view) {
221
-				$this->emitPostHooks($exists);
222
-			}
223
-
224
-			$this->refreshInfo();
225
-
226
-			if (isset($request->server['HTTP_OC_CHECKSUM'])) {
227
-				$checksum = trim($request->server['HTTP_OC_CHECKSUM']);
228
-				$this->fileView->putFileInfo($this->path, ['checksum' => $checksum]);
229
-				$this->refreshInfo();
230
-			} else if ($this->getChecksum() !== null && $this->getChecksum() !== '') {
231
-				$this->fileView->putFileInfo($this->path, ['checksum' => '']);
232
-				$this->refreshInfo();
233
-			}
234
-
235
-		} catch (StorageNotAvailableException $e) {
236
-			throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage());
237
-		}
238
-
239
-		return '"' . $this->info->getEtag() . '"';
240
-	}
241
-
242
-	private function getPartFileBasePath($path) {
243
-		$partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true);
244
-		if ($partFileInStorage) {
245
-			return $path;
246
-		} else {
247
-			return md5($path); // will place it in the root of the view with a unique name
248
-		}
249
-	}
250
-
251
-	/**
252
-	 * @param string $path
253
-	 */
254
-	private function emitPreHooks($exists, $path = null) {
255
-		if (is_null($path)) {
256
-			$path = $this->path;
257
-		}
258
-		$hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
259
-		$run = true;
260
-
261
-		if (!$exists) {
262
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(
263
-				\OC\Files\Filesystem::signal_param_path => $hookPath,
264
-				\OC\Files\Filesystem::signal_param_run => &$run,
265
-			));
266
-		} else {
267
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, array(
268
-				\OC\Files\Filesystem::signal_param_path => $hookPath,
269
-				\OC\Files\Filesystem::signal_param_run => &$run,
270
-			));
271
-		}
272
-		\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(
273
-			\OC\Files\Filesystem::signal_param_path => $hookPath,
274
-			\OC\Files\Filesystem::signal_param_run => &$run,
275
-		));
276
-		return $run;
277
-	}
278
-
279
-	/**
280
-	 * @param string $path
281
-	 */
282
-	private function emitPostHooks($exists, $path = null) {
283
-		if (is_null($path)) {
284
-			$path = $this->path;
285
-		}
286
-		$hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
287
-		if (!$exists) {
288
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(
289
-				\OC\Files\Filesystem::signal_param_path => $hookPath
290
-			));
291
-		} else {
292
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, array(
293
-				\OC\Files\Filesystem::signal_param_path => $hookPath
294
-			));
295
-		}
296
-		\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(
297
-			\OC\Files\Filesystem::signal_param_path => $hookPath
298
-		));
299
-	}
300
-
301
-	/**
302
-	 * Returns the data
303
-	 *
304
-	 * @return resource
305
-	 * @throws Forbidden
306
-	 * @throws ServiceUnavailable
307
-	 */
308
-	public function get() {
309
-		//throw exception if encryption is disabled but files are still encrypted
310
-		try {
311
-			if (!$this->info->isReadable()) {
312
-				// do a if the file did not exist
313
-				throw new NotFound();
314
-			}
315
-			$res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb');
316
-			if ($res === false) {
317
-				throw new ServiceUnavailable("Could not open file");
318
-			}
319
-			return $res;
320
-		} catch (GenericEncryptionException $e) {
321
-			// returning 503 will allow retry of the operation at a later point in time
322
-			throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage());
323
-		} catch (StorageNotAvailableException $e) {
324
-			throw new ServiceUnavailable("Failed to open file: " . $e->getMessage());
325
-		} catch (ForbiddenException $ex) {
326
-			throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
327
-		} catch (LockedException $e) {
328
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
329
-		}
330
-	}
331
-
332
-	/**
333
-	 * Delete the current file
334
-	 *
335
-	 * @throws Forbidden
336
-	 * @throws ServiceUnavailable
337
-	 */
338
-	public function delete() {
339
-		if (!$this->info->isDeletable()) {
340
-			throw new Forbidden();
341
-		}
342
-
343
-		try {
344
-			if (!$this->fileView->unlink($this->path)) {
345
-				// assume it wasn't possible to delete due to permissions
346
-				throw new Forbidden();
347
-			}
348
-		} catch (StorageNotAvailableException $e) {
349
-			throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage());
350
-		} catch (ForbiddenException $ex) {
351
-			throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
352
-		} catch (LockedException $e) {
353
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
354
-		}
355
-	}
356
-
357
-	/**
358
-	 * Returns the mime-type for a file
359
-	 *
360
-	 * If null is returned, we'll assume application/octet-stream
361
-	 *
362
-	 * @return string
363
-	 */
364
-	public function getContentType() {
365
-		$mimeType = $this->info->getMimetype();
366
-
367
-		// PROPFIND needs to return the correct mime type, for consistency with the web UI
368
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
369
-			return $mimeType;
370
-		}
371
-		return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType);
372
-	}
373
-
374
-	/**
375
-	 * @return array|false
376
-	 */
377
-	public function getDirectDownload() {
378
-		if (\OCP\App::isEnabled('encryption')) {
379
-			return [];
380
-		}
381
-		/** @var \OCP\Files\Storage $storage */
382
-		list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
383
-		if (is_null($storage)) {
384
-			return [];
385
-		}
386
-
387
-		return $storage->getDirectDownload($internalPath);
388
-	}
389
-
390
-	/**
391
-	 * @param resource $data
392
-	 * @return null|string
393
-	 * @throws Exception
394
-	 * @throws BadRequest
395
-	 * @throws NotImplemented
396
-	 * @throws ServiceUnavailable
397
-	 */
398
-	private function createFileChunked($data) {
399
-		list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($this->path);
400
-
401
-		$info = \OC_FileChunking::decodeName($name);
402
-		if (empty($info)) {
403
-			throw new NotImplemented('Invalid chunk name');
404
-		}
405
-
406
-		$chunk_handler = new \OC_FileChunking($info);
407
-		$bytesWritten = $chunk_handler->store($info['index'], $data);
408
-
409
-		//detect aborted upload
410
-		if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
411
-			if (isset($_SERVER['CONTENT_LENGTH'])) {
412
-				$expected = $_SERVER['CONTENT_LENGTH'];
413
-				if ($bytesWritten != $expected) {
414
-					$chunk_handler->remove($info['index']);
415
-					throw new BadRequest(
416
-						'expected filesize ' . $expected . ' got ' . $bytesWritten);
417
-				}
418
-			}
419
-		}
420
-
421
-		if ($chunk_handler->isComplete()) {
422
-			list($storage,) = $this->fileView->resolvePath($path);
423
-			$needsPartFile = $this->needsPartFile($storage);
424
-			$partFile = null;
425
-
426
-			$targetPath = $path . '/' . $info['name'];
427
-			/** @var \OC\Files\Storage\Storage $targetStorage */
428
-			list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
429
-
430
-			$exists = $this->fileView->file_exists($targetPath);
431
-
432
-			try {
433
-				$this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED);
434
-
435
-				$this->emitPreHooks($exists, $targetPath);
436
-				$this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
437
-				/** @var \OC\Files\Storage\Storage $targetStorage */
438
-				list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
439
-
440
-				if ($needsPartFile) {
441
-					// we first assembly the target file as a part file
442
-					$partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part';
443
-					/** @var \OC\Files\Storage\Storage $targetStorage */
444
-					list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile);
445
-
446
-
447
-					$chunk_handler->file_assemble($partStorage, $partInternalPath);
448
-
449
-					// here is the final atomic rename
450
-					$renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath);
451
-					$fileExists = $targetStorage->file_exists($targetInternalPath);
452
-					if ($renameOkay === false || $fileExists === false) {
453
-						\OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::rename() failed', \OCP\Util::ERROR);
454
-						// only delete if an error occurred and the target file was already created
455
-						if ($fileExists) {
456
-							// set to null to avoid double-deletion when handling exception
457
-							// stray part file
458
-							$partFile = null;
459
-							$targetStorage->unlink($targetInternalPath);
460
-						}
461
-						$this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
462
-						throw new Exception('Could not rename part file assembled from chunks');
463
-					}
464
-				} else {
465
-					// assemble directly into the final file
466
-					$chunk_handler->file_assemble($targetStorage, $targetInternalPath);
467
-				}
468
-
469
-				// allow sync clients to send the mtime along in a header
470
-				$request = \OC::$server->getRequest();
471
-				if (isset($request->server['HTTP_X_OC_MTIME'])) {
472
-					if ($targetStorage->touch($targetInternalPath, $request->server['HTTP_X_OC_MTIME'])) {
473
-						header('X-OC-MTime: accepted');
474
-					}
475
-				}
476
-
477
-				// since we skipped the view we need to scan and emit the hooks ourselves
478
-				$targetStorage->getUpdater()->update($targetInternalPath);
479
-
480
-				$this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
481
-
482
-				$this->emitPostHooks($exists, $targetPath);
483
-
484
-				// FIXME: should call refreshInfo but can't because $this->path is not the of the final file
485
-				$info = $this->fileView->getFileInfo($targetPath);
486
-
487
-				if (isset($request->server['HTTP_OC_CHECKSUM'])) {
488
-					$checksum = trim($request->server['HTTP_OC_CHECKSUM']);
489
-					$this->fileView->putFileInfo($targetPath, ['checksum' => $checksum]);
490
-				} else if ($info->getChecksum() !== null && $info->getChecksum() !== '') {
491
-					$this->fileView->putFileInfo($this->path, ['checksum' => '']);
492
-				}
493
-
494
-				$this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED);
495
-
496
-				return $info->getEtag();
497
-			} catch (\Exception $e) {
498
-				if ($partFile !== null) {
499
-					$targetStorage->unlink($targetInternalPath);
500
-				}
501
-				$this->convertToSabreException($e);
502
-			}
503
-		}
504
-
505
-		return null;
506
-	}
507
-
508
-	/**
509
-	 * Returns whether a part file is needed for the given storage
510
-	 * or whether the file can be assembled/uploaded directly on the
511
-	 * target storage.
512
-	 *
513
-	 * @param \OCP\Files\Storage $storage
514
-	 * @return bool true if the storage needs part file handling
515
-	 */
516
-	private function needsPartFile($storage) {
517
-		// TODO: in the future use ChunkHandler provided by storage
518
-		return !$storage->instanceOfStorage('OCA\Files_Sharing\External\Storage') &&
519
-			!$storage->instanceOfStorage('OC\Files\Storage\OwnCloud') &&
520
-			!$storage->instanceOfStorage('OC\Files\ObjectStore\ObjectStoreStorage') &&
521
-			$storage->needsPartFile();
522
-	}
523
-
524
-	/**
525
-	 * Convert the given exception to a SabreException instance
526
-	 *
527
-	 * @param \Exception $e
528
-	 *
529
-	 * @throws \Sabre\DAV\Exception
530
-	 */
531
-	private function convertToSabreException(\Exception $e) {
532
-		if ($e instanceof \Sabre\DAV\Exception) {
533
-			throw $e;
534
-		}
535
-		if ($e instanceof NotPermittedException) {
536
-			// a more general case - due to whatever reason the content could not be written
537
-			throw new Forbidden($e->getMessage(), 0, $e);
538
-		}
539
-		if ($e instanceof ForbiddenException) {
540
-			// the path for the file was forbidden
541
-			throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e);
542
-		}
543
-		if ($e instanceof EntityTooLargeException) {
544
-			// the file is too big to be stored
545
-			throw new EntityTooLarge($e->getMessage(), 0, $e);
546
-		}
547
-		if ($e instanceof InvalidContentException) {
548
-			// the file content is not permitted
549
-			throw new UnsupportedMediaType($e->getMessage(), 0, $e);
550
-		}
551
-		if ($e instanceof InvalidPathException) {
552
-			// the path for the file was not valid
553
-			// TODO: find proper http status code for this case
554
-			throw new Forbidden($e->getMessage(), 0, $e);
555
-		}
556
-		if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) {
557
-			// the file is currently being written to by another process
558
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
559
-		}
560
-		if ($e instanceof GenericEncryptionException) {
561
-			// returning 503 will allow retry of the operation at a later point in time
562
-			throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e);
563
-		}
564
-		if ($e instanceof StorageNotAvailableException) {
565
-			throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e);
566
-		}
567
-
568
-		throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e);
569
-	}
570
-
571
-	/**
572
-	 * Get the checksum for this file
573
-	 *
574
-	 * @return string
575
-	 */
576
-	public function getChecksum() {
577
-		return $this->info->getChecksum();
578
-	}
220
+            if ($view) {
221
+                $this->emitPostHooks($exists);
222
+            }
223
+
224
+            $this->refreshInfo();
225
+
226
+            if (isset($request->server['HTTP_OC_CHECKSUM'])) {
227
+                $checksum = trim($request->server['HTTP_OC_CHECKSUM']);
228
+                $this->fileView->putFileInfo($this->path, ['checksum' => $checksum]);
229
+                $this->refreshInfo();
230
+            } else if ($this->getChecksum() !== null && $this->getChecksum() !== '') {
231
+                $this->fileView->putFileInfo($this->path, ['checksum' => '']);
232
+                $this->refreshInfo();
233
+            }
234
+
235
+        } catch (StorageNotAvailableException $e) {
236
+            throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage());
237
+        }
238
+
239
+        return '"' . $this->info->getEtag() . '"';
240
+    }
241
+
242
+    private function getPartFileBasePath($path) {
243
+        $partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true);
244
+        if ($partFileInStorage) {
245
+            return $path;
246
+        } else {
247
+            return md5($path); // will place it in the root of the view with a unique name
248
+        }
249
+    }
250
+
251
+    /**
252
+     * @param string $path
253
+     */
254
+    private function emitPreHooks($exists, $path = null) {
255
+        if (is_null($path)) {
256
+            $path = $this->path;
257
+        }
258
+        $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
259
+        $run = true;
260
+
261
+        if (!$exists) {
262
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(
263
+                \OC\Files\Filesystem::signal_param_path => $hookPath,
264
+                \OC\Files\Filesystem::signal_param_run => &$run,
265
+            ));
266
+        } else {
267
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, array(
268
+                \OC\Files\Filesystem::signal_param_path => $hookPath,
269
+                \OC\Files\Filesystem::signal_param_run => &$run,
270
+            ));
271
+        }
272
+        \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(
273
+            \OC\Files\Filesystem::signal_param_path => $hookPath,
274
+            \OC\Files\Filesystem::signal_param_run => &$run,
275
+        ));
276
+        return $run;
277
+    }
278
+
279
+    /**
280
+     * @param string $path
281
+     */
282
+    private function emitPostHooks($exists, $path = null) {
283
+        if (is_null($path)) {
284
+            $path = $this->path;
285
+        }
286
+        $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
287
+        if (!$exists) {
288
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(
289
+                \OC\Files\Filesystem::signal_param_path => $hookPath
290
+            ));
291
+        } else {
292
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, array(
293
+                \OC\Files\Filesystem::signal_param_path => $hookPath
294
+            ));
295
+        }
296
+        \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(
297
+            \OC\Files\Filesystem::signal_param_path => $hookPath
298
+        ));
299
+    }
300
+
301
+    /**
302
+     * Returns the data
303
+     *
304
+     * @return resource
305
+     * @throws Forbidden
306
+     * @throws ServiceUnavailable
307
+     */
308
+    public function get() {
309
+        //throw exception if encryption is disabled but files are still encrypted
310
+        try {
311
+            if (!$this->info->isReadable()) {
312
+                // do a if the file did not exist
313
+                throw new NotFound();
314
+            }
315
+            $res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb');
316
+            if ($res === false) {
317
+                throw new ServiceUnavailable("Could not open file");
318
+            }
319
+            return $res;
320
+        } catch (GenericEncryptionException $e) {
321
+            // returning 503 will allow retry of the operation at a later point in time
322
+            throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage());
323
+        } catch (StorageNotAvailableException $e) {
324
+            throw new ServiceUnavailable("Failed to open file: " . $e->getMessage());
325
+        } catch (ForbiddenException $ex) {
326
+            throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
327
+        } catch (LockedException $e) {
328
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
329
+        }
330
+    }
331
+
332
+    /**
333
+     * Delete the current file
334
+     *
335
+     * @throws Forbidden
336
+     * @throws ServiceUnavailable
337
+     */
338
+    public function delete() {
339
+        if (!$this->info->isDeletable()) {
340
+            throw new Forbidden();
341
+        }
342
+
343
+        try {
344
+            if (!$this->fileView->unlink($this->path)) {
345
+                // assume it wasn't possible to delete due to permissions
346
+                throw new Forbidden();
347
+            }
348
+        } catch (StorageNotAvailableException $e) {
349
+            throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage());
350
+        } catch (ForbiddenException $ex) {
351
+            throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
352
+        } catch (LockedException $e) {
353
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
354
+        }
355
+    }
356
+
357
+    /**
358
+     * Returns the mime-type for a file
359
+     *
360
+     * If null is returned, we'll assume application/octet-stream
361
+     *
362
+     * @return string
363
+     */
364
+    public function getContentType() {
365
+        $mimeType = $this->info->getMimetype();
366
+
367
+        // PROPFIND needs to return the correct mime type, for consistency with the web UI
368
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
369
+            return $mimeType;
370
+        }
371
+        return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType);
372
+    }
373
+
374
+    /**
375
+     * @return array|false
376
+     */
377
+    public function getDirectDownload() {
378
+        if (\OCP\App::isEnabled('encryption')) {
379
+            return [];
380
+        }
381
+        /** @var \OCP\Files\Storage $storage */
382
+        list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
383
+        if (is_null($storage)) {
384
+            return [];
385
+        }
386
+
387
+        return $storage->getDirectDownload($internalPath);
388
+    }
389
+
390
+    /**
391
+     * @param resource $data
392
+     * @return null|string
393
+     * @throws Exception
394
+     * @throws BadRequest
395
+     * @throws NotImplemented
396
+     * @throws ServiceUnavailable
397
+     */
398
+    private function createFileChunked($data) {
399
+        list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($this->path);
400
+
401
+        $info = \OC_FileChunking::decodeName($name);
402
+        if (empty($info)) {
403
+            throw new NotImplemented('Invalid chunk name');
404
+        }
405
+
406
+        $chunk_handler = new \OC_FileChunking($info);
407
+        $bytesWritten = $chunk_handler->store($info['index'], $data);
408
+
409
+        //detect aborted upload
410
+        if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
411
+            if (isset($_SERVER['CONTENT_LENGTH'])) {
412
+                $expected = $_SERVER['CONTENT_LENGTH'];
413
+                if ($bytesWritten != $expected) {
414
+                    $chunk_handler->remove($info['index']);
415
+                    throw new BadRequest(
416
+                        'expected filesize ' . $expected . ' got ' . $bytesWritten);
417
+                }
418
+            }
419
+        }
420
+
421
+        if ($chunk_handler->isComplete()) {
422
+            list($storage,) = $this->fileView->resolvePath($path);
423
+            $needsPartFile = $this->needsPartFile($storage);
424
+            $partFile = null;
425
+
426
+            $targetPath = $path . '/' . $info['name'];
427
+            /** @var \OC\Files\Storage\Storage $targetStorage */
428
+            list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
429
+
430
+            $exists = $this->fileView->file_exists($targetPath);
431
+
432
+            try {
433
+                $this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED);
434
+
435
+                $this->emitPreHooks($exists, $targetPath);
436
+                $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
437
+                /** @var \OC\Files\Storage\Storage $targetStorage */
438
+                list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
439
+
440
+                if ($needsPartFile) {
441
+                    // we first assembly the target file as a part file
442
+                    $partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part';
443
+                    /** @var \OC\Files\Storage\Storage $targetStorage */
444
+                    list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile);
445
+
446
+
447
+                    $chunk_handler->file_assemble($partStorage, $partInternalPath);
448
+
449
+                    // here is the final atomic rename
450
+                    $renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath);
451
+                    $fileExists = $targetStorage->file_exists($targetInternalPath);
452
+                    if ($renameOkay === false || $fileExists === false) {
453
+                        \OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::rename() failed', \OCP\Util::ERROR);
454
+                        // only delete if an error occurred and the target file was already created
455
+                        if ($fileExists) {
456
+                            // set to null to avoid double-deletion when handling exception
457
+                            // stray part file
458
+                            $partFile = null;
459
+                            $targetStorage->unlink($targetInternalPath);
460
+                        }
461
+                        $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
462
+                        throw new Exception('Could not rename part file assembled from chunks');
463
+                    }
464
+                } else {
465
+                    // assemble directly into the final file
466
+                    $chunk_handler->file_assemble($targetStorage, $targetInternalPath);
467
+                }
468
+
469
+                // allow sync clients to send the mtime along in a header
470
+                $request = \OC::$server->getRequest();
471
+                if (isset($request->server['HTTP_X_OC_MTIME'])) {
472
+                    if ($targetStorage->touch($targetInternalPath, $request->server['HTTP_X_OC_MTIME'])) {
473
+                        header('X-OC-MTime: accepted');
474
+                    }
475
+                }
476
+
477
+                // since we skipped the view we need to scan and emit the hooks ourselves
478
+                $targetStorage->getUpdater()->update($targetInternalPath);
479
+
480
+                $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
481
+
482
+                $this->emitPostHooks($exists, $targetPath);
483
+
484
+                // FIXME: should call refreshInfo but can't because $this->path is not the of the final file
485
+                $info = $this->fileView->getFileInfo($targetPath);
486
+
487
+                if (isset($request->server['HTTP_OC_CHECKSUM'])) {
488
+                    $checksum = trim($request->server['HTTP_OC_CHECKSUM']);
489
+                    $this->fileView->putFileInfo($targetPath, ['checksum' => $checksum]);
490
+                } else if ($info->getChecksum() !== null && $info->getChecksum() !== '') {
491
+                    $this->fileView->putFileInfo($this->path, ['checksum' => '']);
492
+                }
493
+
494
+                $this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED);
495
+
496
+                return $info->getEtag();
497
+            } catch (\Exception $e) {
498
+                if ($partFile !== null) {
499
+                    $targetStorage->unlink($targetInternalPath);
500
+                }
501
+                $this->convertToSabreException($e);
502
+            }
503
+        }
504
+
505
+        return null;
506
+    }
507
+
508
+    /**
509
+     * Returns whether a part file is needed for the given storage
510
+     * or whether the file can be assembled/uploaded directly on the
511
+     * target storage.
512
+     *
513
+     * @param \OCP\Files\Storage $storage
514
+     * @return bool true if the storage needs part file handling
515
+     */
516
+    private function needsPartFile($storage) {
517
+        // TODO: in the future use ChunkHandler provided by storage
518
+        return !$storage->instanceOfStorage('OCA\Files_Sharing\External\Storage') &&
519
+            !$storage->instanceOfStorage('OC\Files\Storage\OwnCloud') &&
520
+            !$storage->instanceOfStorage('OC\Files\ObjectStore\ObjectStoreStorage') &&
521
+            $storage->needsPartFile();
522
+    }
523
+
524
+    /**
525
+     * Convert the given exception to a SabreException instance
526
+     *
527
+     * @param \Exception $e
528
+     *
529
+     * @throws \Sabre\DAV\Exception
530
+     */
531
+    private function convertToSabreException(\Exception $e) {
532
+        if ($e instanceof \Sabre\DAV\Exception) {
533
+            throw $e;
534
+        }
535
+        if ($e instanceof NotPermittedException) {
536
+            // a more general case - due to whatever reason the content could not be written
537
+            throw new Forbidden($e->getMessage(), 0, $e);
538
+        }
539
+        if ($e instanceof ForbiddenException) {
540
+            // the path for the file was forbidden
541
+            throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e);
542
+        }
543
+        if ($e instanceof EntityTooLargeException) {
544
+            // the file is too big to be stored
545
+            throw new EntityTooLarge($e->getMessage(), 0, $e);
546
+        }
547
+        if ($e instanceof InvalidContentException) {
548
+            // the file content is not permitted
549
+            throw new UnsupportedMediaType($e->getMessage(), 0, $e);
550
+        }
551
+        if ($e instanceof InvalidPathException) {
552
+            // the path for the file was not valid
553
+            // TODO: find proper http status code for this case
554
+            throw new Forbidden($e->getMessage(), 0, $e);
555
+        }
556
+        if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) {
557
+            // the file is currently being written to by another process
558
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
559
+        }
560
+        if ($e instanceof GenericEncryptionException) {
561
+            // returning 503 will allow retry of the operation at a later point in time
562
+            throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e);
563
+        }
564
+        if ($e instanceof StorageNotAvailableException) {
565
+            throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e);
566
+        }
567
+
568
+        throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e);
569
+    }
570
+
571
+    /**
572
+     * Get the checksum for this file
573
+     *
574
+     * @return string
575
+     */
576
+    public function getChecksum() {
577
+        return $this->info->getChecksum();
578
+    }
579 579
 }
Please login to merge, or discard this patch.