1
0

DefaultShareProvider.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  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. $a = $qb->getSQL();
  589. $cursor = $qb->executeQuery();
  590. while ($data = $cursor->fetch()) {
  591. $shares[$data['fileid']][] = $this->createShare($data);
  592. }
  593. $cursor->closeCursor();
  594. }
  595. return $shares;
  596. }
  597. /**
  598. * @inheritdoc
  599. */
  600. public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
  601. $qb = $this->dbConn->getQueryBuilder();
  602. $qb->select('*')
  603. ->from('share')
  604. ->andWhere($qb->expr()->orX(
  605. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  606. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  607. ));
  608. $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
  609. /**
  610. * Reshares for this user are shares where they are the owner.
  611. */
  612. if ($reshares === false) {
  613. $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
  614. } else {
  615. if ($node === null) {
  616. $qb->andWhere(
  617. $qb->expr()->orX(
  618. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  619. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  620. )
  621. );
  622. }
  623. }
  624. if ($node !== null) {
  625. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  626. }
  627. if ($limit !== -1) {
  628. $qb->setMaxResults($limit);
  629. }
  630. $qb->setFirstResult($offset);
  631. $qb->orderBy('id');
  632. $cursor = $qb->execute();
  633. $shares = [];
  634. while ($data = $cursor->fetch()) {
  635. $shares[] = $this->createShare($data);
  636. }
  637. $cursor->closeCursor();
  638. return $shares;
  639. }
  640. /**
  641. * @inheritdoc
  642. */
  643. public function getShareById($id, $recipientId = null) {
  644. $qb = $this->dbConn->getQueryBuilder();
  645. $qb->select('*')
  646. ->from('share')
  647. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  648. ->andWhere(
  649. $qb->expr()->in(
  650. 'share_type',
  651. $qb->createNamedParameter([
  652. IShare::TYPE_USER,
  653. IShare::TYPE_GROUP,
  654. IShare::TYPE_LINK,
  655. ], IQueryBuilder::PARAM_INT_ARRAY)
  656. )
  657. )
  658. ->andWhere($qb->expr()->orX(
  659. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  660. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  661. ));
  662. $cursor = $qb->execute();
  663. $data = $cursor->fetch();
  664. $cursor->closeCursor();
  665. if ($data === false) {
  666. throw new ShareNotFound();
  667. }
  668. try {
  669. $share = $this->createShare($data);
  670. } catch (InvalidShare $e) {
  671. throw new ShareNotFound();
  672. }
  673. // If the recipient is set for a group share resolve to that user
  674. if ($recipientId !== null && $share->getShareType() === IShare::TYPE_GROUP) {
  675. $share = $this->resolveGroupShares([(int) $share->getId() => $share], $recipientId)[0];
  676. }
  677. return $share;
  678. }
  679. /**
  680. * Get shares for a given path
  681. *
  682. * @param \OCP\Files\Node $path
  683. * @return \OCP\Share\IShare[]
  684. */
  685. public function getSharesByPath(Node $path) {
  686. $qb = $this->dbConn->getQueryBuilder();
  687. $cursor = $qb->select('*')
  688. ->from('share')
  689. ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
  690. ->andWhere(
  691. $qb->expr()->orX(
  692. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)),
  693. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP))
  694. )
  695. )
  696. ->andWhere($qb->expr()->orX(
  697. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  698. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  699. ))
  700. ->execute();
  701. $shares = [];
  702. while ($data = $cursor->fetch()) {
  703. $shares[] = $this->createShare($data);
  704. }
  705. $cursor->closeCursor();
  706. return $shares;
  707. }
  708. /**
  709. * Returns whether the given database result can be interpreted as
  710. * a share with accessible file (not trashed, not deleted)
  711. */
  712. private function isAccessibleResult($data) {
  713. // exclude shares leading to deleted file entries
  714. if ($data['fileid'] === null || $data['path'] === null) {
  715. return false;
  716. }
  717. // exclude shares leading to trashbin on home storages
  718. $pathSections = explode('/', $data['path'], 2);
  719. // FIXME: would not detect rare md5'd home storage case properly
  720. if ($pathSections[0] !== 'files'
  721. && (str_starts_with($data['storage_string_id'], 'home::') || str_starts_with($data['storage_string_id'], 'object::user'))) {
  722. return false;
  723. } elseif ($pathSections[0] === '__groupfolders'
  724. && str_starts_with($pathSections[1], 'trash/')
  725. ) {
  726. // exclude shares leading to trashbin on group folders storages
  727. return false;
  728. }
  729. return true;
  730. }
  731. /**
  732. * @inheritdoc
  733. */
  734. public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
  735. /** @var Share[] $shares */
  736. $shares = [];
  737. if ($shareType === IShare::TYPE_USER) {
  738. //Get shares directly with this user
  739. $qb = $this->dbConn->getQueryBuilder();
  740. $qb->select('s.*',
  741. 'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
  742. 'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
  743. 'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
  744. )
  745. ->selectAlias('st.id', 'storage_string_id')
  746. ->from('share', 's')
  747. ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
  748. ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
  749. // Order by id
  750. $qb->orderBy('s.id');
  751. // Set limit and offset
  752. if ($limit !== -1) {
  753. $qb->setMaxResults($limit);
  754. }
  755. $qb->setFirstResult($offset);
  756. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)))
  757. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
  758. ->andWhere($qb->expr()->orX(
  759. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  760. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  761. ));
  762. // Filter by node if provided
  763. if ($node !== null) {
  764. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  765. }
  766. $cursor = $qb->execute();
  767. while ($data = $cursor->fetch()) {
  768. if ($data['fileid'] && $data['path'] === null) {
  769. $data['path'] = (string) $data['path'];
  770. $data['name'] = (string) $data['name'];
  771. $data['checksum'] = (string) $data['checksum'];
  772. }
  773. if ($this->isAccessibleResult($data)) {
  774. $shares[] = $this->createShare($data);
  775. }
  776. }
  777. $cursor->closeCursor();
  778. } elseif ($shareType === IShare::TYPE_GROUP) {
  779. $user = new LazyUser($userId, $this->userManager);
  780. $allGroups = $this->groupManager->getUserGroupIds($user);
  781. /** @var Share[] $shares2 */
  782. $shares2 = [];
  783. $start = 0;
  784. while (true) {
  785. $groups = array_slice($allGroups, $start, 1000);
  786. $start += 1000;
  787. if ($groups === []) {
  788. break;
  789. }
  790. $qb = $this->dbConn->getQueryBuilder();
  791. $qb->select('s.*',
  792. 'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
  793. 'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
  794. 'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
  795. )
  796. ->selectAlias('st.id', 'storage_string_id')
  797. ->from('share', 's')
  798. ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
  799. ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
  800. ->orderBy('s.id')
  801. ->setFirstResult(0);
  802. if ($limit !== -1) {
  803. $qb->setMaxResults($limit - count($shares));
  804. }
  805. // Filter by node if provided
  806. if ($node !== null) {
  807. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  808. }
  809. $groups = array_filter($groups);
  810. $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  811. ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
  812. $groups,
  813. IQueryBuilder::PARAM_STR_ARRAY
  814. )))
  815. ->andWhere($qb->expr()->orX(
  816. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  817. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  818. ));
  819. $cursor = $qb->execute();
  820. while ($data = $cursor->fetch()) {
  821. if ($offset > 0) {
  822. $offset--;
  823. continue;
  824. }
  825. if ($this->isAccessibleResult($data)) {
  826. $share = $this->createShare($data);
  827. $shares2[$share->getId()] = $share;
  828. }
  829. }
  830. $cursor->closeCursor();
  831. }
  832. /*
  833. * Resolve all group shares to user specific shares
  834. */
  835. $shares = $this->resolveGroupShares($shares2, $userId);
  836. } else {
  837. throw new BackendError('Invalid backend');
  838. }
  839. return $shares;
  840. }
  841. /**
  842. * Get a share by token
  843. *
  844. * @param string $token
  845. * @return \OCP\Share\IShare
  846. * @throws ShareNotFound
  847. */
  848. public function getShareByToken($token) {
  849. $qb = $this->dbConn->getQueryBuilder();
  850. $cursor = $qb->select('*')
  851. ->from('share')
  852. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK)))
  853. ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  854. ->andWhere($qb->expr()->orX(
  855. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  856. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  857. ))
  858. ->executeQuery();
  859. $data = $cursor->fetch();
  860. if ($data === false) {
  861. throw new ShareNotFound();
  862. }
  863. try {
  864. $share = $this->createShare($data);
  865. } catch (InvalidShare $e) {
  866. throw new ShareNotFound();
  867. }
  868. return $share;
  869. }
  870. /**
  871. * Create a share object from an database row
  872. *
  873. * @param mixed[] $data
  874. * @return \OCP\Share\IShare
  875. * @throws InvalidShare
  876. */
  877. private function createShare($data) {
  878. $share = new Share($this->rootFolder, $this->userManager);
  879. $share->setId((int)$data['id'])
  880. ->setShareType((int)$data['share_type'])
  881. ->setPermissions((int)$data['permissions'])
  882. ->setTarget($data['file_target'])
  883. ->setNote((string)$data['note'])
  884. ->setMailSend((bool)$data['mail_send'])
  885. ->setStatus((int)$data['accepted'])
  886. ->setLabel($data['label'] ?? '');
  887. $shareTime = new \DateTime();
  888. $shareTime->setTimestamp((int)$data['stime']);
  889. $share->setShareTime($shareTime);
  890. if ($share->getShareType() === IShare::TYPE_USER) {
  891. $share->setSharedWith($data['share_with']);
  892. $displayName = $this->userManager->getDisplayName($data['share_with']);
  893. if ($displayName !== null) {
  894. $share->setSharedWithDisplayName($displayName);
  895. }
  896. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  897. $share->setSharedWith($data['share_with']);
  898. $group = $this->groupManager->get($data['share_with']);
  899. if ($group !== null) {
  900. $share->setSharedWithDisplayName($group->getDisplayName());
  901. }
  902. } elseif ($share->getShareType() === IShare::TYPE_LINK) {
  903. $share->setPassword($data['password']);
  904. $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
  905. $share->setToken($data['token']);
  906. }
  907. $share = $this->updateShareAttributes($share, $data['attributes']);
  908. $share->setSharedBy($data['uid_initiator']);
  909. $share->setShareOwner($data['uid_owner']);
  910. $share->setNodeId((int)$data['file_source']);
  911. $share->setNodeType($data['item_type']);
  912. if ($data['expiration'] !== null) {
  913. $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
  914. $share->setExpirationDate($expiration);
  915. }
  916. if (isset($data['f_permissions'])) {
  917. $entryData = $data;
  918. $entryData['permissions'] = $entryData['f_permissions'];
  919. $entryData['parent'] = $entryData['f_parent'];
  920. $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
  921. \OC::$server->getMimeTypeLoader()));
  922. }
  923. $share->setProviderId($this->identifier());
  924. $share->setHideDownload((int)$data['hide_download'] === 1);
  925. return $share;
  926. }
  927. /**
  928. * Update the data from group shares with any per-user modifications
  929. *
  930. * @param array<int, Share> $shareMap shares indexed by share id
  931. * @param $userId
  932. * @return Share[] The updates shares if no update is found for a share return the original
  933. */
  934. private function resolveGroupShares($shareMap, $userId) {
  935. $qb = $this->dbConn->getQueryBuilder();
  936. $query = $qb->select('*')
  937. ->from('share')
  938. ->where($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
  939. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  940. ->andWhere($qb->expr()->in('item_type', [$qb->createNamedParameter('file'), $qb->createNamedParameter('folder')]));
  941. // this is called with either all group shares or one group share.
  942. // for all shares it's easier to just only search by share_with,
  943. // for a single share it's efficient to filter by parent
  944. if (count($shareMap) === 1) {
  945. $share = reset($shareMap);
  946. $query->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
  947. }
  948. $stmt = $query->execute();
  949. while ($data = $stmt->fetch()) {
  950. if (array_key_exists($data['parent'], $shareMap)) {
  951. $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
  952. $shareMap[$data['parent']]->setStatus((int)$data['accepted']);
  953. $shareMap[$data['parent']]->setTarget($data['file_target']);
  954. $shareMap[$data['parent']]->setParent($data['parent']);
  955. }
  956. }
  957. return array_values($shareMap);
  958. }
  959. /**
  960. * A user is deleted from the system
  961. * So clean up the relevant shares.
  962. *
  963. * @param string $uid
  964. * @param int $shareType
  965. */
  966. public function userDeleted($uid, $shareType) {
  967. $qb = $this->dbConn->getQueryBuilder();
  968. $qb->delete('share');
  969. if ($shareType === IShare::TYPE_USER) {
  970. /*
  971. * Delete all user shares that are owned by this user
  972. * or that are received by this user
  973. */
  974. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)));
  975. $qb->andWhere(
  976. $qb->expr()->orX(
  977. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
  978. $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
  979. )
  980. );
  981. } elseif ($shareType === IShare::TYPE_GROUP) {
  982. /*
  983. * Delete all group shares that are owned by this user
  984. * Or special user group shares that are received by this user
  985. */
  986. $qb->where(
  987. $qb->expr()->andX(
  988. $qb->expr()->orX(
  989. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)),
  990. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP))
  991. ),
  992. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
  993. )
  994. );
  995. $qb->orWhere(
  996. $qb->expr()->andX(
  997. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)),
  998. $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
  999. )
  1000. );
  1001. } elseif ($shareType === IShare::TYPE_LINK) {
  1002. /*
  1003. * Delete all link shares owned by this user.
  1004. * And all link shares initiated by this user (until #22327 is in)
  1005. */
  1006. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK)));
  1007. $qb->andWhere(
  1008. $qb->expr()->orX(
  1009. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
  1010. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
  1011. )
  1012. );
  1013. } else {
  1014. $e = new \InvalidArgumentException('Default share provider tried to delete all shares for type: ' . $shareType);
  1015. $this->logger->error($e->getMessage(), ['exception' => $e]);
  1016. return;
  1017. }
  1018. $qb->execute();
  1019. }
  1020. /**
  1021. * Delete all shares received by this group. As well as any custom group
  1022. * shares for group members.
  1023. *
  1024. * @param string $gid
  1025. */
  1026. public function groupDeleted($gid) {
  1027. /*
  1028. * First delete all custom group shares for group members
  1029. */
  1030. $qb = $this->dbConn->getQueryBuilder();
  1031. $qb->select('id')
  1032. ->from('share')
  1033. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  1034. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
  1035. $cursor = $qb->execute();
  1036. $ids = [];
  1037. while ($row = $cursor->fetch()) {
  1038. $ids[] = (int)$row['id'];
  1039. }
  1040. $cursor->closeCursor();
  1041. if (!empty($ids)) {
  1042. $chunks = array_chunk($ids, 100);
  1043. $qb = $this->dbConn->getQueryBuilder();
  1044. $qb->delete('share')
  1045. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  1046. ->andWhere($qb->expr()->in('parent', $qb->createParameter('parents')));
  1047. foreach ($chunks as $chunk) {
  1048. $qb->setParameter('parents', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
  1049. $qb->execute();
  1050. }
  1051. }
  1052. /*
  1053. * Now delete all the group shares
  1054. */
  1055. $qb = $this->dbConn->getQueryBuilder();
  1056. $qb->delete('share')
  1057. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  1058. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
  1059. $qb->execute();
  1060. }
  1061. /**
  1062. * Delete custom group shares to this group for this user
  1063. *
  1064. * @param string $uid
  1065. * @param string $gid
  1066. * @return void
  1067. */
  1068. public function userDeletedFromGroup($uid, $gid) {
  1069. /*
  1070. * Get all group shares
  1071. */
  1072. $qb = $this->dbConn->getQueryBuilder();
  1073. $qb->select('id')
  1074. ->from('share')
  1075. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  1076. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
  1077. $cursor = $qb->executeQuery();
  1078. $ids = [];
  1079. while ($row = $cursor->fetch()) {
  1080. $ids[] = (int)$row['id'];
  1081. }
  1082. $cursor->closeCursor();
  1083. if (!empty($ids)) {
  1084. $chunks = array_chunk($ids, 100);
  1085. /*
  1086. * Delete all special shares with this user for the found group shares
  1087. */
  1088. $qb = $this->dbConn->getQueryBuilder();
  1089. $qb->delete('share')
  1090. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  1091. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
  1092. ->andWhere($qb->expr()->in('parent', $qb->createParameter('parents')));
  1093. foreach ($chunks as $chunk) {
  1094. $qb->setParameter('parents', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
  1095. $qb->executeStatement();
  1096. }
  1097. }
  1098. if ($this->shareManager->shareWithGroupMembersOnly()) {
  1099. $user = $this->userManager->get($uid);
  1100. if ($user === null) {
  1101. return;
  1102. }
  1103. $userGroups = $this->groupManager->getUserGroupIds($user);
  1104. $userGroups = array_diff($userGroups, $this->shareManager->shareWithGroupMembersOnlyExcludeGroupsList());
  1105. // Delete user shares received by the user from users in the group.
  1106. $userReceivedShares = $this->shareManager->getSharedWith($uid, IShare::TYPE_USER, null, -1);
  1107. foreach ($userReceivedShares as $share) {
  1108. $owner = $this->userManager->get($share->getSharedBy());
  1109. if ($owner === null) {
  1110. continue;
  1111. }
  1112. $ownerGroups = $this->groupManager->getUserGroupIds($owner);
  1113. $mutualGroups = array_intersect($userGroups, $ownerGroups);
  1114. if (count($mutualGroups) === 0) {
  1115. $this->shareManager->deleteShare($share);
  1116. }
  1117. }
  1118. // Delete user shares from the user to users in the group.
  1119. $userEmittedShares = $this->shareManager->getSharesBy($uid, IShare::TYPE_USER, null, true, -1);
  1120. foreach ($userEmittedShares as $share) {
  1121. $recipient = $this->userManager->get($share->getSharedWith());
  1122. if ($recipient === null) {
  1123. continue;
  1124. }
  1125. $recipientGroups = $this->groupManager->getUserGroupIds($recipient);
  1126. $mutualGroups = array_intersect($userGroups, $recipientGroups);
  1127. if (count($mutualGroups) === 0) {
  1128. $this->shareManager->deleteShare($share);
  1129. }
  1130. }
  1131. }
  1132. }
  1133. /**
  1134. * @inheritdoc
  1135. */
  1136. public function getAccessList($nodes, $currentAccess) {
  1137. $ids = [];
  1138. foreach ($nodes as $node) {
  1139. $ids[] = $node->getId();
  1140. }
  1141. $qb = $this->dbConn->getQueryBuilder();
  1142. $or = $qb->expr()->orX(
  1143. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)),
  1144. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)),
  1145. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK))
  1146. );
  1147. if ($currentAccess) {
  1148. $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)));
  1149. }
  1150. $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
  1151. ->from('share')
  1152. ->where(
  1153. $or
  1154. )
  1155. ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
  1156. ->andWhere($qb->expr()->orX(
  1157. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  1158. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  1159. ));
  1160. $cursor = $qb->execute();
  1161. $users = [];
  1162. $link = false;
  1163. while ($row = $cursor->fetch()) {
  1164. $type = (int)$row['share_type'];
  1165. if ($type === IShare::TYPE_USER) {
  1166. $uid = $row['share_with'];
  1167. $users[$uid] = $users[$uid] ?? [];
  1168. $users[$uid][$row['id']] = $row;
  1169. } elseif ($type === IShare::TYPE_GROUP) {
  1170. $gid = $row['share_with'];
  1171. $group = $this->groupManager->get($gid);
  1172. if ($group === null) {
  1173. continue;
  1174. }
  1175. $userList = $group->getUsers();
  1176. foreach ($userList as $user) {
  1177. $uid = $user->getUID();
  1178. $users[$uid] = $users[$uid] ?? [];
  1179. $users[$uid][$row['id']] = $row;
  1180. }
  1181. } elseif ($type === IShare::TYPE_LINK) {
  1182. $link = true;
  1183. } elseif ($type === IShare::TYPE_USERGROUP && $currentAccess === true) {
  1184. $uid = $row['share_with'];
  1185. $users[$uid] = $users[$uid] ?? [];
  1186. $users[$uid][$row['id']] = $row;
  1187. }
  1188. }
  1189. $cursor->closeCursor();
  1190. if ($currentAccess === true) {
  1191. $users = array_map([$this, 'filterSharesOfUser'], $users);
  1192. $users = array_filter($users);
  1193. } else {
  1194. $users = array_keys($users);
  1195. }
  1196. return ['users' => $users, 'public' => $link];
  1197. }
  1198. /**
  1199. * For each user the path with the fewest slashes is returned
  1200. * @param array $shares
  1201. * @return array
  1202. */
  1203. protected function filterSharesOfUser(array $shares) {
  1204. // Group shares when the user has a share exception
  1205. foreach ($shares as $id => $share) {
  1206. $type = (int) $share['share_type'];
  1207. $permissions = (int) $share['permissions'];
  1208. if ($type === IShare::TYPE_USERGROUP) {
  1209. unset($shares[$share['parent']]);
  1210. if ($permissions === 0) {
  1211. unset($shares[$id]);
  1212. }
  1213. }
  1214. }
  1215. $best = [];
  1216. $bestDepth = 0;
  1217. foreach ($shares as $id => $share) {
  1218. $depth = substr_count(($share['file_target'] ?? ''), '/');
  1219. if (empty($best) || $depth < $bestDepth) {
  1220. $bestDepth = $depth;
  1221. $best = [
  1222. 'node_id' => $share['file_source'],
  1223. 'node_path' => $share['file_target'],
  1224. ];
  1225. }
  1226. }
  1227. return $best;
  1228. }
  1229. /**
  1230. * propagate notes to the recipients
  1231. *
  1232. * @param IShare $share
  1233. * @throws \OCP\Files\NotFoundException
  1234. */
  1235. private function propagateNote(IShare $share) {
  1236. if ($share->getShareType() === IShare::TYPE_USER) {
  1237. $user = $this->userManager->get($share->getSharedWith());
  1238. $this->sendNote([$user], $share);
  1239. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  1240. $group = $this->groupManager->get($share->getSharedWith());
  1241. $groupMembers = $group->getUsers();
  1242. $this->sendNote($groupMembers, $share);
  1243. }
  1244. }
  1245. public function sendMailNotification(IShare $share): bool {
  1246. try {
  1247. // Check user
  1248. $user = $this->userManager->get($share->getSharedWith());
  1249. if ($user === null) {
  1250. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
  1251. return false;
  1252. }
  1253. // Handle user shares
  1254. if ($share->getShareType() === IShare::TYPE_USER) {
  1255. // Check email address
  1256. $emailAddress = $user->getEMailAddress();
  1257. if ($emailAddress === null || $emailAddress === '') {
  1258. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
  1259. return false;
  1260. }
  1261. $userLang = $this->l10nFactory->getUserLanguage($user);
  1262. $l = $this->l10nFactory->get('lib', $userLang);
  1263. $this->sendUserShareMail(
  1264. $l,
  1265. $share->getNode()->getName(),
  1266. $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
  1267. $share->getSharedBy(),
  1268. $emailAddress,
  1269. $share->getExpirationDate(),
  1270. $share->getNote()
  1271. );
  1272. $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId() . '.', ['app' => 'share']);
  1273. return true;
  1274. }
  1275. } catch (\Exception $e) {
  1276. $this->logger->error('Share notification mail could not be sent.', ['exception' => $e]);
  1277. }
  1278. return false;
  1279. }
  1280. /**
  1281. * Send mail notifications for the user share type
  1282. *
  1283. * @param IL10N $l Language of the recipient
  1284. * @param string $filename file/folder name
  1285. * @param string $link link to the file/folder
  1286. * @param string $initiator user ID of share sender
  1287. * @param string $shareWith email address of share receiver
  1288. * @param \DateTime|null $expiration
  1289. * @param string $note
  1290. * @throws \Exception
  1291. */
  1292. protected function sendUserShareMail(
  1293. IL10N $l,
  1294. $filename,
  1295. $link,
  1296. $initiator,
  1297. $shareWith,
  1298. ?\DateTime $expiration = null,
  1299. $note = '') {
  1300. $initiatorUser = $this->userManager->get($initiator);
  1301. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  1302. $message = $this->mailer->createMessage();
  1303. $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
  1304. 'filename' => $filename,
  1305. 'link' => $link,
  1306. 'initiator' => $initiatorDisplayName,
  1307. 'expiration' => $expiration,
  1308. 'shareWith' => $shareWith,
  1309. ]);
  1310. $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
  1311. $emailTemplate->addHeader();
  1312. $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
  1313. $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
  1314. if ($note !== '') {
  1315. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  1316. }
  1317. $emailTemplate->addBodyText(
  1318. htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
  1319. $text
  1320. );
  1321. $emailTemplate->addBodyButton(
  1322. $l->t('Open »%s«', [$filename]),
  1323. $link
  1324. );
  1325. $message->setTo([$shareWith]);
  1326. // The "From" contains the sharers name
  1327. $instanceName = $this->defaults->getName();
  1328. $senderName = $l->t(
  1329. '%1$s via %2$s',
  1330. [
  1331. $initiatorDisplayName,
  1332. $instanceName,
  1333. ]
  1334. );
  1335. $message->setFrom([\OCP\Util::getDefaultEmailAddress('noreply') => $senderName]);
  1336. // The "Reply-To" is set to the sharer if an mail address is configured
  1337. // also the default footer contains a "Do not reply" which needs to be adjusted.
  1338. if ($initiatorUser) {
  1339. $initiatorEmail = $initiatorUser->getEMailAddress();
  1340. if ($initiatorEmail !== null) {
  1341. $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
  1342. $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
  1343. } else {
  1344. $emailTemplate->addFooter();
  1345. }
  1346. } else {
  1347. $emailTemplate->addFooter();
  1348. }
  1349. $message->useTemplate($emailTemplate);
  1350. $failedRecipients = $this->mailer->send($message);
  1351. if (!empty($failedRecipients)) {
  1352. $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
  1353. return;
  1354. }
  1355. }
  1356. /**
  1357. * send note by mail
  1358. *
  1359. * @param array $recipients
  1360. * @param IShare $share
  1361. * @throws \OCP\Files\NotFoundException
  1362. */
  1363. private function sendNote(array $recipients, IShare $share) {
  1364. $toListByLanguage = [];
  1365. foreach ($recipients as $recipient) {
  1366. /** @var IUser $recipient */
  1367. $email = $recipient->getEMailAddress();
  1368. if ($email) {
  1369. $language = $this->l10nFactory->getUserLanguage($recipient);
  1370. if (!isset($toListByLanguage[$language])) {
  1371. $toListByLanguage[$language] = [];
  1372. }
  1373. $toListByLanguage[$language][$email] = $recipient->getDisplayName();
  1374. }
  1375. }
  1376. if (empty($toListByLanguage)) {
  1377. return;
  1378. }
  1379. foreach ($toListByLanguage as $l10n => $toList) {
  1380. $filename = $share->getNode()->getName();
  1381. $initiator = $share->getSharedBy();
  1382. $note = $share->getNote();
  1383. $l = $this->l10nFactory->get('lib', $l10n);
  1384. $initiatorUser = $this->userManager->get($initiator);
  1385. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  1386. $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
  1387. $plainHeading = $l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
  1388. $htmlHeading = $l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
  1389. $message = $this->mailer->createMessage();
  1390. $emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
  1391. $emailTemplate->setSubject($l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
  1392. $emailTemplate->addHeader();
  1393. $emailTemplate->addHeading($htmlHeading, $plainHeading);
  1394. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  1395. $link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
  1396. $emailTemplate->addBodyButton(
  1397. $l->t('Open »%s«', [$filename]),
  1398. $link
  1399. );
  1400. // The "From" contains the sharers name
  1401. $instanceName = $this->defaults->getName();
  1402. $senderName = $l->t(
  1403. '%1$s via %2$s',
  1404. [
  1405. $initiatorDisplayName,
  1406. $instanceName
  1407. ]
  1408. );
  1409. $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
  1410. if ($initiatorEmailAddress !== null) {
  1411. $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
  1412. $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
  1413. } else {
  1414. $emailTemplate->addFooter();
  1415. }
  1416. if (count($toList) === 1) {
  1417. $message->setTo($toList);
  1418. } else {
  1419. $message->setTo([]);
  1420. $message->setBcc($toList);
  1421. }
  1422. $message->useTemplate($emailTemplate);
  1423. $this->mailer->send($message);
  1424. }
  1425. }
  1426. public function getAllShares(): iterable {
  1427. $qb = $this->dbConn->getQueryBuilder();
  1428. $qb->select('*')
  1429. ->from('share')
  1430. ->where(
  1431. $qb->expr()->orX(
  1432. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_USER)),
  1433. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_GROUP)),
  1434. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_LINK))
  1435. )
  1436. );
  1437. $cursor = $qb->execute();
  1438. while ($data = $cursor->fetch()) {
  1439. try {
  1440. $share = $this->createShare($data);
  1441. } catch (InvalidShare $e) {
  1442. continue;
  1443. }
  1444. yield $share;
  1445. }
  1446. $cursor->closeCursor();
  1447. }
  1448. /**
  1449. * Load from database format (JSON string) to IAttributes
  1450. *
  1451. * @return IShare the modified share
  1452. */
  1453. protected function updateShareAttributes(IShare $share, ?string $data): IShare {
  1454. if ($data !== null && $data !== '') {
  1455. $attributes = new ShareAttributes();
  1456. $compressedAttributes = \json_decode($data, true);
  1457. if ($compressedAttributes === false || $compressedAttributes === null) {
  1458. return $share;
  1459. }
  1460. foreach ($compressedAttributes as $compressedAttribute) {
  1461. $attributes->setAttribute(
  1462. $compressedAttribute[0],
  1463. $compressedAttribute[1],
  1464. $compressedAttribute[2]
  1465. );
  1466. }
  1467. $share->setAttributes($attributes);
  1468. }
  1469. return $share;
  1470. }
  1471. /**
  1472. * Format IAttributes to database format (JSON string)
  1473. */
  1474. protected function formatShareAttributes(?IAttributes $attributes): ?string {
  1475. if ($attributes === null || empty($attributes->toArray())) {
  1476. return null;
  1477. }
  1478. $compressedAttributes = [];
  1479. foreach ($attributes->toArray() as $attribute) {
  1480. $compressedAttributes[] = [
  1481. 0 => $attribute['scope'],
  1482. 1 => $attribute['key'],
  1483. 2 => $attribute['value']
  1484. ];
  1485. }
  1486. return \json_encode($compressedAttributes);
  1487. }
  1488. }