DefaultShareProvider.php 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  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. $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
  1319. if ($note !== '') {
  1320. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  1321. }
  1322. $emailTemplate->addBodyText(
  1323. htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
  1324. $text
  1325. );
  1326. $emailTemplate->addBodyButton(
  1327. $l->t('Open »%s«', [$filename]),
  1328. $link
  1329. );
  1330. $message->setTo([$shareWith]);
  1331. // The "From" contains the sharers name
  1332. $instanceName = $this->defaults->getName();
  1333. $senderName = $l->t(
  1334. '%1$s via %2$s',
  1335. [
  1336. $initiatorDisplayName,
  1337. $instanceName,
  1338. ]
  1339. );
  1340. $message->setFrom([\OCP\Util::getDefaultEmailAddress('noreply') => $senderName]);
  1341. // The "Reply-To" is set to the sharer if an mail address is configured
  1342. // also the default footer contains a "Do not reply" which needs to be adjusted.
  1343. if ($initiatorUser) {
  1344. $initiatorEmail = $initiatorUser->getEMailAddress();
  1345. if ($initiatorEmail !== null) {
  1346. $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
  1347. $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
  1348. } else {
  1349. $emailTemplate->addFooter();
  1350. }
  1351. } else {
  1352. $emailTemplate->addFooter();
  1353. }
  1354. $message->useTemplate($emailTemplate);
  1355. $failedRecipients = $this->mailer->send($message);
  1356. if (!empty($failedRecipients)) {
  1357. $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
  1358. return;
  1359. }
  1360. }
  1361. /**
  1362. * send note by mail
  1363. *
  1364. * @param array $recipients
  1365. * @param IShare $share
  1366. * @throws \OCP\Files\NotFoundException
  1367. */
  1368. private function sendNote(array $recipients, IShare $share) {
  1369. $toListByLanguage = [];
  1370. foreach ($recipients as $recipient) {
  1371. /** @var IUser $recipient */
  1372. $email = $recipient->getEMailAddress();
  1373. if ($email) {
  1374. $language = $this->l10nFactory->getUserLanguage($recipient);
  1375. if (!isset($toListByLanguage[$language])) {
  1376. $toListByLanguage[$language] = [];
  1377. }
  1378. $toListByLanguage[$language][$email] = $recipient->getDisplayName();
  1379. }
  1380. }
  1381. if (empty($toListByLanguage)) {
  1382. return;
  1383. }
  1384. foreach ($toListByLanguage as $l10n => $toList) {
  1385. $filename = $share->getNode()->getName();
  1386. $initiator = $share->getSharedBy();
  1387. $note = $share->getNote();
  1388. $l = $this->l10nFactory->get('lib', $l10n);
  1389. $initiatorUser = $this->userManager->get($initiator);
  1390. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  1391. $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
  1392. $plainHeading = $l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
  1393. $htmlHeading = $l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
  1394. $message = $this->mailer->createMessage();
  1395. $emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
  1396. $emailTemplate->setSubject($l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
  1397. $emailTemplate->addHeader();
  1398. $emailTemplate->addHeading($htmlHeading, $plainHeading);
  1399. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  1400. $link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
  1401. $emailTemplate->addBodyButton(
  1402. $l->t('Open »%s«', [$filename]),
  1403. $link
  1404. );
  1405. // The "From" contains the sharers name
  1406. $instanceName = $this->defaults->getName();
  1407. $senderName = $l->t(
  1408. '%1$s via %2$s',
  1409. [
  1410. $initiatorDisplayName,
  1411. $instanceName
  1412. ]
  1413. );
  1414. $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
  1415. if ($initiatorEmailAddress !== null) {
  1416. $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
  1417. $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
  1418. } else {
  1419. $emailTemplate->addFooter();
  1420. }
  1421. if (count($toList) === 1) {
  1422. $message->setTo($toList);
  1423. } else {
  1424. $message->setTo([]);
  1425. $message->setBcc($toList);
  1426. }
  1427. $message->useTemplate($emailTemplate);
  1428. $this->mailer->send($message);
  1429. }
  1430. }
  1431. public function getAllShares(): iterable {
  1432. $qb = $this->dbConn->getQueryBuilder();
  1433. $qb->select('*')
  1434. ->from('share')
  1435. ->where(
  1436. $qb->expr()->orX(
  1437. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_USER)),
  1438. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_GROUP)),
  1439. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_LINK))
  1440. )
  1441. );
  1442. $cursor = $qb->executeQuery();
  1443. while ($data = $cursor->fetch()) {
  1444. try {
  1445. $share = $this->createShare($data);
  1446. } catch (InvalidShare $e) {
  1447. continue;
  1448. }
  1449. yield $share;
  1450. }
  1451. $cursor->closeCursor();
  1452. }
  1453. /**
  1454. * Load from database format (JSON string) to IAttributes
  1455. *
  1456. * @return IShare the modified share
  1457. */
  1458. protected function updateShareAttributes(IShare $share, ?string $data): IShare {
  1459. if ($data !== null && $data !== '') {
  1460. $attributes = new ShareAttributes();
  1461. $compressedAttributes = \json_decode($data, true);
  1462. if ($compressedAttributes === false || $compressedAttributes === null) {
  1463. return $share;
  1464. }
  1465. foreach ($compressedAttributes as $compressedAttribute) {
  1466. $attributes->setAttribute(
  1467. $compressedAttribute[0],
  1468. $compressedAttribute[1],
  1469. $compressedAttribute[2]
  1470. );
  1471. }
  1472. $share->setAttributes($attributes);
  1473. }
  1474. return $share;
  1475. }
  1476. /**
  1477. * Format IAttributes to database format (JSON string)
  1478. */
  1479. protected function formatShareAttributes(?IAttributes $attributes): ?string {
  1480. if ($attributes === null || empty($attributes->toArray())) {
  1481. return null;
  1482. }
  1483. $compressedAttributes = [];
  1484. foreach ($attributes->toArray() as $attribute) {
  1485. $compressedAttributes[] = [
  1486. 0 => $attribute['scope'],
  1487. 1 => $attribute['key'],
  1488. 2 => $attribute['value']
  1489. ];
  1490. }
  1491. return \json_encode($compressedAttributes);
  1492. }
  1493. }