DefaultShareProvider.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  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. )
  697. )
  698. ->andWhere($qb->expr()->orX(
  699. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  700. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  701. ))
  702. ->executeQuery();
  703. $shares = [];
  704. while ($data = $cursor->fetch()) {
  705. $shares[] = $this->createShare($data);
  706. }
  707. $cursor->closeCursor();
  708. return $shares;
  709. }
  710. /**
  711. * Returns whether the given database result can be interpreted as
  712. * a share with accessible file (not trashed, not deleted)
  713. */
  714. private function isAccessibleResult($data) {
  715. // exclude shares leading to deleted file entries
  716. if ($data['fileid'] === null || $data['path'] === null) {
  717. return false;
  718. }
  719. // exclude shares leading to trashbin on home storages
  720. $pathSections = explode('/', $data['path'], 2);
  721. // FIXME: would not detect rare md5'd home storage case properly
  722. if ($pathSections[0] !== 'files'
  723. && (str_starts_with($data['storage_string_id'], 'home::') || str_starts_with($data['storage_string_id'], 'object::user'))) {
  724. return false;
  725. } elseif ($pathSections[0] === '__groupfolders'
  726. && str_starts_with($pathSections[1], 'trash/')
  727. ) {
  728. // exclude shares leading to trashbin on group folders storages
  729. return false;
  730. }
  731. return true;
  732. }
  733. /**
  734. * @inheritdoc
  735. */
  736. public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
  737. /** @var Share[] $shares */
  738. $shares = [];
  739. if ($shareType === IShare::TYPE_USER) {
  740. //Get shares directly with this user
  741. $qb = $this->dbConn->getQueryBuilder();
  742. $qb->select('s.*',
  743. 'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
  744. 'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
  745. 'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
  746. )
  747. ->selectAlias('st.id', 'storage_string_id')
  748. ->from('share', 's')
  749. ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
  750. ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
  751. // Order by id
  752. $qb->orderBy('s.id');
  753. // Set limit and offset
  754. if ($limit !== -1) {
  755. $qb->setMaxResults($limit);
  756. }
  757. $qb->setFirstResult($offset);
  758. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)))
  759. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
  760. ->andWhere($qb->expr()->orX(
  761. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  762. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  763. ));
  764. // Filter by node if provided
  765. if ($node !== null) {
  766. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  767. }
  768. $cursor = $qb->executeQuery();
  769. while ($data = $cursor->fetch()) {
  770. if ($data['fileid'] && $data['path'] === null) {
  771. $data['path'] = (string)$data['path'];
  772. $data['name'] = (string)$data['name'];
  773. $data['checksum'] = (string)$data['checksum'];
  774. }
  775. if ($this->isAccessibleResult($data)) {
  776. $shares[] = $this->createShare($data);
  777. }
  778. }
  779. $cursor->closeCursor();
  780. } elseif ($shareType === IShare::TYPE_GROUP) {
  781. $user = new LazyUser($userId, $this->userManager);
  782. $allGroups = $this->groupManager->getUserGroupIds($user);
  783. /** @var Share[] $shares2 */
  784. $shares2 = [];
  785. $start = 0;
  786. while (true) {
  787. $groups = array_slice($allGroups, $start, 1000);
  788. $start += 1000;
  789. if ($groups === []) {
  790. break;
  791. }
  792. $qb = $this->dbConn->getQueryBuilder();
  793. $qb->select('s.*',
  794. 'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
  795. 'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
  796. 'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
  797. )
  798. ->selectAlias('st.id', 'storage_string_id')
  799. ->from('share', 's')
  800. ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
  801. ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
  802. ->orderBy('s.id')
  803. ->setFirstResult(0);
  804. if ($limit !== -1) {
  805. $qb->setMaxResults($limit - count($shares));
  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. $groups = array_filter($groups);
  812. $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  813. ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
  814. $groups,
  815. IQueryBuilder::PARAM_STR_ARRAY
  816. )))
  817. ->andWhere($qb->expr()->orX(
  818. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  819. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  820. ));
  821. $cursor = $qb->executeQuery();
  822. while ($data = $cursor->fetch()) {
  823. if ($offset > 0) {
  824. $offset--;
  825. continue;
  826. }
  827. if ($this->isAccessibleResult($data)) {
  828. $share = $this->createShare($data);
  829. $shares2[$share->getId()] = $share;
  830. }
  831. }
  832. $cursor->closeCursor();
  833. }
  834. /*
  835. * Resolve all group shares to user specific shares
  836. */
  837. $shares = $this->resolveGroupShares($shares2, $userId);
  838. } else {
  839. throw new BackendError('Invalid backend');
  840. }
  841. return $shares;
  842. }
  843. /**
  844. * Get a share by token
  845. *
  846. * @param string $token
  847. * @return \OCP\Share\IShare
  848. * @throws ShareNotFound
  849. */
  850. public function getShareByToken($token) {
  851. $qb = $this->dbConn->getQueryBuilder();
  852. $cursor = $qb->select('*')
  853. ->from('share')
  854. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK)))
  855. ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  856. ->andWhere($qb->expr()->orX(
  857. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  858. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  859. ))
  860. ->executeQuery();
  861. $data = $cursor->fetch();
  862. if ($data === false) {
  863. throw new ShareNotFound();
  864. }
  865. try {
  866. $share = $this->createShare($data);
  867. } catch (InvalidShare $e) {
  868. throw new ShareNotFound();
  869. }
  870. return $share;
  871. }
  872. /**
  873. * Create a share object from a database row
  874. *
  875. * @param mixed[] $data
  876. * @return \OCP\Share\IShare
  877. * @throws InvalidShare
  878. */
  879. private function createShare($data) {
  880. $share = new Share($this->rootFolder, $this->userManager);
  881. $share->setId((int)$data['id'])
  882. ->setShareType((int)$data['share_type'])
  883. ->setPermissions((int)$data['permissions'])
  884. ->setTarget($data['file_target'])
  885. ->setNote((string)$data['note'])
  886. ->setMailSend((bool)$data['mail_send'])
  887. ->setStatus((int)$data['accepted'])
  888. ->setLabel($data['label'] ?? '');
  889. $shareTime = new \DateTime();
  890. $shareTime->setTimestamp((int)$data['stime']);
  891. $share->setShareTime($shareTime);
  892. if ($share->getShareType() === IShare::TYPE_USER) {
  893. $share->setSharedWith($data['share_with']);
  894. $displayName = $this->userManager->getDisplayName($data['share_with']);
  895. if ($displayName !== null) {
  896. $share->setSharedWithDisplayName($displayName);
  897. }
  898. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  899. $share->setSharedWith($data['share_with']);
  900. $group = $this->groupManager->get($data['share_with']);
  901. if ($group !== null) {
  902. $share->setSharedWithDisplayName($group->getDisplayName());
  903. }
  904. } elseif ($share->getShareType() === IShare::TYPE_LINK) {
  905. $share->setPassword($data['password']);
  906. $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
  907. $share->setToken($data['token']);
  908. }
  909. $share = $this->updateShareAttributes($share, $data['attributes']);
  910. $share->setSharedBy($data['uid_initiator']);
  911. $share->setShareOwner($data['uid_owner']);
  912. $share->setNodeId((int)$data['file_source']);
  913. $share->setNodeType($data['item_type']);
  914. if ($data['expiration'] !== null) {
  915. $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
  916. $share->setExpirationDate($expiration);
  917. }
  918. if (isset($data['f_permissions'])) {
  919. $entryData = $data;
  920. $entryData['permissions'] = $entryData['f_permissions'];
  921. $entryData['parent'] = $entryData['f_parent'];
  922. $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
  923. \OC::$server->getMimeTypeLoader()));
  924. }
  925. $share->setProviderId($this->identifier());
  926. $share->setHideDownload((int)$data['hide_download'] === 1);
  927. $share->setReminderSent((bool)$data['reminder_sent']);
  928. return $share;
  929. }
  930. /**
  931. * Update the data from group shares with any per-user modifications
  932. *
  933. * @param array<int, Share> $shareMap shares indexed by share id
  934. * @param $userId
  935. * @return Share[] The updates shares if no update is found for a share return the original
  936. */
  937. private function resolveGroupShares($shareMap, $userId) {
  938. $qb = $this->dbConn->getQueryBuilder();
  939. $query = $qb->select('*')
  940. ->from('share')
  941. ->where($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
  942. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  943. ->andWhere($qb->expr()->in('item_type', [$qb->createNamedParameter('file'), $qb->createNamedParameter('folder')]));
  944. // this is called with either all group shares or one group share.
  945. // for all shares it's easier to just only search by share_with,
  946. // for a single share it's efficient to filter by parent
  947. if (count($shareMap) === 1) {
  948. $share = reset($shareMap);
  949. $query->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
  950. }
  951. $stmt = $query->executeQuery();
  952. while ($data = $stmt->fetch()) {
  953. if (array_key_exists($data['parent'], $shareMap)) {
  954. $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
  955. $shareMap[$data['parent']]->setStatus((int)$data['accepted']);
  956. $shareMap[$data['parent']]->setTarget($data['file_target']);
  957. $shareMap[$data['parent']]->setParent($data['parent']);
  958. }
  959. }
  960. return array_values($shareMap);
  961. }
  962. /**
  963. * A user is deleted from the system
  964. * So clean up the relevant shares.
  965. *
  966. * @param string $uid
  967. * @param int $shareType
  968. */
  969. public function userDeleted($uid, $shareType) {
  970. $qb = $this->dbConn->getQueryBuilder();
  971. $qb->delete('share');
  972. if ($shareType === IShare::TYPE_USER) {
  973. /*
  974. * Delete all user shares that are owned by this user
  975. * or that are received by this user
  976. */
  977. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)));
  978. $qb->andWhere(
  979. $qb->expr()->orX(
  980. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
  981. $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
  982. )
  983. );
  984. } elseif ($shareType === IShare::TYPE_GROUP) {
  985. /*
  986. * Delete all group shares that are owned by this user
  987. * Or special user group shares that are received by this user
  988. */
  989. $qb->where(
  990. $qb->expr()->andX(
  991. $qb->expr()->orX(
  992. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)),
  993. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP))
  994. ),
  995. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
  996. )
  997. );
  998. $qb->orWhere(
  999. $qb->expr()->andX(
  1000. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)),
  1001. $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
  1002. )
  1003. );
  1004. } elseif ($shareType === IShare::TYPE_LINK) {
  1005. /*
  1006. * Delete all link shares owned by this user.
  1007. * And all link shares initiated by this user (until #22327 is in)
  1008. */
  1009. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK)));
  1010. $qb->andWhere(
  1011. $qb->expr()->orX(
  1012. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
  1013. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
  1014. )
  1015. );
  1016. } else {
  1017. $e = new \InvalidArgumentException('Default share provider tried to delete all shares for type: ' . $shareType);
  1018. $this->logger->error($e->getMessage(), ['exception' => $e]);
  1019. return;
  1020. }
  1021. $qb->executeStatement();
  1022. }
  1023. /**
  1024. * Delete all shares received by this group. As well as any custom group
  1025. * shares for group members.
  1026. *
  1027. * @param string $gid
  1028. */
  1029. public function groupDeleted($gid) {
  1030. /*
  1031. * First delete all custom group shares for group members
  1032. */
  1033. $qb = $this->dbConn->getQueryBuilder();
  1034. $qb->select('id')
  1035. ->from('share')
  1036. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  1037. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
  1038. $cursor = $qb->executeQuery();
  1039. $ids = [];
  1040. while ($row = $cursor->fetch()) {
  1041. $ids[] = (int)$row['id'];
  1042. }
  1043. $cursor->closeCursor();
  1044. if (!empty($ids)) {
  1045. $chunks = array_chunk($ids, 100);
  1046. $qb = $this->dbConn->getQueryBuilder();
  1047. $qb->delete('share')
  1048. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  1049. ->andWhere($qb->expr()->in('parent', $qb->createParameter('parents')));
  1050. foreach ($chunks as $chunk) {
  1051. $qb->setParameter('parents', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
  1052. $qb->executeStatement();
  1053. }
  1054. }
  1055. /*
  1056. * Now delete all the group shares
  1057. */
  1058. $qb = $this->dbConn->getQueryBuilder();
  1059. $qb->delete('share')
  1060. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  1061. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
  1062. $qb->executeStatement();
  1063. }
  1064. /**
  1065. * Delete custom group shares to this group for this user
  1066. *
  1067. * @param string $uid
  1068. * @param string $gid
  1069. * @return void
  1070. */
  1071. public function userDeletedFromGroup($uid, $gid) {
  1072. /*
  1073. * Get all group shares
  1074. */
  1075. $qb = $this->dbConn->getQueryBuilder();
  1076. $qb->select('id')
  1077. ->from('share')
  1078. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)))
  1079. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
  1080. $cursor = $qb->executeQuery();
  1081. $ids = [];
  1082. while ($row = $cursor->fetch()) {
  1083. $ids[] = (int)$row['id'];
  1084. }
  1085. $cursor->closeCursor();
  1086. if (!empty($ids)) {
  1087. $chunks = array_chunk($ids, 100);
  1088. /*
  1089. * Delete all special shares with this user for the found group shares
  1090. */
  1091. $qb = $this->dbConn->getQueryBuilder();
  1092. $qb->delete('share')
  1093. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)))
  1094. ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
  1095. ->andWhere($qb->expr()->in('parent', $qb->createParameter('parents')));
  1096. foreach ($chunks as $chunk) {
  1097. $qb->setParameter('parents', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
  1098. $qb->executeStatement();
  1099. }
  1100. }
  1101. if ($this->shareManager->shareWithGroupMembersOnly()) {
  1102. $user = $this->userManager->get($uid);
  1103. if ($user === null) {
  1104. return;
  1105. }
  1106. $userGroups = $this->groupManager->getUserGroupIds($user);
  1107. $userGroups = array_diff($userGroups, $this->shareManager->shareWithGroupMembersOnlyExcludeGroupsList());
  1108. // Delete user shares received by the user from users in the group.
  1109. $userReceivedShares = $this->shareManager->getSharedWith($uid, IShare::TYPE_USER, null, -1);
  1110. foreach ($userReceivedShares as $share) {
  1111. $owner = $this->userManager->get($share->getSharedBy());
  1112. if ($owner === null) {
  1113. continue;
  1114. }
  1115. $ownerGroups = $this->groupManager->getUserGroupIds($owner);
  1116. $mutualGroups = array_intersect($userGroups, $ownerGroups);
  1117. if (count($mutualGroups) === 0) {
  1118. $this->shareManager->deleteShare($share);
  1119. }
  1120. }
  1121. // Delete user shares from the user to users in the group.
  1122. $userEmittedShares = $this->shareManager->getSharesBy($uid, IShare::TYPE_USER, null, true, -1);
  1123. foreach ($userEmittedShares as $share) {
  1124. $recipient = $this->userManager->get($share->getSharedWith());
  1125. if ($recipient === null) {
  1126. continue;
  1127. }
  1128. $recipientGroups = $this->groupManager->getUserGroupIds($recipient);
  1129. $mutualGroups = array_intersect($userGroups, $recipientGroups);
  1130. if (count($mutualGroups) === 0) {
  1131. $this->shareManager->deleteShare($share);
  1132. }
  1133. }
  1134. }
  1135. }
  1136. /**
  1137. * @inheritdoc
  1138. */
  1139. public function getAccessList($nodes, $currentAccess) {
  1140. $ids = [];
  1141. foreach ($nodes as $node) {
  1142. $ids[] = $node->getId();
  1143. }
  1144. $qb = $this->dbConn->getQueryBuilder();
  1145. $or = $qb->expr()->orX(
  1146. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USER)),
  1147. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_GROUP)),
  1148. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_LINK))
  1149. );
  1150. if ($currentAccess) {
  1151. $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_USERGROUP)));
  1152. }
  1153. $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
  1154. ->from('share')
  1155. ->where(
  1156. $or
  1157. )
  1158. ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
  1159. ->andWhere($qb->expr()->orX(
  1160. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  1161. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  1162. ));
  1163. $cursor = $qb->executeQuery();
  1164. $users = [];
  1165. $link = false;
  1166. while ($row = $cursor->fetch()) {
  1167. $type = (int)$row['share_type'];
  1168. if ($type === IShare::TYPE_USER) {
  1169. $uid = $row['share_with'];
  1170. $users[$uid] = $users[$uid] ?? [];
  1171. $users[$uid][$row['id']] = $row;
  1172. } elseif ($type === IShare::TYPE_GROUP) {
  1173. $gid = $row['share_with'];
  1174. $group = $this->groupManager->get($gid);
  1175. if ($group === null) {
  1176. continue;
  1177. }
  1178. $userList = $group->getUsers();
  1179. foreach ($userList as $user) {
  1180. $uid = $user->getUID();
  1181. $users[$uid] = $users[$uid] ?? [];
  1182. $users[$uid][$row['id']] = $row;
  1183. }
  1184. } elseif ($type === IShare::TYPE_LINK) {
  1185. $link = true;
  1186. } elseif ($type === IShare::TYPE_USERGROUP && $currentAccess === true) {
  1187. $uid = $row['share_with'];
  1188. $users[$uid] = $users[$uid] ?? [];
  1189. $users[$uid][$row['id']] = $row;
  1190. }
  1191. }
  1192. $cursor->closeCursor();
  1193. if ($currentAccess === true) {
  1194. $users = array_map([$this, 'filterSharesOfUser'], $users);
  1195. $users = array_filter($users);
  1196. } else {
  1197. $users = array_keys($users);
  1198. }
  1199. return ['users' => $users, 'public' => $link];
  1200. }
  1201. /**
  1202. * For each user the path with the fewest slashes is returned
  1203. * @param array $shares
  1204. * @return array
  1205. */
  1206. protected function filterSharesOfUser(array $shares) {
  1207. // Group shares when the user has a share exception
  1208. foreach ($shares as $id => $share) {
  1209. $type = (int)$share['share_type'];
  1210. $permissions = (int)$share['permissions'];
  1211. if ($type === IShare::TYPE_USERGROUP) {
  1212. unset($shares[$share['parent']]);
  1213. if ($permissions === 0) {
  1214. unset($shares[$id]);
  1215. }
  1216. }
  1217. }
  1218. $best = [];
  1219. $bestDepth = 0;
  1220. foreach ($shares as $id => $share) {
  1221. $depth = substr_count(($share['file_target'] ?? ''), '/');
  1222. if (empty($best) || $depth < $bestDepth) {
  1223. $bestDepth = $depth;
  1224. $best = [
  1225. 'node_id' => $share['file_source'],
  1226. 'node_path' => $share['file_target'],
  1227. ];
  1228. }
  1229. }
  1230. return $best;
  1231. }
  1232. /**
  1233. * propagate notes to the recipients
  1234. *
  1235. * @param IShare $share
  1236. * @throws \OCP\Files\NotFoundException
  1237. */
  1238. private function propagateNote(IShare $share) {
  1239. if ($share->getShareType() === IShare::TYPE_USER) {
  1240. $user = $this->userManager->get($share->getSharedWith());
  1241. $this->sendNote([$user], $share);
  1242. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  1243. $group = $this->groupManager->get($share->getSharedWith());
  1244. $groupMembers = $group->getUsers();
  1245. $this->sendNote($groupMembers, $share);
  1246. }
  1247. }
  1248. public function sendMailNotification(IShare $share): bool {
  1249. try {
  1250. // Check user
  1251. $user = $this->userManager->get($share->getSharedWith());
  1252. if ($user === null) {
  1253. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
  1254. return false;
  1255. }
  1256. // Handle user shares
  1257. if ($share->getShareType() === IShare::TYPE_USER) {
  1258. // Check email address
  1259. $emailAddress = $user->getEMailAddress();
  1260. if ($emailAddress === null || $emailAddress === '') {
  1261. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
  1262. return false;
  1263. }
  1264. $userLang = $this->l10nFactory->getUserLanguage($user);
  1265. $l = $this->l10nFactory->get('lib', $userLang);
  1266. $this->sendUserShareMail(
  1267. $l,
  1268. $share->getNode()->getName(),
  1269. $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
  1270. $share->getSharedBy(),
  1271. $emailAddress,
  1272. $share->getExpirationDate(),
  1273. $share->getNote()
  1274. );
  1275. $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId() . '.', ['app' => 'share']);
  1276. return true;
  1277. }
  1278. } catch (\Exception $e) {
  1279. $this->logger->error('Share notification mail could not be sent.', ['exception' => $e]);
  1280. }
  1281. return false;
  1282. }
  1283. /**
  1284. * Send mail notifications for the user share type
  1285. *
  1286. * @param IL10N $l Language of the recipient
  1287. * @param string $filename file/folder name
  1288. * @param string $link link to the file/folder
  1289. * @param string $initiator user ID of share sender
  1290. * @param string $shareWith email address of share receiver
  1291. * @param \DateTime|null $expiration
  1292. * @param string $note
  1293. * @throws \Exception
  1294. */
  1295. protected function sendUserShareMail(
  1296. IL10N $l,
  1297. $filename,
  1298. $link,
  1299. $initiator,
  1300. $shareWith,
  1301. ?\DateTime $expiration = null,
  1302. $note = '') {
  1303. $initiatorUser = $this->userManager->get($initiator);
  1304. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  1305. $message = $this->mailer->createMessage();
  1306. $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
  1307. 'filename' => $filename,
  1308. 'link' => $link,
  1309. 'initiator' => $initiatorDisplayName,
  1310. 'expiration' => $expiration,
  1311. 'shareWith' => $shareWith,
  1312. ]);
  1313. $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
  1314. $emailTemplate->addHeader();
  1315. $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
  1316. $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
  1317. if ($note !== '') {
  1318. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  1319. }
  1320. $emailTemplate->addBodyText(
  1321. htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
  1322. $text
  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. }