DefaultShareProvider.php 50 KB

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