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

DefaultShareProvider.php 50KB

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