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.

1497 lines
46 KiB

3 years ago
  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 Daniel Calviño Sánchez <danxuliu@gmail.com>
  9. * @author Jan-Philipp Litza <jplitza@users.noreply.github.com>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Maxence Lange <maxence@artificial-owl.com>
  14. * @author phisch <git@philippschaffrath.de>
  15. * @author Robin Appelman <robin@icewind.nl>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Vincent Petry <pvince81@owncloud.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 OC\Share20;
  35. use OC\Files\Cache\Cache;
  36. use OC\Share20\Exception\BackendError;
  37. use OC\Share20\Exception\InvalidShare;
  38. use OC\Share20\Exception\ProviderException;
  39. use OCP\DB\QueryBuilder\IQueryBuilder;
  40. use OCP\Defaults;
  41. use OCP\Files\Folder;
  42. use OCP\Files\IRootFolder;
  43. use OCP\Files\Node;
  44. use OCP\IConfig;
  45. use OCP\IDBConnection;
  46. use OCP\IGroupManager;
  47. use OCP\IURLGenerator;
  48. use OCP\IUser;
  49. use OCP\IUserManager;
  50. use OCP\L10N\IFactory;
  51. use OCP\Mail\IMailer;
  52. use OCP\Share\Exceptions\ShareNotFound;
  53. use OCP\Share\IShare;
  54. use OCP\Share\IShareProvider;
  55. /**
  56. * Class DefaultShareProvider
  57. *
  58. * @package OC\Share20
  59. */
  60. class DefaultShareProvider implements IShareProvider {
  61. // Special share type for user modified group shares
  62. public const SHARE_TYPE_USERGROUP = 2;
  63. /** @var IDBConnection */
  64. private $dbConn;
  65. /** @var IUserManager */
  66. private $userManager;
  67. /** @var IGroupManager */
  68. private $groupManager;
  69. /** @var IRootFolder */
  70. private $rootFolder;
  71. /** @var IMailer */
  72. private $mailer;
  73. /** @var Defaults */
  74. private $defaults;
  75. /** @var IFactory */
  76. private $l10nFactory;
  77. /** @var IURLGenerator */
  78. private $urlGenerator;
  79. /** @var IConfig */
  80. private $config;
  81. public function __construct(
  82. IDBConnection $connection,
  83. IUserManager $userManager,
  84. IGroupManager $groupManager,
  85. IRootFolder $rootFolder,
  86. IMailer $mailer,
  87. Defaults $defaults,
  88. IFactory $l10nFactory,
  89. IURLGenerator $urlGenerator,
  90. IConfig $config) {
  91. $this->dbConn = $connection;
  92. $this->userManager = $userManager;
  93. $this->groupManager = $groupManager;
  94. $this->rootFolder = $rootFolder;
  95. $this->mailer = $mailer;
  96. $this->defaults = $defaults;
  97. $this->l10nFactory = $l10nFactory;
  98. $this->urlGenerator = $urlGenerator;
  99. $this->config = $config;
  100. }
  101. /**
  102. * Return the identifier of this provider.
  103. *
  104. * @return string Containing only [a-zA-Z0-9]
  105. */
  106. public function identifier() {
  107. return 'ocinternal';
  108. }
  109. /**
  110. * Share a path
  111. *
  112. * @param \OCP\Share\IShare $share
  113. * @return \OCP\Share\IShare The share object
  114. * @throws ShareNotFound
  115. * @throws \Exception
  116. */
  117. public function create(\OCP\Share\IShare $share) {
  118. $qb = $this->dbConn->getQueryBuilder();
  119. $qb->insert('share');
  120. $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
  121. if ($share->getShareType() === IShare::TYPE_USER) {
  122. //Set the UID of the user we share with
  123. $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
  124. $qb->setValue('accepted', $qb->createNamedParameter(IShare::STATUS_PENDING));
  125. //If an expiration date is set store it
  126. if ($share->getExpirationDate() !== null) {
  127. $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
  128. }
  129. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  130. //Set the GID of the group we share with
  131. $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
  132. //If an expiration date is set store it
  133. if ($share->getExpirationDate() !== null) {
  134. $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
  135. }
  136. } elseif ($share->getShareType() === IShare::TYPE_LINK) {
  137. //set label for public link
  138. $qb->setValue('label', $qb->createNamedParameter($share->getLabel()));
  139. //Set the token of the share
  140. $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
  141. //If a password is set store it
  142. if ($share->getPassword() !== null) {
  143. $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
  144. }
  145. $qb->setValue('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL));
  146. //If an expiration date is set store it
  147. if ($share->getExpirationDate() !== null) {
  148. $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
  149. }
  150. if (method_exists($share, 'getParent')) {
  151. $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
  152. }
  153. } else {
  154. throw new \Exception('invalid share type!');
  155. }
  156. // Set what is shares
  157. $qb->setValue('item_type', $qb->createParameter('itemType'));
  158. if ($share->getNode() instanceof \OCP\Files\File) {
  159. $qb->setParameter('itemType', 'file');
  160. } else {
  161. $qb->setParameter('itemType', 'folder');
  162. }
  163. // Set the file id
  164. $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
  165. $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
  166. // set the permissions
  167. $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
  168. // Set who created this share
  169. $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
  170. // Set who is the owner of this file/folder (and this the owner of the share)
  171. $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
  172. // Set the file target
  173. $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
  174. // Set the time this share was created
  175. $qb->setValue('stime', $qb->createNamedParameter(time()));
  176. // insert the data and fetch the id of the share
  177. $this->dbConn->beginTransaction();
  178. $qb->execute();
  179. $id = $this->dbConn->lastInsertId('*PREFIX*share');
  180. // Now fetch the inserted share and create a complete share object
  181. $qb = $this->dbConn->getQueryBuilder();
  182. $qb->select('*')
  183. ->from('share')
  184. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
  185. $cursor = $qb->execute();
  186. $data = $cursor->fetch();
  187. $this->dbConn->commit();
  188. $cursor->closeCursor();
  189. if ($data === false) {
  190. throw new ShareNotFound();
  191. }
  192. $mailSendValue = $share->getMailSend();
  193. $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
  194. $share = $this->createShare($data);
  195. return $share;
  196. }
  197. /**
  198. * Update a share
  199. *
  200. * @param \OCP\Share\IShare $share
  201. * @return \OCP\Share\IShare The share object
  202. * @throws ShareNotFound
  203. * @throws \OCP\Files\InvalidPathException
  204. * @throws \OCP\Files\NotFoundException
  205. */
  206. public function update(\OCP\Share\IShare $share) {
  207. $originalShare = $this->getShareById($share->getId());
  208. if ($share->getShareType() === IShare::TYPE_USER) {
  209. /*
  210. * We allow updating the recipient on user shares.
  211. */
  212. $qb = $this->dbConn->getQueryBuilder();
  213. $qb->update('share')
  214. ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
  215. ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
  216. ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
  217. ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
  218. ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
  219. ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
  220. ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
  221. ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
  222. ->set('note', $qb->createNamedParameter($share->getNote()))
  223. ->set('accepted', $qb->createNamedParameter($share->getStatus()))
  224. ->execute();
  225. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  226. $qb = $this->dbConn->getQueryBuilder();
  227. $qb->update('share')
  228. ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
  229. ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
  230. ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
  231. ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
  232. ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
  233. ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
  234. ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
  235. ->set('note', $qb->createNamedParameter($share->getNote()))
  236. ->execute();
  237. /*
  238. * Update all user defined group shares
  239. */
  240. $qb = $this->dbConn->getQueryBuilder();
  241. $qb->update('share')
  242. ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
  243. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  244. ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
  245. ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
  246. ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
  247. ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
  248. ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
  249. ->set('note', $qb->createNamedParameter($share->getNote()))
  250. ->execute();
  251. /*
  252. * Now update the permissions for all children that have not set it to 0
  253. */
  254. $qb = $this->dbConn->getQueryBuilder();
  255. $qb->update('share')
  256. ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
  257. ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
  258. ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
  259. ->execute();
  260. } elseif ($share->getShareType() === IShare::TYPE_LINK) {
  261. $qb = $this->dbConn->getQueryBuilder();
  262. $qb->update('share')
  263. ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
  264. ->set('password', $qb->createNamedParameter($share->getPassword()))
  265. ->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
  266. ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
  267. ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
  268. ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
  269. ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
  270. ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
  271. ->set('token', $qb->createNamedParameter($share->getToken()))
  272. ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
  273. ->set('note', $qb->createNamedParameter($share->getNote()))
  274. ->set('label', $qb->createNamedParameter($share->getLabel()))
  275. ->set('hide_download', $qb->createNamedParameter($share->getHideDownload() ? 1 : 0), IQueryBuilder::PARAM_INT)
  276. ->execute();
  277. }
  278. if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
  279. $this->propagateNote($share);
  280. }
  281. return $share;
  282. }
  283. /**
  284. * Accept a share.
  285. *
  286. * @param IShare $share
  287. * @param string $recipient
  288. * @return IShare The share object
  289. * @since 9.0.0
  290. */
  291. public function acceptShare(IShare $share, string $recipient): IShare {
  292. if ($share->getShareType() === IShare::TYPE_GROUP) {
  293. $group = $this->groupManager->get($share->getSharedWith());
  294. $user = $this->userManager->get($recipient);
  295. if (is_null($group)) {
  296. throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
  297. }
  298. if (!$group->inGroup($user)) {
  299. throw new ProviderException('Recipient not in receiving group');
  300. }
  301. // Try to fetch user specific share
  302. $qb = $this->dbConn->getQueryBuilder();
  303. $stmt = $qb->select('*')
  304. ->from('share')
  305. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  306. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
  307. ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
  308. ->andWhere($qb->expr()->orX(
  309. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  310. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  311. ))
  312. ->execute();
  313. $data = $stmt->fetch();
  314. $stmt->closeCursor();
  315. /*
  316. * Check if there already is a user specific group share.
  317. * If there is update it (if required).
  318. */
  319. if ($data === false) {
  320. $id = $this->createUserSpecificGroupShare($share, $recipient);
  321. } else {
  322. $id = $data['id'];
  323. }
  324. } elseif ($share->getShareType() === IShare::TYPE_USER) {
  325. if ($share->getSharedWith() !== $recipient) {
  326. throw new ProviderException('Recipient does not match');
  327. }
  328. $id = $share->getId();
  329. } else {
  330. throw new ProviderException('Invalid shareType');
  331. }
  332. $qb = $this->dbConn->getQueryBuilder();
  333. $qb->update('share')
  334. ->set('accepted', $qb->createNamedParameter(IShare::STATUS_ACCEPTED))
  335. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  336. ->execute();
  337. return $share;
  338. }
  339. /**
  340. * Get all children of this share
  341. * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
  342. *
  343. * @param \OCP\Share\IShare $parent
  344. * @return \OCP\Share\IShare[]
  345. */
  346. public function getChildren(\OCP\Share\IShare $parent) {
  347. $children = [];
  348. $qb = $this->dbConn->getQueryBuilder();
  349. $qb->select('*')
  350. ->from('share')
  351. ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
  352. ->andWhere(
  353. $qb->expr()->in(
  354. 'share_type',
  355. $qb->createNamedParameter([
  356. IShare::TYPE_USER,
  357. IShare::TYPE_GROUP,
  358. IShare::TYPE_LINK,
  359. ], IQueryBuilder::PARAM_INT_ARRAY)
  360. )
  361. )
  362. ->andWhere($qb->expr()->orX(
  363. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  364. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  365. ))
  366. ->orderBy('id');
  367. $cursor = $qb->execute();
  368. while ($data = $cursor->fetch()) {
  369. $children[] = $this->createShare($data);
  370. }
  371. $cursor->closeCursor();
  372. return $children;
  373. }
  374. /**
  375. * Delete a share
  376. *
  377. * @param \OCP\Share\IShare $share
  378. */
  379. public function delete(\OCP\Share\IShare $share) {
  380. $qb = $this->dbConn->getQueryBuilder();
  381. $qb->delete('share')
  382. ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
  383. /*
  384. * If the share is a group share delete all possible
  385. * user defined groups shares.
  386. */
  387. if ($share->getShareType() === IShare::TYPE_GROUP) {
  388. $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
  389. }
  390. $qb->execute();
  391. }
  392. /**
  393. * Unshare a share from the recipient. If this is a group share
  394. * this means we need a special entry in the share db.
  395. *
  396. * @param IShare $share
  397. * @param string $recipient UserId of recipient
  398. * @throws BackendError
  399. * @throws ProviderException
  400. */
  401. public function deleteFromSelf(IShare $share, $recipient) {
  402. if ($share->getShareType() === IShare::TYPE_GROUP) {
  403. $group = $this->groupManager->get($share->getSharedWith());
  404. $user = $this->userManager->get($recipient);
  405. if (is_null($group)) {
  406. throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
  407. }
  408. if (!$group->inGroup($user)) {
  409. throw new ProviderException('Recipient not in receiving group');
  410. }
  411. // Try to fetch user specific share
  412. $qb = $this->dbConn->getQueryBuilder();
  413. $stmt = $qb->select('*')
  414. ->from('share')
  415. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  416. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
  417. ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
  418. ->andWhere($qb->expr()->orX(
  419. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  420. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  421. ))
  422. ->execute();
  423. $data = $stmt->fetch();
  424. /*
  425. * Check if there already is a user specific group share.
  426. * If there is update it (if required).
  427. */
  428. if ($data === false) {
  429. $id = $this->createUserSpecificGroupShare($share, $recipient);
  430. $permissions = $share->getPermissions();
  431. } else {
  432. $permissions = $data['permissions'];
  433. $id = $data['id'];
  434. }
  435. if ($permissions !== 0) {
  436. // Update existing usergroup share
  437. $qb = $this->dbConn->getQueryBuilder();
  438. $qb->update('share')
  439. ->set('permissions', $qb->createNamedParameter(0))
  440. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  441. ->execute();
  442. }
  443. } elseif ($share->getShareType() === IShare::TYPE_USER) {
  444. if ($share->getSharedWith() !== $recipient) {
  445. throw new ProviderException('Recipient does not match');
  446. }
  447. // We can just delete user and link shares
  448. $this->delete($share);
  449. } else {
  450. throw new ProviderException('Invalid shareType');
  451. }
  452. }
  453. protected function createUserSpecificGroupShare(IShare $share, string $recipient): int {
  454. $type = $share->getNodeType();
  455. $qb = $this->dbConn->getQueryBuilder();
  456. $qb->insert('share')
  457. ->values([
  458. 'share_type' => $qb->createNamedParameter(IShare::TYPE_USERGROUP),
  459. 'share_with' => $qb->createNamedParameter($recipient),
  460. 'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
  461. 'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
  462. 'parent' => $qb->createNamedParameter($share->getId()),
  463. 'item_type' => $qb->createNamedParameter($type),
  464. 'item_source' => $qb->createNamedParameter($share->getNodeId()),
  465. 'file_source' => $qb->createNamedParameter($share->getNodeId()),
  466. 'file_target' => $qb->createNamedParameter($share->getTarget()),
  467. 'permissions' => $qb->createNamedParameter($share->getPermissions()),
  468. 'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
  469. ])->execute();
  470. return $qb->getLastInsertId();
  471. }
  472. /**
  473. * @inheritdoc
  474. *
  475. * For now this only works for group shares
  476. * If this gets implemented for normal shares we have to extend it
  477. */
  478. public function restore(IShare $share, string $recipient): IShare {
  479. $qb = $this->dbConn->getQueryBuilder();
  480. $qb->select('permissions')
  481. ->from('share')
  482. ->where(
  483. $qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))
  484. );
  485. $cursor = $qb->execute();
  486. $data = $cursor->fetch();
  487. $cursor->closeCursor();
  488. $originalPermission = $data['permissions'];
  489. $qb = $this->dbConn->getQueryBuilder();
  490. $qb->update('share')
  491. ->set('permissions', $qb->createNamedParameter($originalPermission))
  492. ->where(
  493. $qb->expr()->eq('parent', $qb->createNamedParameter($share->getParent()))
  494. )->andWhere(
  495. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP))
  496. )->andWhere(
  497. $qb->expr()->eq('share_with', $qb->createNamedParameter($recipient))
  498. );
  499. $qb->execute();
  500. return $this->getShareById($share->getId(), $recipient);
  501. }
  502. /**
  503. * @inheritdoc
  504. */
  505. public function move(\OCP\Share\IShare $share, $recipient) {
  506. if ($share->getShareType() === IShare::TYPE_USER) {
  507. // Just update the target
  508. $qb = $this->dbConn->getQueryBuilder();
  509. $qb->update('share')
  510. ->set('file_target', $qb->createNamedParameter($share->getTarget()))
  511. ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
  512. ->execute();
  513. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  514. // Check if there is a usergroup share
  515. $qb = $this->dbConn->getQueryBuilder();
  516. $stmt = $qb->select('id')
  517. ->from('share')
  518. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  519. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
  520. ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
  521. ->andWhere($qb->expr()->orX(
  522. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  523. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  524. ))
  525. ->setMaxResults(1)
  526. ->execute();
  527. $data = $stmt->fetch();
  528. $stmt->closeCursor();
  529. if ($data === false) {
  530. // No usergroup share yet. Create one.
  531. $qb = $this->dbConn->getQueryBuilder();
  532. $qb->insert('share')
  533. ->values([
  534. 'share_type' => $qb->createNamedParameter(IShare::TYPE_USERGROUP),
  535. 'share_with' => $qb->createNamedParameter($recipient),
  536. 'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
  537. 'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
  538. 'parent' => $qb->createNamedParameter($share->getId()),
  539. 'item_type' => $qb->createNamedParameter($share->getNodeType()),
  540. 'item_source' => $qb->createNamedParameter($share->getNodeId()),
  541. 'file_source' => $qb->createNamedParameter($share->getNodeId()),
  542. 'file_target' => $qb->createNamedParameter($share->getTarget()),
  543. 'permissions' => $qb->createNamedParameter($share->getPermissions()),
  544. 'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
  545. ])->execute();
  546. } else {
  547. // Already a usergroup share. Update it.
  548. $qb = $this->dbConn->getQueryBuilder();
  549. $qb->update('share')
  550. ->set('file_target', $qb->createNamedParameter($share->getTarget()))
  551. ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
  552. ->execute();
  553. }
  554. }
  555. return $share;
  556. }
  557. public function getSharesInFolder($userId, Folder $node, $reshares) {
  558. $qb = $this->dbConn->getQueryBuilder();
  559. $qb->select('*')
  560. ->from('share', 's')
  561. ->andWhere($qb->expr()->orX(
  562. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  563. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  564. ));
  565. $qb->andWhere($qb->expr()->orX(
  566. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)),
  567. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)),
  568. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK))
  569. ));
  570. /**
  571. * Reshares for this user are shares where they are the owner.
  572. */
  573. if ($reshares === false) {
  574. $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
  575. } else {
  576. $qb->andWhere(
  577. $qb->expr()->orX(
  578. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  579. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  580. )
  581. );
  582. }
  583. $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
  584. $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
  585. $qb->orderBy('id');
  586. $cursor = $qb->execute();
  587. $shares = [];
  588. while ($data = $cursor->fetch()) {
  589. $shares[$data['fileid']][] = $this->createShare($data);
  590. }
  591. $cursor->closeCursor();
  592. return $shares;
  593. }
  594. /**
  595. * @inheritdoc
  596. */
  597. public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
  598. $qb = $this->dbConn->getQueryBuilder();
  599. $qb->select('*')
  600. ->from('share')
  601. ->andWhere($qb->expr()->orX(
  602. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  603. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  604. ));
  605. $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
  606. /**
  607. * Reshares for this user are shares where they are the owner.
  608. */
  609. if ($reshares === false) {
  610. $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
  611. } else {
  612. if ($node === null) {
  613. $qb->andWhere(
  614. $qb->expr()->orX(
  615. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  616. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  617. )
  618. );
  619. }
  620. }
  621. if ($node !== null) {
  622. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  623. }
  624. if ($limit !== -1) {
  625. $qb->setMaxResults($limit);
  626. }
  627. $qb->setFirstResult($offset);
  628. $qb->orderBy('id');
  629. $cursor = $qb->execute();
  630. $shares = [];
  631. while ($data = $cursor->fetch()) {
  632. $shares[] = $this->createShare($data);
  633. }
  634. $cursor->closeCursor();
  635. return $shares;
  636. }
  637. /**
  638. * @inheritdoc
  639. */
  640. public function getShareById($id, $recipientId = null) {
  641. $qb = $this->dbConn->getQueryBuilder();
  642. $qb->select('*')
  643. ->from('share')
  644. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  645. ->andWhere(
  646. $qb->expr()->in(
  647. 'share_type',
  648. $qb->createNamedParameter([
  649. IShare::TYPE_USER,
  650. IShare::TYPE_GROUP,
  651. IShare::TYPE_LINK,
  652. ], IQueryBuilder::PARAM_INT_ARRAY)
  653. )
  654. )
  655. ->andWhere($qb->expr()->orX(
  656. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  657. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  658. ));
  659. $cursor = $qb->execute();
  660. $data = $cursor->fetch();
  661. $cursor->closeCursor();
  662. if ($data === false) {
  663. throw new ShareNotFound();
  664. }
  665. try {
  666. $share = $this->createShare($data);
  667. } catch (InvalidShare $e) {
  668. throw new ShareNotFound();
  669. }
  670. // If the recipient is set for a group share resolve to that user
  671. if ($recipientId !== null && $share->getShareType() === IShare::TYPE_GROUP) {
  672. $share = $this->resolveGroupShares([$share], $recipientId)[0];
  673. }
  674. return $share;
  675. }
  676. /**
  677. * Get shares for a given path
  678. *
  679. * @param \OCP\Files\Node $path
  680. * @return \OCP\Share\IShare[]
  681. */
  682. public function getSharesByPath(Node $path) {
  683. $qb = $this->dbConn->getQueryBuilder();
  684. $cursor = $qb->select('*')
  685. ->from('share')
  686. ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
  687. ->andWhere(
  688. $qb->expr()->orX(
  689. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)),
  690. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP))
  691. )
  692. )
  693. ->andWhere($qb->expr()->orX(
  694. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  695. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  696. ))
  697. ->execute();
  698. $shares = [];
  699. while ($data = $cursor->fetch()) {
  700. $shares[] = $this->createShare($data);
  701. }
  702. $cursor->closeCursor();
  703. return $shares;
  704. }
  705. /**
  706. * Returns whether the given database result can be interpreted as
  707. * a share with accessible file (not trashed, not deleted)
  708. */
  709. private function isAccessibleResult($data) {
  710. // exclude shares leading to deleted file entries
  711. if ($data['fileid'] === null || $data['path'] === null) {
  712. return false;
  713. }
  714. // exclude shares leading to trashbin on home storages
  715. $pathSections = explode('/', $data['path'], 2);
  716. // FIXME: would not detect rare md5'd home storage case properly
  717. if ($pathSections[0] !== 'files'
  718. && in_array(explode(':', $data['storage_string_id'], 2)[0], ['home', 'object'])) {
  719. return false;
  720. }
  721. return true;
  722. }
  723. /**
  724. * @inheritdoc
  725. */
  726. public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
  727. /** @var Share[] $shares */
  728. $shares = [];
  729. if ($shareType === IShare::TYPE_USER) {
  730. //Get shares directly with this user
  731. $qb = $this->dbConn->getQueryBuilder();
  732. $qb->select('s.*',
  733. 'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
  734. 'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
  735. 'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
  736. )
  737. ->selectAlias('st.id', 'storage_string_id')
  738. ->from('share', 's')
  739. ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
  740. ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
  741. // Order by id
  742. $qb->orderBy('s.id');
  743. // Set limit and offset
  744. if ($limit !== -1) {
  745. $qb->setMaxResults($limit);
  746. }
  747. $qb->setFirstResult($offset);
  748. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)))
  749. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
  750. ->andWhere($qb->expr()->orX(
  751. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  752. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  753. ));
  754. // Filter by node if provided
  755. if ($node !== null) {
  756. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  757. }
  758. $cursor = $qb->execute();
  759. while ($data = $cursor->fetch()) {
  760. if ($this->isAccessibleResult($data)) {
  761. $shares[] = $this->createShare($data);
  762. }
  763. }
  764. $cursor->closeCursor();
  765. } elseif ($shareType === IShare::TYPE_GROUP) {
  766. $user = $this->userManager->get($userId);
  767. $allGroups = ($user instanceof IUser) ? $this->groupManager->getUserGroupIds($user) : [];
  768. /** @var Share[] $shares2 */
  769. $shares2 = [];
  770. $start = 0;
  771. while (true) {
  772. $groups = array_slice($allGroups, $start, 100);
  773. $start += 100;
  774. if ($groups === []) {
  775. break;
  776. }
  777. $qb = $this->dbConn->getQueryBuilder();
  778. $qb->select('s.*',
  779. 'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
  780. 'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
  781. 'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
  782. )
  783. ->selectAlias('st.id', 'storage_string_id')
  784. ->from('share', 's')
  785. ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
  786. ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
  787. ->orderBy('s.id')
  788. ->setFirstResult(0);
  789. if ($limit !== -1) {
  790. $qb->setMaxResults($limit - count($shares));
  791. }
  792. // Filter by node if provided
  793. if ($node !== null) {
  794. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  795. }
  796. $groups = array_filter($groups);
  797. $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  798. ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
  799. $groups,
  800. IQueryBuilder::PARAM_STR_ARRAY
  801. )))
  802. ->andWhere($qb->expr()->orX(
  803. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  804. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  805. ));
  806. $cursor = $qb->execute();
  807. while ($data = $cursor->fetch()) {
  808. if ($offset > 0) {
  809. $offset--;
  810. continue;
  811. }
  812. if ($this->isAccessibleResult($data)) {
  813. $shares2[] = $this->createShare($data);
  814. }
  815. }
  816. $cursor->closeCursor();
  817. }
  818. /*
  819. * Resolve all group shares to user specific shares
  820. */
  821. $shares = $this->resolveGroupShares($shares2, $userId);
  822. } else {
  823. throw new BackendError('Invalid backend');
  824. }
  825. return $shares;
  826. }
  827. /**
  828. * Get a share by token
  829. *
  830. * @param string $token
  831. * @return \OCP\Share\IShare
  832. * @throws ShareNotFound
  833. */
  834. public function getShareByToken($token) {
  835. $qb = $this->dbConn->getQueryBuilder();
  836. $cursor = $qb->select('*')
  837. ->from('share')
  838. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK)))
  839. ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  840. ->andWhere($qb->expr()->orX(
  841. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  842. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  843. ))
  844. ->execute();
  845. $data = $cursor->fetch();
  846. if ($data === false) {
  847. throw new ShareNotFound();
  848. }
  849. try {
  850. $share = $this->createShare($data);
  851. } catch (InvalidShare $e) {
  852. throw new ShareNotFound();
  853. }
  854. return $share;
  855. }
  856. /**
  857. * Create a share object from an database row
  858. *
  859. * @param mixed[] $data
  860. * @return \OCP\Share\IShare
  861. * @throws InvalidShare
  862. */
  863. private function createShare($data) {
  864. $share = new Share($this->rootFolder, $this->userManager);
  865. $share->setId((int)$data['id'])
  866. ->setShareType((int)$data['share_type'])
  867. ->setPermissions((int)$data['permissions'])
  868. ->setTarget($data['file_target'])
  869. ->setNote($data['note'])
  870. ->setMailSend((bool)$data['mail_send'])
  871. ->setStatus((int)$data['accepted'])
  872. ->setLabel($data['label']);
  873. $shareTime = new \DateTime();
  874. $shareTime->setTimestamp((int)$data['stime']);
  875. $share->setShareTime($shareTime);
  876. if ($share->getShareType() === IShare::TYPE_USER) {
  877. $share->setSharedWith($data['share_with']);
  878. $user = $this->userManager->get($data['share_with']);
  879. if ($user !== null) {
  880. $share->setSharedWithDisplayName($user->getDisplayName());
  881. }
  882. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  883. $share->setSharedWith($data['share_with']);
  884. } elseif ($share->getShareType() === IShare::TYPE_LINK) {
  885. $share->setPassword($data['password']);
  886. $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
  887. $share->setToken($data['token']);
  888. }
  889. $share->setSharedBy($data['uid_initiator']);
  890. $share->setShareOwner($data['uid_owner']);
  891. $share->setNodeId((int)$data['file_source']);
  892. $share->setNodeType($data['item_type']);
  893. if ($data['expiration'] !== null) {
  894. $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
  895. $share->setExpirationDate($expiration);
  896. }
  897. if (isset($data['f_permissions'])) {
  898. $entryData = $data;
  899. $entryData['permissions'] = $entryData['f_permissions'];
  900. $entryData['parent'] = $entryData['f_parent'];
  901. $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
  902. \OC::$server->getMimeTypeLoader()));
  903. }
  904. $share->setProviderId($this->identifier());
  905. $share->setHideDownload((int)$data['hide_download'] === 1);
  906. return $share;
  907. }
  908. /**
  909. * @param Share[] $shares
  910. * @param $userId
  911. * @return Share[] The updates shares if no update is found for a share return the original
  912. */
  913. private function resolveGroupShares($shares, $userId) {
  914. $result = [];
  915. $start = 0;
  916. while (true) {
  917. /** @var Share[] $shareSlice */
  918. $shareSlice = array_slice($shares, $start, 100);
  919. $start += 100;
  920. if ($shareSlice === []) {
  921. break;
  922. }
  923. /** @var int[] $ids */
  924. $ids = [];
  925. /** @var Share[] $shareMap */
  926. $shareMap = [];
  927. foreach ($shareSlice as $share) {
  928. $ids[] = (int)$share->getId();
  929. $shareMap[$share->getId()] = $share;
  930. }
  931. $qb = $this->dbConn->getQueryBuilder();
  932. $query = $qb->select('*')
  933. ->from('share')
  934. ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
  935. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
  936. ->andWhere($qb->expr()->orX(
  937. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  938. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  939. ));
  940. $stmt = $query->execute();
  941. while ($data = $stmt->fetch()) {
  942. $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
  943. $shareMap[$data['parent']]->setStatus((int)$data['accepted']);
  944. $shareMap[$data['parent']]->setTarget($data['file_target']);
  945. $shareMap[$data['parent']]->setParent($data['parent']);
  946. }
  947. $stmt->closeCursor();
  948. foreach ($shareMap as $share) {
  949. $result[] = $share;
  950. }
  951. }
  952. return $result;
  953. }
  954. /**
  955. * A user is deleted from the system
  956. * So clean up the relevant shares.
  957. *
  958. * @param string $uid
  959. * @param int $shareType
  960. */
  961. public function userDeleted($uid, $shareType) {
  962. $qb = $this->dbConn->getQueryBuilder();
  963. $qb->delete('share');
  964. if ($shareType === IShare::TYPE_USER) {
  965. /*
  966. * Delete all user shares that are owned by this user
  967. * or that are received by this user
  968. */
  969. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)));
  970. $qb->andWhere(
  971. $qb->expr()->orX(
  972. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
  973. $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
  974. )
  975. );
  976. } elseif ($shareType === IShare::TYPE_GROUP) {
  977. /*
  978. * Delete all group shares that are owned by this user
  979. * Or special user group shares that are received by this user
  980. */
  981. $qb->where(
  982. $qb->expr()->andX(
  983. $qb->expr()->orX(
  984. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)),
  985. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP))
  986. ),
  987. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
  988. )
  989. );
  990. $qb->orWhere(
  991. $qb->expr()->andX(
  992. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)),
  993. $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
  994. )
  995. );
  996. } elseif ($shareType === IShare::TYPE_LINK) {
  997. /*
  998. * Delete all link shares owned by this user.
  999. * And all link shares initiated by this user (until #22327 is in)
  1000. */
  1001. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK)));
  1002. $qb->andWhere(
  1003. $qb->expr()->orX(
  1004. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
  1005. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
  1006. )
  1007. );
  1008. } else {
  1009. \OC::$server->getLogger()->logException(new \InvalidArgumentException('Default share provider tried to delete all shares for type: ' . $shareType));
  1010. return;
  1011. }
  1012. $qb->execute();
  1013. }
  1014. /**
  1015. * Delete all shares received by this group. As well as any custom group
  1016. * shares for group members.
  1017. *
  1018. * @param string $gid
  1019. */
  1020. public function groupDeleted($gid) {
  1021. /*
  1022. * First delete all custom group shares for group members
  1023. */
  1024. $qb = $this->dbConn->getQueryBuilder();
  1025. $qb->select('id')
  1026. ->from('share')
  1027. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  1028. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
  1029. $cursor = $qb->execute();
  1030. $ids = [];
  1031. while ($row = $cursor->fetch()) {
  1032. $ids[] = (int)$row['id'];
  1033. }
  1034. $cursor->closeCursor();
  1035. if (!empty($ids)) {
  1036. $chunks = array_chunk($ids, 100);
  1037. foreach ($chunks as $chunk) {
  1038. $qb->delete('share')
  1039. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  1040. ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
  1041. $qb->execute();
  1042. }
  1043. }
  1044. /*
  1045. * Now delete all the group shares
  1046. */
  1047. $qb = $this->dbConn->getQueryBuilder();
  1048. $qb->delete('share')
  1049. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  1050. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
  1051. $qb->execute();
  1052. }
  1053. /**
  1054. * Delete custom group shares to this group for this user
  1055. *
  1056. * @param string $uid
  1057. * @param string $gid
  1058. */
  1059. public function userDeletedFromGroup($uid, $gid) {
  1060. /*
  1061. * Get all group shares
  1062. */
  1063. $qb = $this->dbConn->getQueryBuilder();
  1064. $qb->select('id')
  1065. ->from('share')
  1066. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  1067. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
  1068. $cursor = $qb->execute();
  1069. $ids = [];
  1070. while ($row = $cursor->fetch()) {
  1071. $ids[] = (int)$row['id'];
  1072. }
  1073. $cursor->closeCursor();
  1074. if (!empty($ids)) {
  1075. $chunks = array_chunk($ids, 100);
  1076. foreach ($chunks as $chunk) {
  1077. /*
  1078. * Delete all special shares wit this users for the found group shares
  1079. */
  1080. $qb->delete('share')
  1081. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  1082. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
  1083. ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
  1084. $qb->execute();
  1085. }
  1086. }
  1087. }
  1088. /**
  1089. * @inheritdoc
  1090. */
  1091. public function getAccessList($nodes, $currentAccess) {
  1092. $ids = [];
  1093. foreach ($nodes as $node) {
  1094. $ids[] = $node->getId();
  1095. }
  1096. $qb = $this->dbConn->getQueryBuilder();
  1097. $or = $qb->expr()->orX(
  1098. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)),
  1099. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)),
  1100. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK))
  1101. );
  1102. if ($currentAccess) {
  1103. $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)));
  1104. }
  1105. $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
  1106. ->from('share')
  1107. ->where(
  1108. $or
  1109. )
  1110. ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
  1111. ->andWhere($qb->expr()->orX(
  1112. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  1113. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  1114. ));
  1115. $cursor = $qb->execute();
  1116. $users = [];
  1117. $link = false;
  1118. while ($row = $cursor->fetch()) {
  1119. $type = (int)$row['share_type'];
  1120. if ($type === IShare::TYPE_USER) {
  1121. $uid = $row['share_with'];
  1122. $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
  1123. $users[$uid][$row['id']] = $row;
  1124. } elseif ($type === IShare::TYPE_GROUP) {
  1125. $gid = $row['share_with'];
  1126. $group = $this->groupManager->get($gid);
  1127. if ($group === null) {
  1128. continue;
  1129. }
  1130. $userList = $group->getUsers();
  1131. foreach ($userList as $user) {
  1132. $uid = $user->getUID();
  1133. $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
  1134. $users[$uid][$row['id']] = $row;
  1135. }
  1136. } elseif ($type === IShare::TYPE_LINK) {
  1137. $link = true;
  1138. } elseif ($type === IShare::TYPE_USERGROUP && $currentAccess === true) {
  1139. $uid = $row['share_with'];
  1140. $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
  1141. $users[$uid][$row['id']] = $row;
  1142. }
  1143. }
  1144. $cursor->closeCursor();
  1145. if ($currentAccess === true) {
  1146. $users = array_map([$this, 'filterSharesOfUser'], $users);
  1147. $users = array_filter($users);
  1148. } else {
  1149. $users = array_keys($users);
  1150. }
  1151. return ['users' => $users, 'public' => $link];
  1152. }
  1153. /**
  1154. * For each user the path with the fewest slashes is returned
  1155. * @param array $shares
  1156. * @return array
  1157. */
  1158. protected function filterSharesOfUser(array $shares) {
  1159. // Group shares when the user has a share exception
  1160. foreach ($shares as $id => $share) {
  1161. $type = (int) $share['share_type'];
  1162. $permissions = (int) $share['permissions'];
  1163. if ($type === IShare::TYPE_USERGROUP) {
  1164. unset($shares[$share['parent']]);
  1165. if ($permissions === 0) {
  1166. unset($shares[$id]);
  1167. }
  1168. }
  1169. }
  1170. $best = [];
  1171. $bestDepth = 0;
  1172. foreach ($shares as $id => $share) {
  1173. $depth = substr_count($share['file_target'], '/');
  1174. if (empty($best) || $depth < $bestDepth) {
  1175. $bestDepth = $depth;
  1176. $best = [
  1177. 'node_id' => $share['file_source'],
  1178. 'node_path' => $share['file_target'],
  1179. ];
  1180. }
  1181. }
  1182. return $best;
  1183. }
  1184. /**
  1185. * propagate notes to the recipients
  1186. *
  1187. * @param IShare $share
  1188. * @throws \OCP\Files\NotFoundException
  1189. */
  1190. private function propagateNote(IShare $share) {
  1191. if ($share->getShareType() === IShare::TYPE_USER) {
  1192. $user = $this->userManager->get($share->getSharedWith());
  1193. $this->sendNote([$user], $share);
  1194. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  1195. $group = $this->groupManager->get($share->getSharedWith());
  1196. $groupMembers = $group->getUsers();
  1197. $this->sendNote($groupMembers, $share);
  1198. }
  1199. }
  1200. /**
  1201. * send note by mail
  1202. *
  1203. * @param array $recipients
  1204. * @param IShare $share
  1205. * @throws \OCP\Files\NotFoundException
  1206. */
  1207. private function sendNote(array $recipients, IShare $share) {
  1208. $toListByLanguage = [];
  1209. foreach ($recipients as $recipient) {
  1210. /** @var IUser $recipient */
  1211. $email = $recipient->getEMailAddress();
  1212. if ($email) {
  1213. $language = $this->l10nFactory->getUserLanguage($recipient);
  1214. if (!isset($toListByLanguage[$language])) {
  1215. $toListByLanguage[$language] = [];
  1216. }
  1217. $toListByLanguage[$language][$email] = $recipient->getDisplayName();
  1218. }
  1219. }
  1220. if (empty($toListByLanguage)) {
  1221. return;
  1222. }
  1223. foreach ($toListByLanguage as $l10n => $toList) {
  1224. $filename = $share->getNode()->getName();
  1225. $initiator = $share->getSharedBy();
  1226. $note = $share->getNote();
  1227. $l = $this->l10nFactory->get('lib', $l10n);
  1228. $initiatorUser = $this->userManager->get($initiator);
  1229. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  1230. $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
  1231. $plainHeading = $l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
  1232. $htmlHeading = $l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
  1233. $message = $this->mailer->createMessage();
  1234. $emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
  1235. $emailTemplate->setSubject($l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
  1236. $emailTemplate->addHeader();
  1237. $emailTemplate->addHeading($htmlHeading, $plainHeading);
  1238. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  1239. $link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
  1240. $emailTemplate->addBodyButton(
  1241. $l->t('Open »%s«', [$filename]),
  1242. $link
  1243. );
  1244. // The "From" contains the sharers name
  1245. $instanceName = $this->defaults->getName();
  1246. $senderName = $l->t(
  1247. '%1$s via %2$s',
  1248. [
  1249. $initiatorDisplayName,
  1250. $instanceName
  1251. ]
  1252. );
  1253. $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
  1254. if ($initiatorEmailAddress !== null) {
  1255. $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
  1256. $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
  1257. } else {
  1258. $emailTemplate->addFooter();
  1259. }
  1260. if (count($toList) === 1) {
  1261. $message->setTo($toList);
  1262. } else {
  1263. $message->setTo([]);
  1264. $message->setBcc($toList);
  1265. }
  1266. $message->useTemplate($emailTemplate);
  1267. $this->mailer->send($message);
  1268. }
  1269. }
  1270. public function getAllShares(): iterable {
  1271. $qb = $this->dbConn->getQueryBuilder();
  1272. $qb->select('*')
  1273. ->from('share')
  1274. ->where(
  1275. $qb->expr()->orX(
  1276. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_USER)),
  1277. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_GROUP)),
  1278. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_LINK))
  1279. )
  1280. );
  1281. $cursor = $qb->execute();
  1282. while ($data = $cursor->fetch()) {
  1283. try {
  1284. $share = $this->createShare($data);
  1285. } catch (InvalidShare $e) {
  1286. continue;
  1287. }
  1288. yield $share;
  1289. }
  1290. $cursor->closeCursor();
  1291. }
  1292. }