1
0

DefaultShareProvider.php 55 KB

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