DefaultShareProvider.php 49 KB

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