DefaultShareProvider.php 50 KB

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