DefaultShareProvider.php 50 KB

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