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

DefaultShareProvider.php 47KB

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