Completed
Pull Request — master (#4733)
by Robin
44:10 queued 31:15
created
apps/dav/lib/Connector/Sabre/FilesPlugin.php 2 patches
Indentation   +436 added lines, -436 removed lines patch added patch discarded remove patch
@@ -49,441 +49,441 @@
 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
-	const MOUNT_TYPE_PROPERTYNAME = '{http://nextcloud.org/ns}mount-type';
69
-
70
-	/**
71
-	 * Reference to main server object
72
-	 *
73
-	 * @var \Sabre\DAV\Server
74
-	 */
75
-	private $server;
76
-
77
-	/**
78
-	 * @var Tree
79
-	 */
80
-	private $tree;
81
-
82
-	/**
83
-	 * Whether this is public webdav.
84
-	 * If true, some returned information will be stripped off.
85
-	 *
86
-	 * @var bool
87
-	 */
88
-	private $isPublic;
89
-
90
-	/**
91
-	 * @var View
92
-	 */
93
-	private $fileView;
94
-
95
-	/**
96
-	 * @var bool
97
-	 */
98
-	private $downloadAttachment;
99
-
100
-	/**
101
-	 * @var IConfig
102
-	 */
103
-	private $config;
104
-
105
-	/**
106
-	 * @var IRequest
107
-	 */
108
-	private $request;
109
-
110
-	/**
111
-	 * @var IPreview
112
-	 */
113
-	private $previewManager;
114
-
115
-	/**
116
-	 * @param Tree $tree
117
-	 * @param IConfig $config
118
-	 * @param IRequest $request
119
-	 * @param IPreview $previewManager
120
-	 * @param bool $isPublic
121
-	 * @param bool $downloadAttachment
122
-	 */
123
-	public function __construct(Tree $tree,
124
-								IConfig $config,
125
-								IRequest $request,
126
-								IPreview $previewManager,
127
-								$isPublic = false,
128
-								$downloadAttachment = true) {
129
-		$this->tree = $tree;
130
-		$this->config = $config;
131
-		$this->request = $request;
132
-		$this->isPublic = $isPublic;
133
-		$this->downloadAttachment = $downloadAttachment;
134
-		$this->previewManager = $previewManager;
135
-	}
136
-
137
-	/**
138
-	 * This initializes the plugin.
139
-	 *
140
-	 * This function is called by \Sabre\DAV\Server, after
141
-	 * addPlugin is called.
142
-	 *
143
-	 * This method should set up the required event subscriptions.
144
-	 *
145
-	 * @param \Sabre\DAV\Server $server
146
-	 * @return void
147
-	 */
148
-	public function initialize(\Sabre\DAV\Server $server) {
149
-
150
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
151
-		$server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
152
-		$server->protectedProperties[] = self::FILEID_PROPERTYNAME;
153
-		$server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
154
-		$server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
155
-		$server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
156
-		$server->protectedProperties[] = self::SIZE_PROPERTYNAME;
157
-		$server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
158
-		$server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
159
-		$server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
160
-		$server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
161
-		$server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
162
-		$server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
163
-		$server->protectedProperties[] = self::MOUNT_TYPE_PROPERTYNAME;
164
-
165
-		// normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
166
-		$allowedProperties = ['{DAV:}getetag'];
167
-		$server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
168
-
169
-		$this->server = $server;
170
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
171
-		$this->server->on('propPatch', array($this, 'handleUpdateProperties'));
172
-		$this->server->on('afterBind', array($this, 'sendFileIdHeader'));
173
-		$this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
174
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
175
-		$this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
176
-		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
177
-			$body = $response->getBody();
178
-			if (is_resource($body)) {
179
-				fclose($body);
180
-			}
181
-		});
182
-		$this->server->on('beforeMove', [$this, 'checkMove']);
183
-		$this->server->on('beforeMove', [$this, 'beforeMoveFutureFile']);
184
-	}
185
-
186
-	/**
187
-	 * Plugin that checks if a move can actually be performed.
188
-	 *
189
-	 * @param string $source source path
190
-	 * @param string $destination destination path
191
-	 * @throws Forbidden
192
-	 * @throws NotFound
193
-	 */
194
-	function checkMove($source, $destination) {
195
-		$sourceNode = $this->tree->getNodeForPath($source);
196
-		if (!$sourceNode instanceof Node) {
197
-			return;
198
-		}
199
-		list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($source);
200
-		list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
201
-
202
-		if ($sourceDir !== $destinationDir) {
203
-			$sourceNodeFileInfo = $sourceNode->getFileInfo();
204
-			if (is_null($sourceNodeFileInfo)) {
205
-				throw new NotFound($source . ' does not exist');
206
-			}
207
-
208
-			if (!$sourceNodeFileInfo->isDeletable()) {
209
-				throw new Forbidden($source . " cannot be deleted");
210
-			}
211
-		}
212
-	}
213
-
214
-	/**
215
-	 * This sets a cookie to be able to recognize the start of the download
216
-	 * the content must not be longer than 32 characters and must only contain
217
-	 * alphanumeric characters
218
-	 *
219
-	 * @param RequestInterface $request
220
-	 * @param ResponseInterface $response
221
-	 */
222
-	function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
223
-		$queryParams = $request->getQueryParameters();
224
-
225
-		/**
226
-		 * this sets a cookie to be able to recognize the start of the download
227
-		 * the content must not be longer than 32 characters and must only contain
228
-		 * alphanumeric characters
229
-		 */
230
-		if (isset($queryParams['downloadStartSecret'])) {
231
-			$token = $queryParams['downloadStartSecret'];
232
-			if (!isset($token[32])
233
-				&& preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
234
-				// FIXME: use $response->setHeader() instead
235
-				setcookie('ocDownloadStarted', $token, time() + 20, '/');
236
-			}
237
-		}
238
-	}
239
-
240
-	/**
241
-	 * Add headers to file download
242
-	 *
243
-	 * @param RequestInterface $request
244
-	 * @param ResponseInterface $response
245
-	 */
246
-	function httpGet(RequestInterface $request, ResponseInterface $response) {
247
-		// Only handle valid files
248
-		$node = $this->tree->getNodeForPath($request->getPath());
249
-		if (!($node instanceof IFile)) return;
250
-
251
-		// adds a 'Content-Disposition: attachment' header in case no disposition
252
-		// header has been set before
253
-		if ($this->downloadAttachment &&
254
-			$response->getHeader('Content-Disposition') === null) {
255
-			$filename = $node->getName();
256
-			if ($this->request->isUserAgent(
257
-				[
258
-					\OC\AppFramework\Http\Request::USER_AGENT_IE,
259
-					\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
260
-					\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
261
-				])) {
262
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
263
-			} else {
264
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
265
-													 . '; filename="' . rawurlencode($filename) . '"');
266
-			}
267
-		}
268
-
269
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
270
-			//Add OC-Checksum header
271
-			/** @var $node File */
272
-			$checksum = $node->getChecksum();
273
-			if ($checksum !== null && $checksum !== '') {
274
-				$response->addHeader('OC-Checksum', $checksum);
275
-			}
276
-		}
277
-	}
278
-
279
-	/**
280
-	 * Adds all ownCloud-specific properties
281
-	 *
282
-	 * @param PropFind $propFind
283
-	 * @param \Sabre\DAV\INode $node
284
-	 * @return void
285
-	 */
286
-	public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
287
-
288
-		$httpRequest = $this->server->httpRequest;
289
-
290
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
291
-			if (!$node->getFileInfo()->isReadable()) {
292
-				// avoid detecting files through this means
293
-				throw new NotFound();
294
-			}
295
-
296
-			$propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
297
-				return $node->getFileId();
298
-			});
299
-
300
-			$propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
301
-				return $node->getInternalFileId();
302
-			});
303
-
304
-			$propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
305
-				$perms = $node->getDavPermissions();
306
-				if ($this->isPublic) {
307
-					// remove mount information
308
-					$perms = str_replace(['S', 'M'], '', $perms);
309
-				}
310
-				return $perms;
311
-			});
312
-
313
-			$propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
314
-				return $node->getSharePermissions(
315
-					$httpRequest->getRawServerValue('PHP_AUTH_USER')
316
-				);
317
-			});
318
-
319
-			$propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
320
-				return $node->getETag();
321
-			});
322
-
323
-			$propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
324
-				$owner = $node->getOwner();
325
-				if (!$owner) {
326
-					return null;
327
-				} else {
328
-					return $owner->getUID();
329
-				}
330
-			});
331
-			$propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
332
-				$owner = $node->getOwner();
333
-				if (!$owner) {
334
-					return null;
335
-				} else {
336
-					return $owner->getDisplayName();
337
-				}
338
-			});
339
-
340
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
341
-				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
342
-			});
343
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
344
-				return $node->getSize();
345
-			});
346
-			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
347
-				return $node->getFileInfo()->getMountPoint()->getMountType();
348
-			});
349
-		}
350
-
351
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
352
-			$propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
353
-				return $this->config->getSystemValue('data-fingerprint', '');
354
-			});
355
-		}
356
-
357
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
358
-			$propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
359
-				/** @var $node \OCA\DAV\Connector\Sabre\File */
360
-				try {
361
-					$directDownloadUrl = $node->getDirectDownload();
362
-					if (isset($directDownloadUrl['url'])) {
363
-						return $directDownloadUrl['url'];
364
-					}
365
-				} catch (StorageNotAvailableException $e) {
366
-					return false;
367
-				} catch (ForbiddenException $e) {
368
-					return false;
369
-				}
370
-				return false;
371
-			});
372
-
373
-			$propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
374
-				$checksum = $node->getChecksum();
375
-				if ($checksum === NULL || $checksum === '') {
376
-					return null;
377
-				}
378
-
379
-				return new ChecksumList($checksum);
380
-			});
381
-
382
-		}
383
-
384
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
385
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
386
-				return $node->getSize();
387
-			});
388
-		}
389
-	}
390
-
391
-	/**
392
-	 * Update ownCloud-specific properties
393
-	 *
394
-	 * @param string $path
395
-	 * @param PropPatch $propPatch
396
-	 *
397
-	 * @return void
398
-	 */
399
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
400
-		$node = $this->tree->getNodeForPath($path);
401
-		if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
402
-			return;
403
-		}
404
-
405
-		$propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($node) {
406
-			if (empty($time)) {
407
-				return false;
408
-			}
409
-			$node->touch($time);
410
-			return true;
411
-		});
412
-		$propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($node) {
413
-			if (empty($etag)) {
414
-				return false;
415
-			}
416
-			if ($node->setEtag($etag) !== -1) {
417
-				return true;
418
-			}
419
-			return false;
420
-		});
421
-	}
422
-
423
-	/**
424
-	 * @param string $filePath
425
-	 * @param \Sabre\DAV\INode $node
426
-	 * @throws \Sabre\DAV\Exception\BadRequest
427
-	 */
428
-	public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
429
-		// chunked upload handling
430
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
431
-			list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
432
-			$info = \OC_FileChunking::decodeName($name);
433
-			if (!empty($info)) {
434
-				$filePath = $path . '/' . $info['name'];
435
-			}
436
-		}
437
-
438
-		// we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
439
-		if (!$this->server->tree->nodeExists($filePath)) {
440
-			return;
441
-		}
442
-		$node = $this->server->tree->getNodeForPath($filePath);
443
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
444
-			$fileId = $node->getFileId();
445
-			if (!is_null($fileId)) {
446
-				$this->server->httpResponse->setHeader('OC-FileId', $fileId);
447
-			}
448
-		}
449
-	}
450
-
451
-	/**
452
-	 * Move handler for future file.
453
-	 *
454
-	 * This overrides the default move behavior to prevent Sabre
455
-	 * to delete the target file before moving. Because deleting would
456
-	 * lose the file id and metadata.
457
-	 *
458
-	 * @param string $path source path
459
-	 * @param string $destination destination path
460
-	 * @return bool|void false to stop handling, void to skip this handler
461
-	 */
462
-	public function beforeMoveFutureFile($path, $destination) {
463
-		$sourceNode = $this->tree->getNodeForPath($path);
464
-		if (!$sourceNode instanceof FutureFile) {
465
-			// skip handling as the source is not a chunked FutureFile
466
-			return;
467
-		}
468
-
469
-		if (!$this->tree->nodeExists($destination)) {
470
-			// skip and let the default handler do its work
471
-			return;
472
-		}
473
-
474
-		// do a move manually, skipping Sabre's default "delete" for existing nodes
475
-		$this->tree->move($path, $destination);
476
-
477
-		// trigger all default events (copied from CorePlugin::move)
478
-		$this->server->emit('afterMove', [$path, $destination]);
479
-		$this->server->emit('afterUnbind', [$path]);
480
-		$this->server->emit('afterBind', [$destination]);
481
-
482
-		$response = $this->server->httpResponse;
483
-		$response->setHeader('Content-Length', '0');
484
-		$response->setStatus(204);
485
-
486
-		return false;
487
-	}
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
+    const MOUNT_TYPE_PROPERTYNAME = '{http://nextcloud.org/ns}mount-type';
69
+
70
+    /**
71
+     * Reference to main server object
72
+     *
73
+     * @var \Sabre\DAV\Server
74
+     */
75
+    private $server;
76
+
77
+    /**
78
+     * @var Tree
79
+     */
80
+    private $tree;
81
+
82
+    /**
83
+     * Whether this is public webdav.
84
+     * If true, some returned information will be stripped off.
85
+     *
86
+     * @var bool
87
+     */
88
+    private $isPublic;
89
+
90
+    /**
91
+     * @var View
92
+     */
93
+    private $fileView;
94
+
95
+    /**
96
+     * @var bool
97
+     */
98
+    private $downloadAttachment;
99
+
100
+    /**
101
+     * @var IConfig
102
+     */
103
+    private $config;
104
+
105
+    /**
106
+     * @var IRequest
107
+     */
108
+    private $request;
109
+
110
+    /**
111
+     * @var IPreview
112
+     */
113
+    private $previewManager;
114
+
115
+    /**
116
+     * @param Tree $tree
117
+     * @param IConfig $config
118
+     * @param IRequest $request
119
+     * @param IPreview $previewManager
120
+     * @param bool $isPublic
121
+     * @param bool $downloadAttachment
122
+     */
123
+    public function __construct(Tree $tree,
124
+                                IConfig $config,
125
+                                IRequest $request,
126
+                                IPreview $previewManager,
127
+                                $isPublic = false,
128
+                                $downloadAttachment = true) {
129
+        $this->tree = $tree;
130
+        $this->config = $config;
131
+        $this->request = $request;
132
+        $this->isPublic = $isPublic;
133
+        $this->downloadAttachment = $downloadAttachment;
134
+        $this->previewManager = $previewManager;
135
+    }
136
+
137
+    /**
138
+     * This initializes the plugin.
139
+     *
140
+     * This function is called by \Sabre\DAV\Server, after
141
+     * addPlugin is called.
142
+     *
143
+     * This method should set up the required event subscriptions.
144
+     *
145
+     * @param \Sabre\DAV\Server $server
146
+     * @return void
147
+     */
148
+    public function initialize(\Sabre\DAV\Server $server) {
149
+
150
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
151
+        $server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
152
+        $server->protectedProperties[] = self::FILEID_PROPERTYNAME;
153
+        $server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
154
+        $server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
155
+        $server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
156
+        $server->protectedProperties[] = self::SIZE_PROPERTYNAME;
157
+        $server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
158
+        $server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
159
+        $server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
160
+        $server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
161
+        $server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
162
+        $server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
163
+        $server->protectedProperties[] = self::MOUNT_TYPE_PROPERTYNAME;
164
+
165
+        // normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
166
+        $allowedProperties = ['{DAV:}getetag'];
167
+        $server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
168
+
169
+        $this->server = $server;
170
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
171
+        $this->server->on('propPatch', array($this, 'handleUpdateProperties'));
172
+        $this->server->on('afterBind', array($this, 'sendFileIdHeader'));
173
+        $this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
174
+        $this->server->on('afterMethod:GET', [$this,'httpGet']);
175
+        $this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
176
+        $this->server->on('afterResponse', function($request, ResponseInterface $response) {
177
+            $body = $response->getBody();
178
+            if (is_resource($body)) {
179
+                fclose($body);
180
+            }
181
+        });
182
+        $this->server->on('beforeMove', [$this, 'checkMove']);
183
+        $this->server->on('beforeMove', [$this, 'beforeMoveFutureFile']);
184
+    }
185
+
186
+    /**
187
+     * Plugin that checks if a move can actually be performed.
188
+     *
189
+     * @param string $source source path
190
+     * @param string $destination destination path
191
+     * @throws Forbidden
192
+     * @throws NotFound
193
+     */
194
+    function checkMove($source, $destination) {
195
+        $sourceNode = $this->tree->getNodeForPath($source);
196
+        if (!$sourceNode instanceof Node) {
197
+            return;
198
+        }
199
+        list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($source);
200
+        list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
201
+
202
+        if ($sourceDir !== $destinationDir) {
203
+            $sourceNodeFileInfo = $sourceNode->getFileInfo();
204
+            if (is_null($sourceNodeFileInfo)) {
205
+                throw new NotFound($source . ' does not exist');
206
+            }
207
+
208
+            if (!$sourceNodeFileInfo->isDeletable()) {
209
+                throw new Forbidden($source . " cannot be deleted");
210
+            }
211
+        }
212
+    }
213
+
214
+    /**
215
+     * This sets a cookie to be able to recognize the start of the download
216
+     * the content must not be longer than 32 characters and must only contain
217
+     * alphanumeric characters
218
+     *
219
+     * @param RequestInterface $request
220
+     * @param ResponseInterface $response
221
+     */
222
+    function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
223
+        $queryParams = $request->getQueryParameters();
224
+
225
+        /**
226
+         * this sets a cookie to be able to recognize the start of the download
227
+         * the content must not be longer than 32 characters and must only contain
228
+         * alphanumeric characters
229
+         */
230
+        if (isset($queryParams['downloadStartSecret'])) {
231
+            $token = $queryParams['downloadStartSecret'];
232
+            if (!isset($token[32])
233
+                && preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
234
+                // FIXME: use $response->setHeader() instead
235
+                setcookie('ocDownloadStarted', $token, time() + 20, '/');
236
+            }
237
+        }
238
+    }
239
+
240
+    /**
241
+     * Add headers to file download
242
+     *
243
+     * @param RequestInterface $request
244
+     * @param ResponseInterface $response
245
+     */
246
+    function httpGet(RequestInterface $request, ResponseInterface $response) {
247
+        // Only handle valid files
248
+        $node = $this->tree->getNodeForPath($request->getPath());
249
+        if (!($node instanceof IFile)) return;
250
+
251
+        // adds a 'Content-Disposition: attachment' header in case no disposition
252
+        // header has been set before
253
+        if ($this->downloadAttachment &&
254
+            $response->getHeader('Content-Disposition') === null) {
255
+            $filename = $node->getName();
256
+            if ($this->request->isUserAgent(
257
+                [
258
+                    \OC\AppFramework\Http\Request::USER_AGENT_IE,
259
+                    \OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
260
+                    \OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
261
+                ])) {
262
+                $response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
263
+            } else {
264
+                $response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
265
+                                                        . '; filename="' . rawurlencode($filename) . '"');
266
+            }
267
+        }
268
+
269
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
270
+            //Add OC-Checksum header
271
+            /** @var $node File */
272
+            $checksum = $node->getChecksum();
273
+            if ($checksum !== null && $checksum !== '') {
274
+                $response->addHeader('OC-Checksum', $checksum);
275
+            }
276
+        }
277
+    }
278
+
279
+    /**
280
+     * Adds all ownCloud-specific properties
281
+     *
282
+     * @param PropFind $propFind
283
+     * @param \Sabre\DAV\INode $node
284
+     * @return void
285
+     */
286
+    public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
287
+
288
+        $httpRequest = $this->server->httpRequest;
289
+
290
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
291
+            if (!$node->getFileInfo()->isReadable()) {
292
+                // avoid detecting files through this means
293
+                throw new NotFound();
294
+            }
295
+
296
+            $propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
297
+                return $node->getFileId();
298
+            });
299
+
300
+            $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
301
+                return $node->getInternalFileId();
302
+            });
303
+
304
+            $propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
305
+                $perms = $node->getDavPermissions();
306
+                if ($this->isPublic) {
307
+                    // remove mount information
308
+                    $perms = str_replace(['S', 'M'], '', $perms);
309
+                }
310
+                return $perms;
311
+            });
312
+
313
+            $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
314
+                return $node->getSharePermissions(
315
+                    $httpRequest->getRawServerValue('PHP_AUTH_USER')
316
+                );
317
+            });
318
+
319
+            $propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
320
+                return $node->getETag();
321
+            });
322
+
323
+            $propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
324
+                $owner = $node->getOwner();
325
+                if (!$owner) {
326
+                    return null;
327
+                } else {
328
+                    return $owner->getUID();
329
+                }
330
+            });
331
+            $propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
332
+                $owner = $node->getOwner();
333
+                if (!$owner) {
334
+                    return null;
335
+                } else {
336
+                    return $owner->getDisplayName();
337
+                }
338
+            });
339
+
340
+            $propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
341
+                return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
342
+            });
343
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
344
+                return $node->getSize();
345
+            });
346
+            $propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
347
+                return $node->getFileInfo()->getMountPoint()->getMountType();
348
+            });
349
+        }
350
+
351
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
352
+            $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
353
+                return $this->config->getSystemValue('data-fingerprint', '');
354
+            });
355
+        }
356
+
357
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
358
+            $propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
359
+                /** @var $node \OCA\DAV\Connector\Sabre\File */
360
+                try {
361
+                    $directDownloadUrl = $node->getDirectDownload();
362
+                    if (isset($directDownloadUrl['url'])) {
363
+                        return $directDownloadUrl['url'];
364
+                    }
365
+                } catch (StorageNotAvailableException $e) {
366
+                    return false;
367
+                } catch (ForbiddenException $e) {
368
+                    return false;
369
+                }
370
+                return false;
371
+            });
372
+
373
+            $propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
374
+                $checksum = $node->getChecksum();
375
+                if ($checksum === NULL || $checksum === '') {
376
+                    return null;
377
+                }
378
+
379
+                return new ChecksumList($checksum);
380
+            });
381
+
382
+        }
383
+
384
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
385
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
386
+                return $node->getSize();
387
+            });
388
+        }
389
+    }
390
+
391
+    /**
392
+     * Update ownCloud-specific properties
393
+     *
394
+     * @param string $path
395
+     * @param PropPatch $propPatch
396
+     *
397
+     * @return void
398
+     */
399
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
400
+        $node = $this->tree->getNodeForPath($path);
401
+        if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
402
+            return;
403
+        }
404
+
405
+        $propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($node) {
406
+            if (empty($time)) {
407
+                return false;
408
+            }
409
+            $node->touch($time);
410
+            return true;
411
+        });
412
+        $propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($node) {
413
+            if (empty($etag)) {
414
+                return false;
415
+            }
416
+            if ($node->setEtag($etag) !== -1) {
417
+                return true;
418
+            }
419
+            return false;
420
+        });
421
+    }
422
+
423
+    /**
424
+     * @param string $filePath
425
+     * @param \Sabre\DAV\INode $node
426
+     * @throws \Sabre\DAV\Exception\BadRequest
427
+     */
428
+    public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
429
+        // chunked upload handling
430
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
431
+            list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
432
+            $info = \OC_FileChunking::decodeName($name);
433
+            if (!empty($info)) {
434
+                $filePath = $path . '/' . $info['name'];
435
+            }
436
+        }
437
+
438
+        // we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
439
+        if (!$this->server->tree->nodeExists($filePath)) {
440
+            return;
441
+        }
442
+        $node = $this->server->tree->getNodeForPath($filePath);
443
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
444
+            $fileId = $node->getFileId();
445
+            if (!is_null($fileId)) {
446
+                $this->server->httpResponse->setHeader('OC-FileId', $fileId);
447
+            }
448
+        }
449
+    }
450
+
451
+    /**
452
+     * Move handler for future file.
453
+     *
454
+     * This overrides the default move behavior to prevent Sabre
455
+     * to delete the target file before moving. Because deleting would
456
+     * lose the file id and metadata.
457
+     *
458
+     * @param string $path source path
459
+     * @param string $destination destination path
460
+     * @return bool|void false to stop handling, void to skip this handler
461
+     */
462
+    public function beforeMoveFutureFile($path, $destination) {
463
+        $sourceNode = $this->tree->getNodeForPath($path);
464
+        if (!$sourceNode instanceof FutureFile) {
465
+            // skip handling as the source is not a chunked FutureFile
466
+            return;
467
+        }
468
+
469
+        if (!$this->tree->nodeExists($destination)) {
470
+            // skip and let the default handler do its work
471
+            return;
472
+        }
473
+
474
+        // do a move manually, skipping Sabre's default "delete" for existing nodes
475
+        $this->tree->move($path, $destination);
476
+
477
+        // trigger all default events (copied from CorePlugin::move)
478
+        $this->server->emit('afterMove', [$path, $destination]);
479
+        $this->server->emit('afterUnbind', [$path]);
480
+        $this->server->emit('afterBind', [$destination]);
481
+
482
+        $response = $this->server->httpResponse;
483
+        $response->setHeader('Content-Length', '0');
484
+        $response->setStatus(204);
485
+
486
+        return false;
487
+    }
488 488
 
489 489
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		$this->server->on('propPatch', array($this, 'handleUpdateProperties'));
172 172
 		$this->server->on('afterBind', array($this, 'sendFileIdHeader'));
173 173
 		$this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
174
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
174
+		$this->server->on('afterMethod:GET', [$this, 'httpGet']);
175 175
 		$this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
176 176
 		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
177 177
 			$body = $response->getBody();
@@ -202,11 +202,11 @@  discard block
 block discarded – undo
202 202
 		if ($sourceDir !== $destinationDir) {
203 203
 			$sourceNodeFileInfo = $sourceNode->getFileInfo();
204 204
 			if (is_null($sourceNodeFileInfo)) {
205
-				throw new NotFound($source . ' does not exist');
205
+				throw new NotFound($source.' does not exist');
206 206
 			}
207 207
 
208 208
 			if (!$sourceNodeFileInfo->isDeletable()) {
209
-				throw new Forbidden($source . " cannot be deleted");
209
+				throw new Forbidden($source." cannot be deleted");
210 210
 			}
211 211
 		}
212 212
 	}
@@ -259,10 +259,10 @@  discard block
 block discarded – undo
259 259
 					\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
260 260
 					\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
261 261
 				])) {
262
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
262
+				$response->addHeader('Content-Disposition', 'attachment; filename="'.rawurlencode($filename).'"');
263 263
 			} else {
264
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
265
-													 . '; filename="' . rawurlencode($filename) . '"');
264
+				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\''.rawurlencode($filename)
265
+													 . '; filename="'.rawurlencode($filename).'"');
266 266
 			}
267 267
 		}
268 268
 
@@ -337,13 +337,13 @@  discard block
 block discarded – undo
337 337
 				}
338 338
 			});
339 339
 
340
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
340
+			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function() use ($node) {
341 341
 				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
342 342
 			});
343 343
 			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
344 344
 				return $node->getSize();
345 345
 			});
346
-			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
346
+			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function() use ($node) {
347 347
 				return $node->getFileInfo()->getMountPoint()->getMountType();
348 348
 			});
349 349
 		}
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
 			list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
432 432
 			$info = \OC_FileChunking::decodeName($name);
433 433
 			if (!empty($info)) {
434
-				$filePath = $path . '/' . $info['name'];
434
+				$filePath = $path.'/'.$info['name'];
435 435
 			}
436 436
 		}
437 437
 
Please login to merge, or discard this patch.