DefaultShareProvider.php 50 KB

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