1
0

ShareByMailProvider.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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\Security\PasswordContext;
  31. use OCP\Share\Exceptions\GenericShareException;
  32. use OCP\Share\Exceptions\ShareNotFound;
  33. use OCP\Share\IAttributes;
  34. use OCP\Share\IManager as IShareManager;
  35. use OCP\Share\IShare;
  36. use OCP\Share\IShareProviderWithNotification;
  37. use OCP\Util;
  38. use Psr\Log\LoggerInterface;
  39. /**
  40. * Class ShareByMail
  41. *
  42. * @package OCA\ShareByMail
  43. */
  44. class ShareByMailProvider extends DefaultShareProvider implements IShareProviderWithNotification {
  45. /**
  46. * Return the identifier of this provider.
  47. *
  48. * @return string Containing only [a-zA-Z0-9]
  49. */
  50. public function identifier(): string {
  51. return 'ocMailShare';
  52. }
  53. public function __construct(
  54. private IConfig $config,
  55. private IDBConnection $dbConnection,
  56. private ISecureRandom $secureRandom,
  57. private IUserManager $userManager,
  58. private IRootFolder $rootFolder,
  59. private IL10N $l,
  60. private LoggerInterface $logger,
  61. private IMailer $mailer,
  62. private IURLGenerator $urlGenerator,
  63. private IManager $activityManager,
  64. private SettingsManager $settingsManager,
  65. private Defaults $defaults,
  66. private IHasher $hasher,
  67. private IEventDispatcher $eventDispatcher,
  68. private IShareManager $shareManager,
  69. ) {
  70. }
  71. /**
  72. * Share a path
  73. *
  74. * @throws ShareNotFound
  75. * @throws \Exception
  76. */
  77. public function create(IShare $share): IShare {
  78. $shareWith = $share->getSharedWith();
  79. // Check if file is not already shared with the given email,
  80. // if we have an email at all.
  81. $alreadyShared = $this->getSharedWith($shareWith, IShare::TYPE_EMAIL, $share->getNode(), 1, 0);
  82. if ($shareWith !== '' && !empty($alreadyShared)) {
  83. $message = 'Sharing %1$s failed, because this item is already shared with the account %2$s';
  84. $message_t = $this->l->t('Sharing %1$s failed, because this item is already shared with the account %2$s', [$share->getNode()->getName(), $shareWith]);
  85. $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
  86. throw new \Exception($message_t);
  87. }
  88. // if the admin enforces a password for all mail shares we create a
  89. // random password and send it to the recipient
  90. $password = $share->getPassword() ?: '';
  91. $passwordEnforced = $this->shareManager->shareApiLinkEnforcePassword();
  92. if ($passwordEnforced && empty($password)) {
  93. $password = $this->autoGeneratePassword($share);
  94. }
  95. if (!empty($password)) {
  96. $share->setPassword($this->hasher->hash($password));
  97. }
  98. $shareId = $this->createMailShare($share);
  99. $this->createShareActivity($share);
  100. $data = $this->getRawShare($shareId);
  101. // Temporary set the clear password again to send it by mail
  102. // This need to be done after the share was created in the database
  103. // as the password is hashed in between.
  104. if (!empty($password)) {
  105. $data['password'] = $password;
  106. }
  107. return $this->createShareObject($data);
  108. }
  109. /**
  110. * auto generate password in case of password enforcement on mail shares
  111. *
  112. * @throws \Exception
  113. */
  114. protected function autoGeneratePassword(IShare $share): string {
  115. $initiatorUser = $this->userManager->get($share->getSharedBy());
  116. $initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
  117. $allowPasswordByMail = $this->settingsManager->sendPasswordByMail();
  118. if ($initiatorEMailAddress === null && !$allowPasswordByMail) {
  119. throw new \Exception(
  120. $this->l->t('We cannot send you the auto-generated password. Please set a valid email address in your personal settings and try again.')
  121. );
  122. }
  123. $passwordEvent = new GenerateSecurePasswordEvent(PasswordContext::SHARING);
  124. $this->eventDispatcher->dispatchTyped($passwordEvent);
  125. $password = $passwordEvent->getPassword();
  126. if ($password === null) {
  127. $password = $this->secureRandom->generate(8, ISecureRandom::CHAR_HUMAN_READABLE);
  128. }
  129. return $password;
  130. }
  131. /**
  132. * create activity if a file/folder was shared by mail
  133. */
  134. protected function createShareActivity(IShare $share, string $type = 'share'): void {
  135. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  136. $this->publishActivity(
  137. $type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_SELF : Activity::SUBJECT_UNSHARED_EMAIL_SELF,
  138. [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
  139. $share->getSharedBy(),
  140. $share->getNode()->getId(),
  141. (string)$userFolder->getRelativePath($share->getNode()->getPath())
  142. );
  143. if ($share->getShareOwner() !== $share->getSharedBy()) {
  144. $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  145. $fileId = $share->getNode()->getId();
  146. $nodes = $ownerFolder->getById($fileId);
  147. $ownerPath = $nodes[0]->getPath();
  148. $this->publishActivity(
  149. $type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_BY : Activity::SUBJECT_UNSHARED_EMAIL_BY,
  150. [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
  151. $share->getShareOwner(),
  152. $fileId,
  153. (string)$ownerFolder->getRelativePath($ownerPath)
  154. );
  155. }
  156. }
  157. /**
  158. * create activity if a file/folder was shared by mail
  159. */
  160. protected function createPasswordSendActivity(IShare $share, string $sharedWith, bool $sendToSelf): void {
  161. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  162. if ($sendToSelf) {
  163. $this->publishActivity(
  164. Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF,
  165. [$userFolder->getRelativePath($share->getNode()->getPath())],
  166. $share->getSharedBy(),
  167. $share->getNode()->getId(),
  168. (string)$userFolder->getRelativePath($share->getNode()->getPath())
  169. );
  170. } else {
  171. $this->publishActivity(
  172. Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND,
  173. [$userFolder->getRelativePath($share->getNode()->getPath()), $sharedWith],
  174. $share->getSharedBy(),
  175. $share->getNode()->getId(),
  176. (string)$userFolder->getRelativePath($share->getNode()->getPath())
  177. );
  178. }
  179. }
  180. /**
  181. * publish activity if a file/folder was shared by mail
  182. */
  183. protected function publishActivity(string $subject, array $parameters, string $affectedUser, int $fileId, string $filePath): void {
  184. $event = $this->activityManager->generateEvent();
  185. $event->setApp('sharebymail')
  186. ->setType('shared')
  187. ->setSubject($subject, $parameters)
  188. ->setAffectedUser($affectedUser)
  189. ->setObject('files', $fileId, $filePath);
  190. $this->activityManager->publish($event);
  191. }
  192. /**
  193. * @throws \Exception
  194. */
  195. protected function createMailShare(IShare $share): int {
  196. $share->setToken($this->generateToken());
  197. return $this->addShareToDB(
  198. $share->getNodeId(),
  199. $share->getNodeType(),
  200. $share->getSharedWith(),
  201. $share->getSharedBy(),
  202. $share->getShareOwner(),
  203. $share->getPermissions(),
  204. $share->getToken(),
  205. $share->getPassword(),
  206. $share->getPasswordExpirationTime(),
  207. $share->getSendPasswordByTalk(),
  208. $share->getHideDownload(),
  209. $share->getLabel(),
  210. $share->getExpirationDate(),
  211. $share->getNote(),
  212. $share->getAttributes(),
  213. $share->getMailSend(),
  214. );
  215. }
  216. /**
  217. * @inheritDoc
  218. */
  219. public function sendMailNotification(IShare $share): bool {
  220. $shareId = $share->getId();
  221. $emails = $this->getSharedWithEmails($share);
  222. $validEmails = array_filter($emails, function (string $email) {
  223. return $this->mailer->validateMailAddress($email);
  224. });
  225. if (count($validEmails) === 0) {
  226. $this->removeShareFromTable((int)$shareId);
  227. $e = new HintException('Failed to send share by mail. Could not find a valid email address: ' . join(', ', $emails),
  228. $this->l->t('Failed to send share by email. Got an invalid email address'));
  229. $this->logger->error('Failed to send share by mail. Could not find a valid email address ' . join(', ', $emails), [
  230. 'app' => 'sharebymail',
  231. 'exception' => $e,
  232. ]);
  233. }
  234. try {
  235. $this->sendEmail($share, $validEmails);
  236. // If we have a password set, we send it to the recipient
  237. if ($share->getPassword() !== null) {
  238. // If share-by-talk password is enabled, we do not send the notification
  239. // to the recipient. They will have to request it to the owner after opening the link.
  240. // Secondly, if the password expiration is disabled, we send the notification to the recipient
  241. // Lastly, if the mail to recipient failed, we send the password to the owner as a fallback.
  242. // If a password expires, the recipient will still be able to request a new one via talk.
  243. $passwordExpire = $this->config->getSystemValue('sharing.enable_mail_link_password_expiration', false);
  244. $passwordEnforced = $this->shareManager->shareApiLinkEnforcePassword();
  245. if ($passwordExpire === false || $share->getSendPasswordByTalk()) {
  246. $send = $this->sendPassword($share, $share->getPassword(), $validEmails);
  247. if ($passwordEnforced && $send === false) {
  248. $this->sendPasswordToOwner($share, $share->getPassword());
  249. }
  250. }
  251. }
  252. return true;
  253. } catch (HintException $hintException) {
  254. $this->logger->error('Failed to send share by mail.', [
  255. 'app' => 'sharebymail',
  256. 'exception' => $hintException,
  257. ]);
  258. $this->removeShareFromTable((int)$shareId);
  259. throw $hintException;
  260. } catch (\Exception $e) {
  261. $this->logger->error('Failed to send share by mail.', [
  262. 'app' => 'sharebymail',
  263. 'exception' => $e,
  264. ]);
  265. $this->removeShareFromTable((int)$shareId);
  266. throw new HintException(
  267. 'Failed to send share by mail',
  268. $this->l->t('Failed to send share by email'),
  269. 0,
  270. $e,
  271. );
  272. }
  273. return false;
  274. }
  275. /**
  276. * @param IShare $share The share to send the email for
  277. * @param array $emails The email addresses to send the email to
  278. */
  279. protected function sendEmail(IShare $share, array $emails): void {
  280. $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', [
  281. 'token' => $share->getToken()
  282. ]);
  283. $expiration = $share->getExpirationDate();
  284. $filename = $share->getNode()->getName();
  285. $initiator = $share->getSharedBy();
  286. $note = $share->getNote();
  287. $shareWith = $share->getSharedWith();
  288. $initiatorUser = $this->userManager->get($initiator);
  289. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  290. $message = $this->mailer->createMessage();
  291. $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientNotification', [
  292. 'filename' => $filename,
  293. 'link' => $link,
  294. 'initiator' => $initiatorDisplayName,
  295. 'expiration' => $expiration,
  296. 'shareWith' => $shareWith,
  297. 'note' => $note
  298. ]);
  299. $emailTemplate->setSubject($this->l->t('%1$s shared %2$s with you', [$initiatorDisplayName, $filename]));
  300. $emailTemplate->addHeader();
  301. $emailTemplate->addHeading($this->l->t('%1$s shared %2$s with you', [$initiatorDisplayName, $filename]), false);
  302. if ($note !== '') {
  303. $emailTemplate->addBodyListItem(
  304. htmlspecialchars($note),
  305. $this->l->t('Note:'),
  306. $this->getAbsoluteImagePath('caldav/description.png'),
  307. $note
  308. );
  309. }
  310. if ($expiration !== null) {
  311. $dateString = (string)$this->l->l('date', $expiration, ['width' => 'medium']);
  312. $emailTemplate->addBodyListItem(
  313. $this->l->t('This share is valid until %s at midnight', [$dateString]),
  314. $this->l->t('Expiration:'),
  315. $this->getAbsoluteImagePath('caldav/time.png'),
  316. );
  317. }
  318. $emailTemplate->addBodyText(
  319. $this->l->t('Click the button below to open it.')
  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([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([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([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([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_DATETIME_MUTABLE))
  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_DATETIME_MUTABLE));
  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_DATETIME_MUTABLE))
  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_DATETIME_MUTABLE))
  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. ->set('reminder_sent', $qb->createNamedParameter($share->getReminderSent(), IQueryBuilder::PARAM_BOOL))
  670. ->executeStatement();
  671. if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
  672. $this->sendNote($share);
  673. }
  674. return $share;
  675. }
  676. /**
  677. * @inheritdoc
  678. */
  679. public function move(IShare $share, $recipient): IShare {
  680. /**
  681. * nothing to do here, mail shares are only outgoing shares
  682. */
  683. return $share;
  684. }
  685. /**
  686. * Delete a share (owner unShares the file)
  687. *
  688. * @param IShare $share
  689. */
  690. public function delete(IShare $share): void {
  691. try {
  692. $this->createShareActivity($share, 'unshare');
  693. } catch (\Exception $e) {
  694. }
  695. $this->removeShareFromTable((int)$share->getId());
  696. }
  697. /**
  698. * @inheritdoc
  699. */
  700. public function deleteFromSelf(IShare $share, $recipient): void {
  701. // nothing to do here, mail shares are only outgoing shares
  702. }
  703. public function restore(IShare $share, string $recipient): IShare {
  704. throw new GenericShareException('not implemented');
  705. }
  706. /**
  707. * @inheritdoc
  708. */
  709. public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset): array {
  710. $qb = $this->dbConnection->getQueryBuilder();
  711. $qb->select('*')
  712. ->from('share');
  713. $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)));
  714. /**
  715. * Reshares for this user are shares where they are the owner.
  716. */
  717. if ($reshares === false) {
  718. //Special case for old shares created via the web UI
  719. $or1 = $qb->expr()->andX(
  720. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  721. $qb->expr()->isNull('uid_initiator')
  722. );
  723. $qb->andWhere(
  724. $qb->expr()->orX(
  725. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
  726. $or1
  727. )
  728. );
  729. } elseif ($node === null) {
  730. $qb->andWhere(
  731. $qb->expr()->orX(
  732. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  733. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  734. )
  735. );
  736. }
  737. if ($node !== null) {
  738. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  739. }
  740. if ($limit !== -1) {
  741. $qb->setMaxResults($limit);
  742. }
  743. $qb->setFirstResult($offset);
  744. $qb->orderBy('id');
  745. $cursor = $qb->executeQuery();
  746. $shares = [];
  747. while ($data = $cursor->fetch()) {
  748. $shares[] = $this->createShareObject($data);
  749. }
  750. $cursor->closeCursor();
  751. return $shares;
  752. }
  753. /**
  754. * @inheritdoc
  755. */
  756. public function getShareById($id, $recipientId = null): IShare {
  757. $qb = $this->dbConnection->getQueryBuilder();
  758. $qb->select('*')
  759. ->from('share')
  760. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  761. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)));
  762. $cursor = $qb->executeQuery();
  763. $data = $cursor->fetch();
  764. $cursor->closeCursor();
  765. if ($data === false) {
  766. throw new ShareNotFound();
  767. }
  768. try {
  769. $share = $this->createShareObject($data);
  770. } catch (InvalidShare $e) {
  771. throw new ShareNotFound();
  772. }
  773. return $share;
  774. }
  775. /**
  776. * Get shares for a given path
  777. *
  778. * @return IShare[]
  779. */
  780. public function getSharesByPath(Node $path): array {
  781. $qb = $this->dbConnection->getQueryBuilder();
  782. $cursor = $qb->select('*')
  783. ->from('share')
  784. ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
  785. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  786. ->executeQuery();
  787. $shares = [];
  788. while ($data = $cursor->fetch()) {
  789. $shares[] = $this->createShareObject($data);
  790. }
  791. $cursor->closeCursor();
  792. return $shares;
  793. }
  794. /**
  795. * @inheritdoc
  796. */
  797. public function getSharedWith($userId, $shareType, $node, $limit, $offset): array {
  798. /** @var IShare[] $shares */
  799. $shares = [];
  800. //Get shares directly with this user
  801. $qb = $this->dbConnection->getQueryBuilder();
  802. $qb->select('*')
  803. ->from('share');
  804. // Order by id
  805. $qb->orderBy('id');
  806. // Set limit and offset
  807. if ($limit !== -1) {
  808. $qb->setMaxResults($limit);
  809. }
  810. $qb->setFirstResult($offset);
  811. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)));
  812. $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
  813. // Filter by node if provided
  814. if ($node !== null) {
  815. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  816. }
  817. $cursor = $qb->executeQuery();
  818. while ($data = $cursor->fetch()) {
  819. $shares[] = $this->createShareObject($data);
  820. }
  821. $cursor->closeCursor();
  822. return $shares;
  823. }
  824. /**
  825. * Get a share by token
  826. *
  827. * @throws ShareNotFound
  828. */
  829. public function getShareByToken($token): IShare {
  830. $qb = $this->dbConnection->getQueryBuilder();
  831. $cursor = $qb->select('*')
  832. ->from('share')
  833. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  834. ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  835. ->executeQuery();
  836. $data = $cursor->fetch();
  837. if ($data === false) {
  838. throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
  839. }
  840. try {
  841. $share = $this->createShareObject($data);
  842. } catch (InvalidShare $e) {
  843. throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
  844. }
  845. return $share;
  846. }
  847. /**
  848. * remove share from table
  849. */
  850. protected function removeShareFromTable(int $shareId): void {
  851. $qb = $this->dbConnection->getQueryBuilder();
  852. $qb->delete('share')
  853. ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
  854. $qb->executeStatement();
  855. }
  856. /**
  857. * Create a share object from a database row
  858. *
  859. * @throws InvalidShare
  860. * @throws ShareNotFound
  861. */
  862. protected function createShareObject(array $data): IShare {
  863. $share = new Share($this->rootFolder, $this->userManager);
  864. $share->setId((int)$data['id'])
  865. ->setShareType((int)$data['share_type'])
  866. ->setPermissions((int)$data['permissions'])
  867. ->setTarget($data['file_target'])
  868. ->setMailSend((bool)$data['mail_send'])
  869. ->setNote($data['note'])
  870. ->setToken($data['token']);
  871. $shareTime = new \DateTime();
  872. $shareTime->setTimestamp((int)$data['stime']);
  873. $share->setShareTime($shareTime);
  874. $share->setSharedWith($data['share_with'] ?? '');
  875. $share->setPassword($data['password']);
  876. $passwordExpirationTime = \DateTime::createFromFormat('Y-m-d H:i:s', $data['password_expiration_time'] ?? '');
  877. $share->setPasswordExpirationTime($passwordExpirationTime !== false ? $passwordExpirationTime : null);
  878. $share->setLabel($data['label']);
  879. $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
  880. $share->setHideDownload((bool)$data['hide_download']);
  881. $share->setReminderSent((bool)$data['reminder_sent']);
  882. if ($data['uid_initiator'] !== null) {
  883. $share->setShareOwner($data['uid_owner']);
  884. $share->setSharedBy($data['uid_initiator']);
  885. } else {
  886. //OLD SHARE
  887. $share->setSharedBy($data['uid_owner']);
  888. $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
  889. $owner = $path->getOwner();
  890. $share->setShareOwner($owner->getUID());
  891. }
  892. if ($data['expiration'] !== null) {
  893. $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
  894. if ($expiration !== false) {
  895. $share->setExpirationDate($expiration);
  896. }
  897. }
  898. $share = $this->updateShareAttributes($share, $data['attributes']);
  899. $share->setNodeId((int)$data['file_source']);
  900. $share->setNodeType($data['item_type']);
  901. $share->setProviderId($this->identifier());
  902. return $share;
  903. }
  904. /**
  905. * Get the node with file $id for $user
  906. *
  907. * @throws InvalidShare
  908. */
  909. private function getNode(string $userId, int $id): Node {
  910. try {
  911. $userFolder = $this->rootFolder->getUserFolder($userId);
  912. } catch (NoUserException $e) {
  913. throw new InvalidShare();
  914. }
  915. $nodes = $userFolder->getById($id);
  916. if (empty($nodes)) {
  917. throw new InvalidShare();
  918. }
  919. return $nodes[0];
  920. }
  921. /**
  922. * A user is deleted from the system
  923. * So clean up the relevant shares.
  924. */
  925. public function userDeleted($uid, $shareType): void {
  926. $qb = $this->dbConnection->getQueryBuilder();
  927. $qb->delete('share')
  928. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  929. ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
  930. ->executeStatement();
  931. }
  932. /**
  933. * This provider does not support group shares
  934. */
  935. public function groupDeleted($gid): void {
  936. }
  937. /**
  938. * This provider does not support group shares
  939. */
  940. public function userDeletedFromGroup($uid, $gid): void {
  941. }
  942. /**
  943. * get database row of a give share
  944. *
  945. * @throws ShareNotFound
  946. */
  947. protected function getRawShare(int $id): array {
  948. // Now fetch the inserted share and create a complete share object
  949. $qb = $this->dbConnection->getQueryBuilder();
  950. $qb->select('*')
  951. ->from('share')
  952. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
  953. $cursor = $qb->executeQuery();
  954. $data = $cursor->fetch();
  955. $cursor->closeCursor();
  956. if ($data === false) {
  957. throw new ShareNotFound;
  958. }
  959. return $data;
  960. }
  961. public function getSharesInFolder($userId, Folder $node, $reshares, $shallow = true): array {
  962. $qb = $this->dbConnection->getQueryBuilder();
  963. $qb->select('*')
  964. ->from('share', 's')
  965. ->andWhere($qb->expr()->orX(
  966. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  967. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  968. ))
  969. ->andWhere(
  970. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL))
  971. );
  972. /**
  973. * Reshares for this user are shares where they are the owner.
  974. */
  975. if ($reshares === false) {
  976. $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
  977. } else {
  978. $qb->andWhere(
  979. $qb->expr()->orX(
  980. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  981. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  982. )
  983. );
  984. }
  985. $qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
  986. $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
  987. $qb->orderBy('id');
  988. $cursor = $qb->executeQuery();
  989. $shares = [];
  990. while ($data = $cursor->fetch()) {
  991. $shares[$data['fileid']][] = $this->createShareObject($data);
  992. }
  993. $cursor->closeCursor();
  994. return $shares;
  995. }
  996. /**
  997. * @inheritdoc
  998. */
  999. public function getAccessList($nodes, $currentAccess): array {
  1000. $ids = [];
  1001. foreach ($nodes as $node) {
  1002. $ids[] = $node->getId();
  1003. }
  1004. $qb = $this->dbConnection->getQueryBuilder();
  1005. $qb->select('share_with', 'file_source', 'token')
  1006. ->from('share')
  1007. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  1008. ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
  1009. ->andWhere($qb->expr()->orX(
  1010. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  1011. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  1012. ));
  1013. $cursor = $qb->executeQuery();
  1014. $public = false;
  1015. $mail = [];
  1016. while ($row = $cursor->fetch()) {
  1017. $public = true;
  1018. if ($currentAccess === false) {
  1019. $mail[] = $row['share_with'];
  1020. } else {
  1021. $mail[$row['share_with']] = [
  1022. 'node_id' => $row['file_source'],
  1023. 'token' => $row['token']
  1024. ];
  1025. }
  1026. }
  1027. $cursor->closeCursor();
  1028. return ['public' => $public, 'mail' => $mail];
  1029. }
  1030. public function getAllShares(): iterable {
  1031. $qb = $this->dbConnection->getQueryBuilder();
  1032. $qb->select('*')
  1033. ->from('share')
  1034. ->where(
  1035. $qb->expr()->orX(
  1036. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL))
  1037. )
  1038. );
  1039. $cursor = $qb->executeQuery();
  1040. while ($data = $cursor->fetch()) {
  1041. try {
  1042. $share = $this->createShareObject($data);
  1043. } catch (InvalidShare $e) {
  1044. continue;
  1045. } catch (ShareNotFound $e) {
  1046. continue;
  1047. }
  1048. yield $share;
  1049. }
  1050. $cursor->closeCursor();
  1051. }
  1052. /**
  1053. * Extract the emails from the share
  1054. * It can be a single email, from the share_with field
  1055. * or a list of emails from the emails attributes field.
  1056. * @param IShare $share
  1057. * @return string[]
  1058. */
  1059. protected function getSharedWithEmails(IShare $share): array {
  1060. $attributes = $share->getAttributes();
  1061. if ($attributes === null) {
  1062. return [$share->getSharedWith()];
  1063. }
  1064. $emails = $attributes->getAttribute('shareWith', 'emails');
  1065. if (isset($emails) && is_array($emails) && !empty($emails)) {
  1066. return $emails;
  1067. }
  1068. return [$share->getSharedWith()];
  1069. }
  1070. }