DefaultShareProvider.php 50 KB

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