FilesPlugin.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Björn Schießle <bjoern@schiessle.org>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <robin@icewind.nl>
  10. * @author Robin McCorkell <robin@mccorkell.me.uk>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <pvince81@owncloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OCA\DAV\Connector\Sabre;
  31. use OC\Files\View;
  32. use OCA\DAV\Upload\FutureFile;
  33. use OCP\Files\ForbiddenException;
  34. use OCP\IPreview;
  35. use Sabre\DAV\Exception\Forbidden;
  36. use Sabre\DAV\Exception\NotFound;
  37. use Sabre\DAV\IFile;
  38. use \Sabre\DAV\PropFind;
  39. use \Sabre\DAV\PropPatch;
  40. use Sabre\DAV\ServerPlugin;
  41. use Sabre\DAV\Tree;
  42. use \Sabre\HTTP\RequestInterface;
  43. use \Sabre\HTTP\ResponseInterface;
  44. use OCP\Files\StorageNotAvailableException;
  45. use OCP\IConfig;
  46. use OCP\IRequest;
  47. use Sabre\DAV\Exception\BadRequest;
  48. use OCA\DAV\Connector\Sabre\Directory;
  49. class FilesPlugin extends ServerPlugin {
  50. // namespace
  51. const NS_OWNCLOUD = 'http://owncloud.org/ns';
  52. const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
  53. const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
  54. const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
  55. const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
  56. const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
  57. const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
  58. const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
  59. const GETETAG_PROPERTYNAME = '{DAV:}getetag';
  60. const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
  61. const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
  62. const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
  63. const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
  64. const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
  65. const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
  66. /**
  67. * Reference to main server object
  68. *
  69. * @var \Sabre\DAV\Server
  70. */
  71. private $server;
  72. /**
  73. * @var Tree
  74. */
  75. private $tree;
  76. /**
  77. * Whether this is public webdav.
  78. * If true, some returned information will be stripped off.
  79. *
  80. * @var bool
  81. */
  82. private $isPublic;
  83. /**
  84. * @var View
  85. */
  86. private $fileView;
  87. /**
  88. * @var bool
  89. */
  90. private $downloadAttachment;
  91. /**
  92. * @var IConfig
  93. */
  94. private $config;
  95. /**
  96. * @var IRequest
  97. */
  98. private $request;
  99. /**
  100. * @var IPreview
  101. */
  102. private $previewManager;
  103. /**
  104. * @param Tree $tree
  105. * @param IConfig $config
  106. * @param IRequest $request
  107. * @param IPreview $previewManager
  108. * @param bool $isPublic
  109. * @param bool $downloadAttachment
  110. */
  111. public function __construct(Tree $tree,
  112. IConfig $config,
  113. IRequest $request,
  114. IPreview $previewManager,
  115. $isPublic = false,
  116. $downloadAttachment = true) {
  117. $this->tree = $tree;
  118. $this->config = $config;
  119. $this->request = $request;
  120. $this->isPublic = $isPublic;
  121. $this->downloadAttachment = $downloadAttachment;
  122. $this->previewManager = $previewManager;
  123. }
  124. /**
  125. * This initializes the plugin.
  126. *
  127. * This function is called by \Sabre\DAV\Server, after
  128. * addPlugin is called.
  129. *
  130. * This method should set up the required event subscriptions.
  131. *
  132. * @param \Sabre\DAV\Server $server
  133. * @return void
  134. */
  135. public function initialize(\Sabre\DAV\Server $server) {
  136. $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
  137. $server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
  138. $server->protectedProperties[] = self::FILEID_PROPERTYNAME;
  139. $server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
  140. $server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
  141. $server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
  142. $server->protectedProperties[] = self::SIZE_PROPERTYNAME;
  143. $server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
  144. $server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
  145. $server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
  146. $server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
  147. $server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
  148. $server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
  149. // normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
  150. $allowedProperties = ['{DAV:}getetag'];
  151. $server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
  152. $this->server = $server;
  153. $this->server->on('propFind', array($this, 'handleGetProperties'));
  154. $this->server->on('propPatch', array($this, 'handleUpdateProperties'));
  155. $this->server->on('afterBind', array($this, 'sendFileIdHeader'));
  156. $this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
  157. $this->server->on('afterMethod:GET', [$this,'httpGet']);
  158. $this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
  159. $this->server->on('afterResponse', function($request, ResponseInterface $response) {
  160. $body = $response->getBody();
  161. if (is_resource($body)) {
  162. fclose($body);
  163. }
  164. });
  165. $this->server->on('beforeMove', [$this, 'checkMove']);
  166. }
  167. /**
  168. * Plugin that checks if a move can actually be performed.
  169. *
  170. * @param string $source source path
  171. * @param string $destination destination path
  172. * @throws Forbidden
  173. * @throws NotFound
  174. */
  175. function checkMove($source, $destination) {
  176. $sourceNode = $this->tree->getNodeForPath($source);
  177. if (!$sourceNode instanceof Node) {
  178. return;
  179. }
  180. list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($source);
  181. list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
  182. if ($sourceDir !== $destinationDir) {
  183. $sourceNodeFileInfo = $sourceNode->getFileInfo();
  184. if (is_null($sourceNodeFileInfo)) {
  185. throw new NotFound($source . ' does not exist');
  186. }
  187. if (!$sourceNodeFileInfo->isDeletable()) {
  188. throw new Forbidden($source . " cannot be deleted");
  189. }
  190. }
  191. }
  192. /**
  193. * This sets a cookie to be able to recognize the start of the download
  194. * the content must not be longer than 32 characters and must only contain
  195. * alphanumeric characters
  196. *
  197. * @param RequestInterface $request
  198. * @param ResponseInterface $response
  199. */
  200. function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
  201. $queryParams = $request->getQueryParameters();
  202. /**
  203. * this sets a cookie to be able to recognize the start of the download
  204. * the content must not be longer than 32 characters and must only contain
  205. * alphanumeric characters
  206. */
  207. if (isset($queryParams['downloadStartSecret'])) {
  208. $token = $queryParams['downloadStartSecret'];
  209. if (!isset($token[32])
  210. && preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
  211. // FIXME: use $response->setHeader() instead
  212. setcookie('ocDownloadStarted', $token, time() + 20, '/');
  213. }
  214. }
  215. }
  216. /**
  217. * Add headers to file download
  218. *
  219. * @param RequestInterface $request
  220. * @param ResponseInterface $response
  221. */
  222. function httpGet(RequestInterface $request, ResponseInterface $response) {
  223. // Only handle valid files
  224. $node = $this->tree->getNodeForPath($request->getPath());
  225. if (!($node instanceof IFile)) return;
  226. // adds a 'Content-Disposition: attachment' header in case no disposition
  227. // header has been set before
  228. if ($this->downloadAttachment &&
  229. $response->getHeader('Content-Disposition') === null) {
  230. $filename = $node->getName();
  231. if ($this->request->isUserAgent(
  232. [
  233. \OC\AppFramework\Http\Request::USER_AGENT_IE,
  234. \OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
  235. \OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
  236. ])) {
  237. $response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
  238. } else {
  239. $response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
  240. . '; filename="' . rawurlencode($filename) . '"');
  241. }
  242. }
  243. if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
  244. //Add OC-Checksum header
  245. /** @var $node File */
  246. $checksum = $node->getChecksum();
  247. if ($checksum !== null && $checksum !== '') {
  248. $response->addHeader('OC-Checksum', $checksum);
  249. }
  250. }
  251. }
  252. /**
  253. * Adds all ownCloud-specific properties
  254. *
  255. * @param PropFind $propFind
  256. * @param \Sabre\DAV\INode $node
  257. * @return void
  258. */
  259. public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
  260. $httpRequest = $this->server->httpRequest;
  261. if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
  262. $propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
  263. return $node->getFileId();
  264. });
  265. $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
  266. return $node->getInternalFileId();
  267. });
  268. $propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
  269. $perms = $node->getDavPermissions();
  270. if ($this->isPublic) {
  271. // remove mount information
  272. $perms = str_replace(['S', 'M'], '', $perms);
  273. }
  274. return $perms;
  275. });
  276. $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
  277. return $node->getSharePermissions(
  278. $httpRequest->getRawServerValue('PHP_AUTH_USER')
  279. );
  280. });
  281. $propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
  282. return $node->getETag();
  283. });
  284. $propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
  285. $owner = $node->getOwner();
  286. if (!$owner) {
  287. return null;
  288. } else {
  289. return $owner->getUID();
  290. }
  291. });
  292. $propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
  293. $owner = $node->getOwner();
  294. if (!$owner) {
  295. return null;
  296. } else {
  297. return $owner->getDisplayName();
  298. }
  299. });
  300. $propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
  301. return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
  302. });
  303. $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
  304. return $node->getSize();
  305. });
  306. }
  307. if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
  308. $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
  309. return $this->config->getSystemValue('data-fingerprint', '');
  310. });
  311. }
  312. if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
  313. $propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
  314. /** @var $node \OCA\DAV\Connector\Sabre\File */
  315. try {
  316. $directDownloadUrl = $node->getDirectDownload();
  317. if (isset($directDownloadUrl['url'])) {
  318. return $directDownloadUrl['url'];
  319. }
  320. } catch (StorageNotAvailableException $e) {
  321. return false;
  322. } catch (ForbiddenException $e) {
  323. return false;
  324. }
  325. return false;
  326. });
  327. $propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
  328. $checksum = $node->getChecksum();
  329. if ($checksum === NULL || $checksum === '') {
  330. return null;
  331. }
  332. return new ChecksumList($checksum);
  333. });
  334. }
  335. if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
  336. $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
  337. return $node->getSize();
  338. });
  339. }
  340. }
  341. /**
  342. * Update ownCloud-specific properties
  343. *
  344. * @param string $path
  345. * @param PropPatch $propPatch
  346. *
  347. * @return void
  348. */
  349. public function handleUpdateProperties($path, PropPatch $propPatch) {
  350. $propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($path) {
  351. if (empty($time)) {
  352. return false;
  353. }
  354. $node = $this->tree->getNodeForPath($path);
  355. if (is_null($node)) {
  356. return 404;
  357. }
  358. $node->touch($time);
  359. return true;
  360. });
  361. $propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($path) {
  362. if (empty($etag)) {
  363. return false;
  364. }
  365. $node = $this->tree->getNodeForPath($path);
  366. if (is_null($node)) {
  367. return 404;
  368. }
  369. if ($node->setEtag($etag) !== -1) {
  370. return true;
  371. }
  372. return false;
  373. });
  374. }
  375. /**
  376. * @param string $filePath
  377. * @param \Sabre\DAV\INode $node
  378. * @throws \Sabre\DAV\Exception\BadRequest
  379. */
  380. public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
  381. // chunked upload handling
  382. if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
  383. list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
  384. $info = \OC_FileChunking::decodeName($name);
  385. if (!empty($info)) {
  386. $filePath = $path . '/' . $info['name'];
  387. }
  388. }
  389. // we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
  390. if (!$this->server->tree->nodeExists($filePath)) {
  391. return;
  392. }
  393. $node = $this->server->tree->getNodeForPath($filePath);
  394. if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
  395. $fileId = $node->getFileId();
  396. if (!is_null($fileId)) {
  397. $this->server->httpResponse->setHeader('OC-FileId', $fileId);
  398. }
  399. }
  400. }
  401. }