1
0

DefaultShareProvider.php 50 KB

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