DefaultShareProvider.php 50 KB

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