DefaultShareProvider.php 54 KB

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