You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FilesPlugin.php 16KB

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