ShareByMailProvider.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\ShareByMail;
  7. use OC\Share20\DefaultShareProvider;
  8. use OC\Share20\Exception\InvalidShare;
  9. use OC\Share20\Share;
  10. use OC\User\NoUserException;
  11. use OCA\ShareByMail\Settings\SettingsManager;
  12. use OCP\Activity\IManager;
  13. use OCP\DB\QueryBuilder\IQueryBuilder;
  14. use OCP\Defaults;
  15. use OCP\EventDispatcher\IEventDispatcher;
  16. use OCP\Files\Folder;
  17. use OCP\Files\IRootFolder;
  18. use OCP\Files\Node;
  19. use OCP\HintException;
  20. use OCP\IConfig;
  21. use OCP\IDBConnection;
  22. use OCP\IL10N;
  23. use OCP\IURLGenerator;
  24. use OCP\IUser;
  25. use OCP\IUserManager;
  26. use OCP\Mail\IMailer;
  27. use OCP\Security\Events\GenerateSecurePasswordEvent;
  28. use OCP\Security\IHasher;
  29. use OCP\Security\ISecureRandom;
  30. use OCP\Share\Exceptions\GenericShareException;
  31. use OCP\Share\Exceptions\ShareNotFound;
  32. use OCP\Share\IAttributes;
  33. use OCP\Share\IManager as IShareManager;
  34. use OCP\Share\IShare;
  35. use OCP\Share\IShareProviderWithNotification;
  36. use Psr\Log\LoggerInterface;
  37. /**
  38. * Class ShareByMail
  39. *
  40. * @package OCA\ShareByMail
  41. */
  42. class ShareByMailProvider extends DefaultShareProvider implements IShareProviderWithNotification {
  43. /**
  44. * Return the identifier of this provider.
  45. *
  46. * @return string Containing only [a-zA-Z0-9]
  47. */
  48. public function identifier(): string {
  49. return 'ocMailShare';
  50. }
  51. public function __construct(
  52. private IConfig $config,
  53. private IDBConnection $dbConnection,
  54. private ISecureRandom $secureRandom,
  55. private IUserManager $userManager,
  56. private IRootFolder $rootFolder,
  57. private IL10N $l,
  58. private LoggerInterface $logger,
  59. private IMailer $mailer,
  60. private IURLGenerator $urlGenerator,
  61. private IManager $activityManager,
  62. private SettingsManager $settingsManager,
  63. private Defaults $defaults,
  64. private IHasher $hasher,
  65. private IEventDispatcher $eventDispatcher,
  66. private IShareManager $shareManager,
  67. ) {
  68. }
  69. /**
  70. * Share a path
  71. *
  72. * @throws ShareNotFound
  73. * @throws \Exception
  74. */
  75. public function create(IShare $share): IShare {
  76. $shareWith = $share->getSharedWith();
  77. // Check if file is not already shared with the given email,
  78. // if we have an email at all.
  79. $alreadyShared = $this->getSharedWith($shareWith, IShare::TYPE_EMAIL, $share->getNode(), 1, 0);
  80. if ($shareWith !== '' && !empty($alreadyShared)) {
  81. $message = 'Sharing %1$s failed, because this item is already shared with the account %2$s';
  82. $message_t = $this->l->t('Sharing %1$s failed, because this item is already shared with the account %2$s', [$share->getNode()->getName(), $shareWith]);
  83. $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
  84. throw new \Exception($message_t);
  85. }
  86. // if the admin enforces a password for all mail shares we create a
  87. // random password and send it to the recipient
  88. $password = $share->getPassword() ?: '';
  89. $passwordEnforced = $this->shareManager->shareApiLinkEnforcePassword();
  90. if ($passwordEnforced && empty($password)) {
  91. $password = $this->autoGeneratePassword($share);
  92. }
  93. if (!empty($password)) {
  94. $share->setPassword($this->hasher->hash($password));
  95. }
  96. $shareId = $this->createMailShare($share);
  97. $this->createShareActivity($share);
  98. $data = $this->getRawShare($shareId);
  99. // Temporary set the clear password again to send it by mail
  100. // This need to be done after the share was created in the database
  101. // as the password is hashed in between.
  102. if (!empty($password)) {
  103. $data['password'] = $password;
  104. }
  105. return $this->createShareObject($data);
  106. }
  107. /**
  108. * auto generate password in case of password enforcement on mail shares
  109. *
  110. * @throws \Exception
  111. */
  112. protected function autoGeneratePassword(IShare $share): string {
  113. $initiatorUser = $this->userManager->get($share->getSharedBy());
  114. $initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
  115. $allowPasswordByMail = $this->settingsManager->sendPasswordByMail();
  116. if ($initiatorEMailAddress === null && !$allowPasswordByMail) {
  117. throw new \Exception(
  118. $this->l->t("We cannot send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
  119. );
  120. }
  121. $passwordEvent = new GenerateSecurePasswordEvent();
  122. $this->eventDispatcher->dispatchTyped($passwordEvent);
  123. $password = $passwordEvent->getPassword();
  124. if ($password === null) {
  125. $password = $this->secureRandom->generate(8, ISecureRandom::CHAR_HUMAN_READABLE);
  126. }
  127. return $password;
  128. }
  129. /**
  130. * create activity if a file/folder was shared by mail
  131. */
  132. protected function createShareActivity(IShare $share, string $type = 'share'): void {
  133. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  134. $this->publishActivity(
  135. $type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_SELF : Activity::SUBJECT_UNSHARED_EMAIL_SELF,
  136. [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
  137. $share->getSharedBy(),
  138. $share->getNode()->getId(),
  139. (string) $userFolder->getRelativePath($share->getNode()->getPath())
  140. );
  141. if ($share->getShareOwner() !== $share->getSharedBy()) {
  142. $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  143. $fileId = $share->getNode()->getId();
  144. $nodes = $ownerFolder->getById($fileId);
  145. $ownerPath = $nodes[0]->getPath();
  146. $this->publishActivity(
  147. $type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_BY : Activity::SUBJECT_UNSHARED_EMAIL_BY,
  148. [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
  149. $share->getShareOwner(),
  150. $fileId,
  151. (string) $ownerFolder->getRelativePath($ownerPath)
  152. );
  153. }
  154. }
  155. /**
  156. * create activity if a file/folder was shared by mail
  157. */
  158. protected function createPasswordSendActivity(IShare $share, string $sharedWith, bool $sendToSelf): void {
  159. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  160. if ($sendToSelf) {
  161. $this->publishActivity(
  162. Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF,
  163. [$userFolder->getRelativePath($share->getNode()->getPath())],
  164. $share->getSharedBy(),
  165. $share->getNode()->getId(),
  166. (string) $userFolder->getRelativePath($share->getNode()->getPath())
  167. );
  168. } else {
  169. $this->publishActivity(
  170. Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND,
  171. [$userFolder->getRelativePath($share->getNode()->getPath()), $sharedWith],
  172. $share->getSharedBy(),
  173. $share->getNode()->getId(),
  174. (string) $userFolder->getRelativePath($share->getNode()->getPath())
  175. );
  176. }
  177. }
  178. /**
  179. * publish activity if a file/folder was shared by mail
  180. */
  181. protected function publishActivity(string $subject, array $parameters, string $affectedUser, int $fileId, string $filePath): void {
  182. $event = $this->activityManager->generateEvent();
  183. $event->setApp('sharebymail')
  184. ->setType('shared')
  185. ->setSubject($subject, $parameters)
  186. ->setAffectedUser($affectedUser)
  187. ->setObject('files', $fileId, $filePath);
  188. $this->activityManager->publish($event);
  189. }
  190. /**
  191. * @throws \Exception
  192. */
  193. protected function createMailShare(IShare $share): int {
  194. $share->setToken($this->generateToken());
  195. return $this->addShareToDB(
  196. $share->getNodeId(),
  197. $share->getNodeType(),
  198. $share->getSharedWith(),
  199. $share->getSharedBy(),
  200. $share->getShareOwner(),
  201. $share->getPermissions(),
  202. $share->getToken(),
  203. $share->getPassword(),
  204. $share->getPasswordExpirationTime(),
  205. $share->getSendPasswordByTalk(),
  206. $share->getHideDownload(),
  207. $share->getLabel(),
  208. $share->getExpirationDate(),
  209. $share->getNote(),
  210. $share->getAttributes(),
  211. $share->getMailSend(),
  212. );
  213. }
  214. /**
  215. * @inheritDoc
  216. */
  217. public function sendMailNotification(IShare $share): bool {
  218. $shareId = $share->getId();
  219. $emails = $this->getSharedWithEmails($share);
  220. $validEmails = array_filter($emails, function (string $email) {
  221. return $this->mailer->validateMailAddress($email);
  222. });
  223. if (count($validEmails) === 0) {
  224. $this->removeShareFromTable((int)$shareId);
  225. $e = new HintException('Failed to send share by mail. Could not find a valid email address: ' . join(', ', $emails),
  226. $this->l->t('Failed to send share by email. Got an invalid email address'));
  227. $this->logger->error('Failed to send share by mail. Could not find a valid email address ' . join(', ', $emails), [
  228. 'app' => 'sharebymail',
  229. 'exception' => $e,
  230. ]);
  231. }
  232. try {
  233. $this->sendEmail($share, $validEmails);
  234. // If we have a password set, we send it to the recipient
  235. if ($share->getPassword() !== null) {
  236. // If share-by-talk password is enabled, we do not send the notification
  237. // to the recipient. They will have to request it to the owner after opening the link.
  238. // Secondly, if the password expiration is disabled, we send the notification to the recipient
  239. // Lastly, if the mail to recipient failed, we send the password to the owner as a fallback.
  240. // If a password expires, the recipient will still be able to request a new one via talk.
  241. $passwordExpire = $this->config->getSystemValue('sharing.enable_mail_link_password_expiration', false);
  242. $passwordEnforced = $this->shareManager->shareApiLinkEnforcePassword();
  243. if ($passwordExpire === false || $share->getSendPasswordByTalk()) {
  244. $send = $this->sendPassword($share, $share->getPassword(), $validEmails);
  245. if ($passwordEnforced && $send === false) {
  246. $this->sendPasswordToOwner($share, $share->getPassword());
  247. }
  248. }
  249. }
  250. return true;
  251. } catch (HintException $hintException) {
  252. $this->logger->error('Failed to send share by mail.', [
  253. 'app' => 'sharebymail',
  254. 'exception' => $hintException,
  255. ]);
  256. $this->removeShareFromTable((int)$shareId);
  257. throw $hintException;
  258. } catch (\Exception $e) {
  259. $this->logger->error('Failed to send share by mail.', [
  260. 'app' => 'sharebymail',
  261. 'exception' => $e,
  262. ]);
  263. $this->removeShareFromTable((int)$shareId);
  264. throw new HintException(
  265. 'Failed to send share by mail',
  266. $this->l->t('Failed to send share by email'),
  267. 0,
  268. $e,
  269. );
  270. }
  271. return false;
  272. }
  273. /**
  274. * @param IShare $share The share to send the email for
  275. * @param array $emails The email addresses to send the email to
  276. */
  277. protected function sendEmail(IShare $share, array $emails): void {
  278. $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', [
  279. 'token' => $share->getToken()
  280. ]);
  281. $expiration = $share->getExpirationDate();
  282. $filename = $share->getNode()->getName();
  283. $initiator = $share->getSharedBy();
  284. $note = $share->getNote();
  285. $shareWith = $share->getSharedWith();
  286. $initiatorUser = $this->userManager->get($initiator);
  287. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  288. $message = $this->mailer->createMessage();
  289. $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientNotification', [
  290. 'filename' => $filename,
  291. 'link' => $link,
  292. 'initiator' => $initiatorDisplayName,
  293. 'expiration' => $expiration,
  294. 'shareWith' => $shareWith,
  295. 'note' => $note
  296. ]);
  297. $emailTemplate->setSubject($this->l->t('%1$s shared %2$s with you', [$initiatorDisplayName, $filename]));
  298. $emailTemplate->addHeader();
  299. $emailTemplate->addHeading($this->l->t('%1$s shared %2$s with you', [$initiatorDisplayName, $filename]), false);
  300. $text = $this->l->t('%1$s shared %2$s with you.', [$initiatorDisplayName, $filename]);
  301. if ($note !== '') {
  302. $emailTemplate->addBodyListItem(
  303. htmlspecialchars($note),
  304. $this->l->t('Note:'),
  305. $this->getAbsoluteImagePath('caldav/description.png'),
  306. $note
  307. );
  308. }
  309. if ($expiration !== null) {
  310. $dateString = (string)$this->l->l('date', $expiration, ['width' => 'medium']);
  311. $emailTemplate->addBodyListItem(
  312. $this->l->t('This share is valid until %s at midnight', [$dateString]),
  313. $this->l->t('Expiration:'),
  314. $this->getAbsoluteImagePath('caldav/time.png'),
  315. );
  316. }
  317. $emailTemplate->addBodyText(
  318. htmlspecialchars($text . ' ' . $this->l->t('Click the button below to open it.')),
  319. $text
  320. );
  321. $emailTemplate->addBodyButton(
  322. $this->l->t('Open %s', [$filename]),
  323. $link
  324. );
  325. // If multiple recipients are given, we send the mail to all of them
  326. if (count($emails) > 1) {
  327. // We do not want to expose the email addresses of the other recipients
  328. $message->setBcc($emails);
  329. } else {
  330. $message->setTo($emails);
  331. }
  332. // The "From" contains the sharers name
  333. $instanceName = $this->defaults->getName();
  334. $senderName = $instanceName;
  335. if ($this->settingsManager->replyToInitiator()) {
  336. $senderName = $this->l->t(
  337. '%1$s via %2$s',
  338. [
  339. $initiatorDisplayName,
  340. $instanceName
  341. ]
  342. );
  343. }
  344. $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
  345. // The "Reply-To" is set to the sharer if an mail address is configured
  346. // also the default footer contains a "Do not reply" which needs to be adjusted.
  347. if ($initiatorUser && $this->settingsManager->replyToInitiator()) {
  348. $initiatorEmail = $initiatorUser->getEMailAddress();
  349. if ($initiatorEmail !== null) {
  350. $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
  351. $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
  352. } else {
  353. $emailTemplate->addFooter();
  354. }
  355. } else {
  356. $emailTemplate->addFooter();
  357. }
  358. $message->useTemplate($emailTemplate);
  359. $failedRecipients = $this->mailer->send($message);
  360. if (!empty($failedRecipients)) {
  361. $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
  362. return;
  363. }
  364. }
  365. /**
  366. * Send password to recipient of a mail share
  367. * Will return false if
  368. * 1. the password is empty
  369. * 2. the setting to send the password by mail is disabled
  370. * 3. the share is set to send the password by talk
  371. *
  372. * @param IShare $share
  373. * @param string $password
  374. * @param array $emails
  375. * @return bool
  376. */
  377. protected function sendPassword(IShare $share, string $password, array $emails): bool {
  378. $filename = $share->getNode()->getName();
  379. $initiator = $share->getSharedBy();
  380. $shareWith = $share->getSharedWith();
  381. if ($password === '' || $this->settingsManager->sendPasswordByMail() === false || $share->getSendPasswordByTalk()) {
  382. return false;
  383. }
  384. $initiatorUser = $this->userManager->get($initiator);
  385. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  386. $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
  387. $plainBodyPart = $this->l->t("%1\$s shared %2\$s with you.\nYou should have already received a separate mail with a link to access it.\n", [$initiatorDisplayName, $filename]);
  388. $htmlBodyPart = $this->l->t('%1$s shared %2$s with you. You should have already received a separate mail with a link to access it.', [$initiatorDisplayName, $filename]);
  389. $message = $this->mailer->createMessage();
  390. $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientPasswordNotification', [
  391. 'filename' => $filename,
  392. 'password' => $password,
  393. 'initiator' => $initiatorDisplayName,
  394. 'initiatorEmail' => $initiatorEmailAddress,
  395. 'shareWith' => $shareWith,
  396. ]);
  397. $emailTemplate->setSubject($this->l->t('Password to access %1$s shared to you by %2$s', [$filename, $initiatorDisplayName]));
  398. $emailTemplate->addHeader();
  399. $emailTemplate->addHeading($this->l->t('Password to access %s', [$filename]), false);
  400. $emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
  401. $emailTemplate->addBodyText($this->l->t('It is protected with the following password:'));
  402. $emailTemplate->addBodyText($password);
  403. if ($this->config->getSystemValue('sharing.enable_mail_link_password_expiration', false) === true) {
  404. $expirationTime = new \DateTime();
  405. $expirationInterval = $this->config->getSystemValue('sharing.mail_link_password_expiration_interval', 3600);
  406. $expirationTime = $expirationTime->add(new \DateInterval('PT' . $expirationInterval . 'S'));
  407. $emailTemplate->addBodyText($this->l->t('This password will expire at %s', [$expirationTime->format('r')]));
  408. }
  409. // If multiple recipients are given, we send the mail to all of them
  410. if (count($emails) > 1) {
  411. // We do not want to expose the email addresses of the other recipients
  412. $message->setBcc($emails);
  413. } else {
  414. $message->setTo($emails);
  415. }
  416. // The "From" contains the sharers name
  417. $instanceName = $this->defaults->getName();
  418. $senderName = $instanceName;
  419. if ($this->settingsManager->replyToInitiator()) {
  420. $senderName = $this->l->t(
  421. '%1$s via %2$s',
  422. [
  423. $initiatorDisplayName,
  424. $instanceName
  425. ]
  426. );
  427. }
  428. $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
  429. // The "Reply-To" is set to the sharer if an mail address is configured
  430. // also the default footer contains a "Do not reply" which needs to be adjusted.
  431. if ($initiatorUser && $this->settingsManager->replyToInitiator()) {
  432. $initiatorEmail = $initiatorUser->getEMailAddress();
  433. if ($initiatorEmail !== null) {
  434. $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
  435. $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
  436. } else {
  437. $emailTemplate->addFooter();
  438. }
  439. } else {
  440. $emailTemplate->addFooter();
  441. }
  442. $message->useTemplate($emailTemplate);
  443. $failedRecipients = $this->mailer->send($message);
  444. if (!empty($failedRecipients)) {
  445. $this->logger->error('Share password mail could not be sent to: ' . implode(', ', $failedRecipients));
  446. return false;
  447. }
  448. $this->createPasswordSendActivity($share, $shareWith, false);
  449. return true;
  450. }
  451. protected function sendNote(IShare $share): void {
  452. $recipient = $share->getSharedWith();
  453. $filename = $share->getNode()->getName();
  454. $initiator = $share->getSharedBy();
  455. $note = $share->getNote();
  456. $initiatorUser = $this->userManager->get($initiator);
  457. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  458. $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
  459. $plainHeading = $this->l->t('%1$s shared %2$s with you and wants to add:', [$initiatorDisplayName, $filename]);
  460. $htmlHeading = $this->l->t('%1$s shared %2$s with you and wants to add', [$initiatorDisplayName, $filename]);
  461. $message = $this->mailer->createMessage();
  462. $emailTemplate = $this->mailer->createEMailTemplate('shareByMail.sendNote');
  463. $emailTemplate->setSubject($this->l->t('%s added a note to a file shared with you', [$initiatorDisplayName]));
  464. $emailTemplate->addHeader();
  465. $emailTemplate->addHeading(htmlspecialchars($htmlHeading), $plainHeading);
  466. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  467. $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
  468. ['token' => $share->getToken()]);
  469. $emailTemplate->addBodyButton(
  470. $this->l->t('Open %s', [$filename]),
  471. $link
  472. );
  473. // The "From" contains the sharers name
  474. $instanceName = $this->defaults->getName();
  475. $senderName = $instanceName;
  476. if ($this->settingsManager->replyToInitiator()) {
  477. $senderName = $this->l->t(
  478. '%1$s via %2$s',
  479. [
  480. $initiatorDisplayName,
  481. $instanceName
  482. ]
  483. );
  484. }
  485. $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
  486. if ($this->settingsManager->replyToInitiator() && $initiatorEmailAddress !== null) {
  487. $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
  488. $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
  489. } else {
  490. $emailTemplate->addFooter();
  491. }
  492. $message->setTo([$recipient]);
  493. $message->useTemplate($emailTemplate);
  494. $this->mailer->send($message);
  495. }
  496. /**
  497. * send auto generated password to the owner. This happens if the admin enforces
  498. * a password for mail shares and forbid to send the password by mail to the recipient
  499. *
  500. * @throws \Exception
  501. */
  502. protected function sendPasswordToOwner(IShare $share, string $password): bool {
  503. $filename = $share->getNode()->getName();
  504. $initiator = $this->userManager->get($share->getSharedBy());
  505. $initiatorEMailAddress = ($initiator instanceof IUser) ? $initiator->getEMailAddress() : null;
  506. $initiatorDisplayName = ($initiator instanceof IUser) ? $initiator->getDisplayName() : $share->getSharedBy();
  507. $shareWith = $share->getSharedWith();
  508. if ($initiatorEMailAddress === null) {
  509. throw new \Exception(
  510. $this->l->t("We cannot send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
  511. );
  512. }
  513. $bodyPart = $this->l->t('You just shared %1$s with %2$s. The share was already sent to the recipient. Due to the security policies defined by the administrator of %3$s each share needs to be protected by password and it is not allowed to send the password directly to the recipient. Therefore you need to forward the password manually to the recipient.', [$filename, $shareWith, $this->defaults->getName()]);
  514. $message = $this->mailer->createMessage();
  515. $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.OwnerPasswordNotification', [
  516. 'filename' => $filename,
  517. 'password' => $password,
  518. 'initiator' => $initiatorDisplayName,
  519. 'initiatorEmail' => $initiatorEMailAddress,
  520. 'shareWith' => $shareWith,
  521. ]);
  522. $emailTemplate->setSubject($this->l->t('Password to access %1$s shared by you with %2$s', [$filename, $shareWith]));
  523. $emailTemplate->addHeader();
  524. $emailTemplate->addHeading($this->l->t('Password to access %s', [$filename]), false);
  525. $emailTemplate->addBodyText($bodyPart);
  526. $emailTemplate->addBodyText($this->l->t('This is the password:'));
  527. $emailTemplate->addBodyText($password);
  528. if ($this->config->getSystemValue('sharing.enable_mail_link_password_expiration', false) === true) {
  529. $expirationTime = new \DateTime();
  530. $expirationInterval = $this->config->getSystemValue('sharing.mail_link_password_expiration_interval', 3600);
  531. $expirationTime = $expirationTime->add(new \DateInterval('PT' . $expirationInterval . 'S'));
  532. $emailTemplate->addBodyText($this->l->t('This password will expire at %s', [$expirationTime->format('r')]));
  533. }
  534. $emailTemplate->addBodyText($this->l->t('You can choose a different password at any time in the share dialog.'));
  535. $emailTemplate->addFooter();
  536. $instanceName = $this->defaults->getName();
  537. $senderName = $this->l->t(
  538. '%1$s via %2$s',
  539. [
  540. $initiatorDisplayName,
  541. $instanceName
  542. ]
  543. );
  544. $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
  545. $message->setTo([$initiatorEMailAddress => $initiatorDisplayName]);
  546. $message->useTemplate($emailTemplate);
  547. $this->mailer->send($message);
  548. $this->createPasswordSendActivity($share, $shareWith, true);
  549. return true;
  550. }
  551. private function getAbsoluteImagePath(string $path):string {
  552. return $this->urlGenerator->getAbsoluteURL(
  553. $this->urlGenerator->imagePath('core', $path)
  554. );
  555. }
  556. /**
  557. * generate share token
  558. */
  559. protected function generateToken(int $size = 15): string {
  560. $token = $this->secureRandom->generate($size, ISecureRandom::CHAR_HUMAN_READABLE);
  561. return $token;
  562. }
  563. /**
  564. * Get all children of this share
  565. *
  566. * @return IShare[]
  567. */
  568. public function getChildren(IShare $parent): array {
  569. $children = [];
  570. $qb = $this->dbConnection->getQueryBuilder();
  571. $qb->select('*')
  572. ->from('share')
  573. ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
  574. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  575. ->orderBy('id');
  576. $cursor = $qb->executeQuery();
  577. while ($data = $cursor->fetch()) {
  578. $children[] = $this->createShareObject($data);
  579. }
  580. $cursor->closeCursor();
  581. return $children;
  582. }
  583. /**
  584. * Add share to the database and return the ID
  585. */
  586. protected function addShareToDB(
  587. ?int $itemSource,
  588. ?string $itemType,
  589. ?string $shareWith,
  590. ?string $sharedBy,
  591. ?string $uidOwner,
  592. ?int $permissions,
  593. ?string $token,
  594. ?string $password,
  595. ?\DateTimeInterface $passwordExpirationTime,
  596. ?bool $sendPasswordByTalk,
  597. ?bool $hideDownload,
  598. ?string $label,
  599. ?\DateTimeInterface $expirationTime,
  600. ?string $note = '',
  601. ?IAttributes $attributes = null,
  602. ?bool $mailSend = true
  603. ): int {
  604. $qb = $this->dbConnection->getQueryBuilder();
  605. $qb->insert('share')
  606. ->setValue('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL))
  607. ->setValue('item_type', $qb->createNamedParameter($itemType))
  608. ->setValue('item_source', $qb->createNamedParameter($itemSource))
  609. ->setValue('file_source', $qb->createNamedParameter($itemSource))
  610. ->setValue('share_with', $qb->createNamedParameter($shareWith))
  611. ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
  612. ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
  613. ->setValue('permissions', $qb->createNamedParameter($permissions))
  614. ->setValue('token', $qb->createNamedParameter($token))
  615. ->setValue('password', $qb->createNamedParameter($password))
  616. ->setValue('password_expiration_time', $qb->createNamedParameter($passwordExpirationTime, IQueryBuilder::PARAM_DATE))
  617. ->setValue('password_by_talk', $qb->createNamedParameter($sendPasswordByTalk, IQueryBuilder::PARAM_BOOL))
  618. ->setValue('stime', $qb->createNamedParameter(time()))
  619. ->setValue('hide_download', $qb->createNamedParameter((int)$hideDownload, IQueryBuilder::PARAM_INT))
  620. ->setValue('label', $qb->createNamedParameter($label))
  621. ->setValue('note', $qb->createNamedParameter($note))
  622. ->setValue('mail_send', $qb->createNamedParameter((int)$mailSend, IQueryBuilder::PARAM_INT));
  623. // set share attributes
  624. $shareAttributes = $this->formatShareAttributes($attributes);
  625. $qb->setValue('attributes', $qb->createNamedParameter($shareAttributes));
  626. if ($expirationTime !== null) {
  627. $qb->setValue('expiration', $qb->createNamedParameter($expirationTime, IQueryBuilder::PARAM_DATE));
  628. }
  629. $qb->executeStatement();
  630. return $qb->getLastInsertId();
  631. }
  632. /**
  633. * Update a share
  634. */
  635. public function update(IShare $share, ?string $plainTextPassword = null): IShare {
  636. $originalShare = $this->getShareById($share->getId());
  637. // a real password was given
  638. $validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
  639. if ($validPassword && ($originalShare->getPassword() !== $share->getPassword() ||
  640. ($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()))) {
  641. $emails = $this->getSharedWithEmails($share);
  642. $validEmails = array_filter($emails, function ($email) {
  643. return $this->mailer->validateMailAddress($email);
  644. });
  645. $this->sendPassword($share, $plainTextPassword, $validEmails);
  646. }
  647. $shareAttributes = $this->formatShareAttributes($share->getAttributes());
  648. /*
  649. * We allow updating mail shares
  650. */
  651. $qb = $this->dbConnection->getQueryBuilder();
  652. $qb->update('share')
  653. ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
  654. ->set('item_source', $qb->createNamedParameter($share->getNodeId()))
  655. ->set('file_source', $qb->createNamedParameter($share->getNodeId()))
  656. ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
  657. ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
  658. ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
  659. ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
  660. ->set('password', $qb->createNamedParameter($share->getPassword()))
  661. ->set('password_expiration_time', $qb->createNamedParameter($share->getPasswordExpirationTime(), IQueryBuilder::PARAM_DATE))
  662. ->set('label', $qb->createNamedParameter($share->getLabel()))
  663. ->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
  664. ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
  665. ->set('note', $qb->createNamedParameter($share->getNote()))
  666. ->set('hide_download', $qb->createNamedParameter((int)$share->getHideDownload(), IQueryBuilder::PARAM_INT))
  667. ->set('attributes', $qb->createNamedParameter($shareAttributes))
  668. ->set('mail_send', $qb->createNamedParameter((int)$share->getMailSend(), IQueryBuilder::PARAM_INT))
  669. ->executeStatement();
  670. if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
  671. $this->sendNote($share);
  672. }
  673. return $share;
  674. }
  675. /**
  676. * @inheritdoc
  677. */
  678. public function move(IShare $share, $recipient): IShare {
  679. /**
  680. * nothing to do here, mail shares are only outgoing shares
  681. */
  682. return $share;
  683. }
  684. /**
  685. * Delete a share (owner unShares the file)
  686. *
  687. * @param IShare $share
  688. */
  689. public function delete(IShare $share): void {
  690. try {
  691. $this->createShareActivity($share, 'unshare');
  692. } catch (\Exception $e) {
  693. }
  694. $this->removeShareFromTable((int)$share->getId());
  695. }
  696. /**
  697. * @inheritdoc
  698. */
  699. public function deleteFromSelf(IShare $share, $recipient): void {
  700. // nothing to do here, mail shares are only outgoing shares
  701. }
  702. public function restore(IShare $share, string $recipient): IShare {
  703. throw new GenericShareException('not implemented');
  704. }
  705. /**
  706. * @inheritdoc
  707. */
  708. public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset): array {
  709. $qb = $this->dbConnection->getQueryBuilder();
  710. $qb->select('*')
  711. ->from('share');
  712. $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)));
  713. /**
  714. * Reshares for this user are shares where they are the owner.
  715. */
  716. if ($reshares === false) {
  717. //Special case for old shares created via the web UI
  718. $or1 = $qb->expr()->andX(
  719. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  720. $qb->expr()->isNull('uid_initiator')
  721. );
  722. $qb->andWhere(
  723. $qb->expr()->orX(
  724. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
  725. $or1
  726. )
  727. );
  728. } elseif ($node === null) {
  729. $qb->andWhere(
  730. $qb->expr()->orX(
  731. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  732. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  733. )
  734. );
  735. }
  736. if ($node !== null) {
  737. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  738. }
  739. if ($limit !== -1) {
  740. $qb->setMaxResults($limit);
  741. }
  742. $qb->setFirstResult($offset);
  743. $qb->orderBy('id');
  744. $cursor = $qb->executeQuery();
  745. $shares = [];
  746. while ($data = $cursor->fetch()) {
  747. $shares[] = $this->createShareObject($data);
  748. }
  749. $cursor->closeCursor();
  750. return $shares;
  751. }
  752. /**
  753. * @inheritdoc
  754. */
  755. public function getShareById($id, $recipientId = null): IShare {
  756. $qb = $this->dbConnection->getQueryBuilder();
  757. $qb->select('*')
  758. ->from('share')
  759. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  760. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)));
  761. $cursor = $qb->executeQuery();
  762. $data = $cursor->fetch();
  763. $cursor->closeCursor();
  764. if ($data === false) {
  765. throw new ShareNotFound();
  766. }
  767. try {
  768. $share = $this->createShareObject($data);
  769. } catch (InvalidShare $e) {
  770. throw new ShareNotFound();
  771. }
  772. return $share;
  773. }
  774. /**
  775. * Get shares for a given path
  776. *
  777. * @return IShare[]
  778. */
  779. public function getSharesByPath(Node $path): array {
  780. $qb = $this->dbConnection->getQueryBuilder();
  781. $cursor = $qb->select('*')
  782. ->from('share')
  783. ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
  784. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  785. ->executeQuery();
  786. $shares = [];
  787. while ($data = $cursor->fetch()) {
  788. $shares[] = $this->createShareObject($data);
  789. }
  790. $cursor->closeCursor();
  791. return $shares;
  792. }
  793. /**
  794. * @inheritdoc
  795. */
  796. public function getSharedWith($userId, $shareType, $node, $limit, $offset): array {
  797. /** @var IShare[] $shares */
  798. $shares = [];
  799. //Get shares directly with this user
  800. $qb = $this->dbConnection->getQueryBuilder();
  801. $qb->select('*')
  802. ->from('share');
  803. // Order by id
  804. $qb->orderBy('id');
  805. // Set limit and offset
  806. if ($limit !== -1) {
  807. $qb->setMaxResults($limit);
  808. }
  809. $qb->setFirstResult($offset);
  810. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)));
  811. $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
  812. // Filter by node if provided
  813. if ($node !== null) {
  814. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  815. }
  816. $cursor = $qb->executeQuery();
  817. while ($data = $cursor->fetch()) {
  818. $shares[] = $this->createShareObject($data);
  819. }
  820. $cursor->closeCursor();
  821. return $shares;
  822. }
  823. /**
  824. * Get a share by token
  825. *
  826. * @throws ShareNotFound
  827. */
  828. public function getShareByToken($token): IShare {
  829. $qb = $this->dbConnection->getQueryBuilder();
  830. $cursor = $qb->select('*')
  831. ->from('share')
  832. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  833. ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  834. ->executeQuery();
  835. $data = $cursor->fetch();
  836. if ($data === false) {
  837. throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
  838. }
  839. try {
  840. $share = $this->createShareObject($data);
  841. } catch (InvalidShare $e) {
  842. throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
  843. }
  844. return $share;
  845. }
  846. /**
  847. * remove share from table
  848. */
  849. protected function removeShareFromTable(int $shareId): void {
  850. $qb = $this->dbConnection->getQueryBuilder();
  851. $qb->delete('share')
  852. ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
  853. $qb->executeStatement();
  854. }
  855. /**
  856. * Create a share object from an database row
  857. *
  858. * @throws InvalidShare
  859. * @throws ShareNotFound
  860. */
  861. protected function createShareObject(array $data): IShare {
  862. $share = new Share($this->rootFolder, $this->userManager);
  863. $share->setId((int)$data['id'])
  864. ->setShareType((int)$data['share_type'])
  865. ->setPermissions((int)$data['permissions'])
  866. ->setTarget($data['file_target'])
  867. ->setMailSend((bool)$data['mail_send'])
  868. ->setNote($data['note'])
  869. ->setToken($data['token']);
  870. $shareTime = new \DateTime();
  871. $shareTime->setTimestamp((int)$data['stime']);
  872. $share->setShareTime($shareTime);
  873. $share->setSharedWith($data['share_with'] ?? '');
  874. $share->setPassword($data['password']);
  875. $passwordExpirationTime = \DateTime::createFromFormat('Y-m-d H:i:s', $data['password_expiration_time'] ?? '');
  876. $share->setPasswordExpirationTime($passwordExpirationTime !== false ? $passwordExpirationTime : null);
  877. $share->setLabel($data['label']);
  878. $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
  879. $share->setHideDownload((bool)$data['hide_download']);
  880. if ($data['uid_initiator'] !== null) {
  881. $share->setShareOwner($data['uid_owner']);
  882. $share->setSharedBy($data['uid_initiator']);
  883. } else {
  884. //OLD SHARE
  885. $share->setSharedBy($data['uid_owner']);
  886. $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
  887. $owner = $path->getOwner();
  888. $share->setShareOwner($owner->getUID());
  889. }
  890. if ($data['expiration'] !== null) {
  891. $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
  892. if ($expiration !== false) {
  893. $share->setExpirationDate($expiration);
  894. }
  895. }
  896. $share = $this->updateShareAttributes($share, $data['attributes']);
  897. $share->setNodeId((int)$data['file_source']);
  898. $share->setNodeType($data['item_type']);
  899. $share->setProviderId($this->identifier());
  900. return $share;
  901. }
  902. /**
  903. * Get the node with file $id for $user
  904. *
  905. * @throws InvalidShare
  906. */
  907. private function getNode(string $userId, int $id): Node {
  908. try {
  909. $userFolder = $this->rootFolder->getUserFolder($userId);
  910. } catch (NoUserException $e) {
  911. throw new InvalidShare();
  912. }
  913. $nodes = $userFolder->getById($id);
  914. if (empty($nodes)) {
  915. throw new InvalidShare();
  916. }
  917. return $nodes[0];
  918. }
  919. /**
  920. * A user is deleted from the system
  921. * So clean up the relevant shares.
  922. */
  923. public function userDeleted($uid, $shareType): void {
  924. $qb = $this->dbConnection->getQueryBuilder();
  925. $qb->delete('share')
  926. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  927. ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
  928. ->executeStatement();
  929. }
  930. /**
  931. * This provider does not support group shares
  932. */
  933. public function groupDeleted($gid): void {
  934. }
  935. /**
  936. * This provider does not support group shares
  937. */
  938. public function userDeletedFromGroup($uid, $gid): void {
  939. }
  940. /**
  941. * get database row of a give share
  942. *
  943. * @throws ShareNotFound
  944. */
  945. protected function getRawShare(int $id): array {
  946. // Now fetch the inserted share and create a complete share object
  947. $qb = $this->dbConnection->getQueryBuilder();
  948. $qb->select('*')
  949. ->from('share')
  950. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
  951. $cursor = $qb->executeQuery();
  952. $data = $cursor->fetch();
  953. $cursor->closeCursor();
  954. if ($data === false) {
  955. throw new ShareNotFound;
  956. }
  957. return $data;
  958. }
  959. public function getSharesInFolder($userId, Folder $node, $reshares, $shallow = true): array {
  960. $qb = $this->dbConnection->getQueryBuilder();
  961. $qb->select('*')
  962. ->from('share', 's')
  963. ->andWhere($qb->expr()->orX(
  964. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  965. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  966. ))
  967. ->andWhere(
  968. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL))
  969. );
  970. /**
  971. * Reshares for this user are shares where they are the owner.
  972. */
  973. if ($reshares === false) {
  974. $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
  975. } else {
  976. $qb->andWhere(
  977. $qb->expr()->orX(
  978. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  979. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  980. )
  981. );
  982. }
  983. $qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
  984. $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
  985. $qb->orderBy('id');
  986. $cursor = $qb->executeQuery();
  987. $shares = [];
  988. while ($data = $cursor->fetch()) {
  989. $shares[$data['fileid']][] = $this->createShareObject($data);
  990. }
  991. $cursor->closeCursor();
  992. return $shares;
  993. }
  994. /**
  995. * @inheritdoc
  996. */
  997. public function getAccessList($nodes, $currentAccess): array {
  998. $ids = [];
  999. foreach ($nodes as $node) {
  1000. $ids[] = $node->getId();
  1001. }
  1002. $qb = $this->dbConnection->getQueryBuilder();
  1003. $qb->select('share_with', 'file_source', 'token')
  1004. ->from('share')
  1005. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  1006. ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
  1007. ->andWhere($qb->expr()->orX(
  1008. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  1009. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  1010. ));
  1011. $cursor = $qb->executeQuery();
  1012. $public = false;
  1013. $mail = [];
  1014. while ($row = $cursor->fetch()) {
  1015. $public = true;
  1016. if ($currentAccess === false) {
  1017. $mail[] = $row['share_with'];
  1018. } else {
  1019. $mail[$row['share_with']] = [
  1020. 'node_id' => $row['file_source'],
  1021. 'token' => $row['token']
  1022. ];
  1023. }
  1024. }
  1025. $cursor->closeCursor();
  1026. return ['public' => $public, 'mail' => $mail];
  1027. }
  1028. public function getAllShares(): iterable {
  1029. $qb = $this->dbConnection->getQueryBuilder();
  1030. $qb->select('*')
  1031. ->from('share')
  1032. ->where(
  1033. $qb->expr()->orX(
  1034. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_EMAIL))
  1035. )
  1036. );
  1037. $cursor = $qb->executeQuery();
  1038. while ($data = $cursor->fetch()) {
  1039. try {
  1040. $share = $this->createShareObject($data);
  1041. } catch (InvalidShare $e) {
  1042. continue;
  1043. } catch (ShareNotFound $e) {
  1044. continue;
  1045. }
  1046. yield $share;
  1047. }
  1048. $cursor->closeCursor();
  1049. }
  1050. /**
  1051. * Extract the emails from the share
  1052. * It can be a single email, from the share_with field
  1053. * or a list of emails from the emails attributes field.
  1054. * @param IShare $share
  1055. * @return string[]
  1056. */
  1057. protected function getSharedWithEmails(IShare $share): array {
  1058. $attributes = $share->getAttributes();
  1059. if ($attributes === null) {
  1060. return [$share->getSharedWith()];
  1061. }
  1062. $emails = $attributes->getAttribute('shareWith', 'emails');
  1063. if (isset($emails) && is_array($emails) && !empty($emails)) {
  1064. return $emails;
  1065. }
  1066. return [$share->getSharedWith()];
  1067. }
  1068. }