From ce897f80e60a4e2258da89745b8fda030f548df8 Mon Sep 17 00:00:00 2001
From: Vincent Petry <pvince81@owncloud.com>
Date: Thu, 19 Nov 2015 12:01:55 +0100
Subject: [PATCH] Send download token as cookie to tell the UI that it started

This used to be done in the ajax download code. Now that single file
downloads are going through Webdav, the token handling needs to be done
here too.
---
 apps/dav/lib/connector/sabre/filesplugin.php | 27 ++++++++++++++++++++
 1 file changed, 27 insertions(+)

diff --git a/apps/dav/lib/connector/sabre/filesplugin.php b/apps/dav/lib/connector/sabre/filesplugin.php
index d68397dcaa..e85a67a875 100644
--- a/apps/dav/lib/connector/sabre/filesplugin.php
+++ b/apps/dav/lib/connector/sabre/filesplugin.php
@@ -116,6 +116,7 @@ class FilesPlugin extends \Sabre\DAV\ServerPlugin {
 		$this->server->on('afterBind', array($this, 'sendFileIdHeader'));
 		$this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
 		$this->server->on('afterMethod:GET', [$this,'httpGet']);
+		$this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
 		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
 			$body = $response->getBody();
 			if (is_resource($body)) {
@@ -148,6 +149,32 @@ class FilesPlugin extends \Sabre\DAV\ServerPlugin {
 		}
 	}
 
+	/**
+	 * This sets a cookie to be able to recognize the start of the download
+	 * the content must not be longer than 32 characters and must only contain
+	 * alphanumeric characters
+	 *
+	 * @param RequestInterface $request
+	 * @param ResponseInterface $response
+	 */
+	function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
+		$queryParams = $request->getQueryParameters();
+
+		/**
+		 * this sets a cookie to be able to recognize the start of the download
+		 * the content must not be longer than 32 characters and must only contain
+		 * alphanumeric characters
+		 */
+		if (isset($queryParams['downloadStartSecret'])) {
+			$token = $queryParams['downloadStartSecret'];
+			if (!isset($token[32])
+				&& preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
+				// FIXME: use $response->setHeader() instead
+				setcookie('ocDownloadStarted', $token, time() + 20, '/');
+			}
+		}
+	}
+
 	/**
 	 * Plugin that adds a 'Content-Disposition: attachment' header to all files
 	 * delivered by SabreDAV.
-- 
GitLab